Merge "Convert extension functions to regular functions." into main
diff --git a/PACKAGE_MANAGER_OWNERS b/PACKAGE_MANAGER_OWNERS
index eb5842b..45719a7 100644
--- a/PACKAGE_MANAGER_OWNERS
+++ b/PACKAGE_MANAGER_OWNERS
@@ -1,3 +1,6 @@
+# Bug component: 36137
+# Bug template url: https://b.corp.google.com/issues/new?component=36137&template=198919
+
alexbuy@google.com
patb@google.com
schfan@google.com
\ No newline at end of file
diff --git a/api/Android.bp b/api/Android.bp
index 8e06366..093ee4b 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -298,6 +298,28 @@
"org.xmlpull",
]
+// These are libs from framework-internal-utils that are required (i.e. being referenced)
+// from framework-non-updatable-sources. Add more here when there's a need.
+// DO NOT add the entire framework-internal-utils. It might cause unnecessary circular
+// dependencies gets bigger.
+android_non_updatable_stubs_libs = [
+ "android.hardware.cas-V1.2-java",
+ "android.hardware.health-V1.0-java-constants",
+ "android.hardware.thermal-V1.0-java-constants",
+ "android.hardware.thermal-V2.0-java",
+ "android.hardware.tv.input-V1.0-java-constants",
+ "android.hardware.usb-V1.0-java-constants",
+ "android.hardware.usb-V1.1-java-constants",
+ "android.hardware.usb.gadget-V1.0-java",
+ "android.hardware.vibrator-V1.3-java",
+ "framework-protos",
+]
+
+java_defaults {
+ name: "android-non-updatable-stubs-libs-defaults",
+ libs: android_non_updatable_stubs_libs,
+}
+
// Defaults for all stubs that include the non-updatable framework. These defaults do not include
// module symbols, so will not compile correctly on their own. Users must add module APIs to the
// classpath (or sources) somehow.
@@ -329,18 +351,7 @@
// from framework-non-updatable-sources. Add more here when there's a need.
// DO NOT add the entire framework-internal-utils. It might cause unnecessary circular
// dependencies gets bigger.
- libs: [
- "android.hardware.cas-V1.2-java",
- "android.hardware.health-V1.0-java-constants",
- "android.hardware.thermal-V1.0-java-constants",
- "android.hardware.thermal-V2.0-java",
- "android.hardware.tv.input-V1.0-java-constants",
- "android.hardware.usb-V1.0-java-constants",
- "android.hardware.usb-V1.1-java-constants",
- "android.hardware.usb.gadget-V1.0-java",
- "android.hardware.vibrator-V1.3-java",
- "framework-protos",
- ],
+ libs: android_non_updatable_stubs_libs,
flags: [
"--error NoSettingsProvider",
"--error UnhiddenSystemApi",
diff --git a/core/api/current.txt b/core/api/current.txt
index 7e33bfb..cd9c3ad 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -5395,7 +5395,7 @@
public final class AutomaticZenRule implements android.os.Parcelable {
ctor @Deprecated public AutomaticZenRule(String, android.content.ComponentName, android.net.Uri, int, boolean);
- ctor public AutomaticZenRule(@NonNull String, @Nullable android.content.ComponentName, @Nullable android.content.ComponentName, @NonNull android.net.Uri, @Nullable android.service.notification.ZenPolicy, int, boolean);
+ ctor @Deprecated public AutomaticZenRule(@NonNull String, @Nullable android.content.ComponentName, @Nullable android.content.ComponentName, @NonNull android.net.Uri, @Nullable android.service.notification.ZenPolicy, int, boolean);
ctor public AutomaticZenRule(android.os.Parcel);
method public int describeContents();
method public android.net.Uri getConditionId();
@@ -6674,9 +6674,9 @@
method @Deprecated public android.app.Notification.Builder addPerson(String);
method @NonNull public android.app.Notification.Builder addPerson(android.app.Person);
method @NonNull public android.app.Notification build();
- method public android.widget.RemoteViews createBigContentView();
- method public android.widget.RemoteViews createContentView();
- method public android.widget.RemoteViews createHeadsUpContentView();
+ method @Deprecated public android.widget.RemoteViews createBigContentView();
+ method @Deprecated public android.widget.RemoteViews createContentView();
+ method @Deprecated public android.widget.RemoteViews createHeadsUpContentView();
method @NonNull public android.app.Notification.Builder extend(android.app.Notification.Extender);
method public android.os.Bundle getExtras();
method @Deprecated public android.app.Notification getNotification();
@@ -15708,7 +15708,7 @@
method public boolean clipRect(int, int, int, int);
method @FlaggedApi("com.android.graphics.hwui.flags.clip_shader") public void clipShader(@NonNull android.graphics.Shader);
method public void concat(@Nullable android.graphics.Matrix);
- method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void concat44(@Nullable android.graphics.Matrix44);
+ method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void concat(@Nullable android.graphics.Matrix44);
method public void disableZ();
method public void drawARGB(int, int, int, int);
method public void drawArc(@NonNull android.graphics.RectF, float, float, boolean, @NonNull android.graphics.Paint);
@@ -16361,7 +16361,7 @@
ctor @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public Matrix44();
ctor @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public Matrix44(@NonNull android.graphics.Matrix);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") @NonNull public android.graphics.Matrix44 concat(@NonNull android.graphics.Matrix44);
- method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public float get(int, int);
+ method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public float get(@IntRange(from=0, to=3) int, @IntRange(from=0, to=3) int);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void getValues(@NonNull float[]);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public boolean invert();
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public boolean isIdentity();
@@ -16370,7 +16370,7 @@
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void reset();
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") @NonNull public android.graphics.Matrix44 rotate(float, float, float, float);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") @NonNull public android.graphics.Matrix44 scale(float, float, float);
- method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void set(int, int, float);
+ method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void set(@IntRange(from=0, to=3) int, @IntRange(from=0, to=3) int, float);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") public void setValues(@NonNull float[]);
method @FlaggedApi("com.android.graphics.hwui.flags.matrix_44") @NonNull public android.graphics.Matrix44 translate(float, float, float);
}
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index adc7ef1..ee69ce1 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -70,7 +70,7 @@
field public static final String BIND_NETWORK_RECOMMENDATION_SERVICE = "android.permission.BIND_NETWORK_RECOMMENDATION_SERVICE";
field public static final String BIND_NOTIFICATION_ASSISTANT_SERVICE = "android.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE";
field @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public static final String BIND_ON_DEVICE_INTELLIGENCE_SERVICE = "android.permission.BIND_ON_DEVICE_INTELLIGENCE_SERVICE";
- field @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public static final String BIND_ON_DEVICE_TRUSTED_SERVICE = "android.permission.BIND_ON_DEVICE_TRUSTED_SERVICE";
+ field @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public static final String BIND_ON_DEVICE_SANDBOXED_INFERENCE_SERVICE = "android.permission.BIND_ON_DEVICE_SANDBOXED_INFERENCE_SERVICE";
field public static final String BIND_PHONE_ACCOUNT_SUGGESTION_SERVICE = "android.permission.BIND_PHONE_ACCOUNT_SUGGESTION_SERVICE";
field public static final String BIND_PRINT_RECOMMENDATION_SERVICE = "android.permission.BIND_PRINT_RECOMMENDATION_SERVICE";
field public static final String BIND_REMOTE_LOCKSCREEN_VALIDATION_SERVICE = "android.permission.BIND_REMOTE_LOCKSCREEN_VALIDATION_SERVICE";
@@ -2223,10 +2223,9 @@
}
public static final class Feature.Builder {
- ctor public Feature.Builder(int, int, int, @NonNull android.os.PersistableBundle);
+ ctor public Feature.Builder(int);
method @NonNull public android.app.ondeviceintelligence.Feature build();
method @NonNull public android.app.ondeviceintelligence.Feature.Builder setFeatureParams(@NonNull android.os.PersistableBundle);
- method @NonNull public android.app.ondeviceintelligence.Feature.Builder setId(int);
method @NonNull public android.app.ondeviceintelligence.Feature.Builder setModelName(@NonNull String);
method @NonNull public android.app.ondeviceintelligence.Feature.Builder setName(@NonNull String);
method @NonNull public android.app.ondeviceintelligence.Feature.Builder setType(int);
@@ -2238,7 +2237,7 @@
ctor public FeatureDetails(@android.app.ondeviceintelligence.FeatureDetails.Status int);
method public int describeContents();
method @NonNull public android.os.PersistableBundle getFeatureDetailParams();
- method @android.app.ondeviceintelligence.FeatureDetails.Status public int getStatus();
+ method @android.app.ondeviceintelligence.FeatureDetails.Status public int getFeatureStatus();
method public void writeToParcel(@NonNull android.os.Parcel, int);
field @NonNull public static final android.os.Parcelable.Creator<android.app.ondeviceintelligence.FeatureDetails> CREATOR;
field public static final int FEATURE_STATUS_AVAILABLE = 3; // 0x3
@@ -2251,27 +2250,16 @@
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE) @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE_USE, java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.PARAMETER, java.lang.annotation.ElementType.FIELD}) public static @interface FeatureDetails.Status {
}
- @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public final class FilePart implements android.os.Parcelable {
- ctor public FilePart(@NonNull String, @NonNull android.os.PersistableBundle, @NonNull String) throws java.io.FileNotFoundException;
- ctor public FilePart(@NonNull String, @NonNull android.os.PersistableBundle, @NonNull java.io.FileInputStream) throws java.io.IOException;
- method public int describeContents();
- method @NonNull public java.io.FileInputStream getFileInputStream();
- method @NonNull public String getFilePartKey();
- method @NonNull public android.os.PersistableBundle getFilePartParams();
- method public void writeToParcel(@NonNull android.os.Parcel, int);
- field @NonNull public static final android.os.Parcelable.Creator<android.app.ondeviceintelligence.FilePart> CREATOR;
- }
-
@FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public class OnDeviceIntelligenceManager {
method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void getFeature(int, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.Feature,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void getFeatureDetails(@NonNull android.app.ondeviceintelligence.Feature, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.FeatureDetails,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
+ method @Nullable @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public String getRemoteServicePackageName();
method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void getVersion(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.LongConsumer);
method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void listFeatures(@NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.util.List<android.app.ondeviceintelligence.Feature>,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
- method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void processRequest(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
- method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void processRequestStreaming(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull java.util.concurrent.Executor, @NonNull android.app.ondeviceintelligence.StreamingResponseReceiver<android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
+ method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void processRequest(@NonNull android.app.ondeviceintelligence.Feature, @Nullable android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull java.util.concurrent.Executor, @NonNull android.app.ondeviceintelligence.ProcessingOutcomeReceiver);
+ method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void processRequestStreaming(@NonNull android.app.ondeviceintelligence.Feature, @Nullable android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull java.util.concurrent.Executor, @NonNull android.app.ondeviceintelligence.StreamedProcessingOutcomeReceiver);
method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void requestFeatureDownload(@NonNull android.app.ondeviceintelligence.Feature, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.app.ondeviceintelligence.DownloadCallback);
- method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void requestTokenCount(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Long,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
- field public static final String API_VERSION_BUNDLE_KEY = "ApiVersionBundleKey";
+ method @RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE) public void requestTokenInfo(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, @Nullable android.os.CancellationSignal, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.TokenInfo,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
field public static final int REQUEST_TYPE_EMBEDDINGS = 2; // 0x2
field public static final int REQUEST_TYPE_INFERENCE = 0; // 0x0
field public static final int REQUEST_TYPE_PREPARE = 1; // 0x1
@@ -2305,6 +2293,10 @@
field public static final int PROCESSING_ERROR_UNKNOWN = 1; // 0x1
}
+ @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public interface ProcessingOutcomeReceiver extends android.os.OutcomeReceiver<android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> {
+ method public default void onDataAugmentRequest(@NonNull android.app.ondeviceintelligence.Content, @NonNull java.util.function.Consumer<android.app.ondeviceintelligence.Content>);
+ }
+
@FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public final class ProcessingSignal {
ctor public ProcessingSignal();
method public void sendSignal(@NonNull android.os.PersistableBundle);
@@ -2315,8 +2307,18 @@
method public void onSignalReceived(@NonNull android.os.PersistableBundle);
}
- @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public interface StreamingResponseReceiver<R, T, E extends java.lang.Throwable> extends android.os.OutcomeReceiver<R,E> {
- method public void onNewContent(@NonNull T);
+ @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public interface StreamedProcessingOutcomeReceiver extends android.app.ondeviceintelligence.ProcessingOutcomeReceiver {
+ method public void onNewContent(@NonNull android.app.ondeviceintelligence.Content);
+ }
+
+ @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public final class TokenInfo implements android.os.Parcelable {
+ ctor public TokenInfo(long, @NonNull android.os.PersistableBundle);
+ ctor public TokenInfo(long);
+ method public int describeContents();
+ method public long getCount();
+ method @NonNull public android.os.PersistableBundle getInfoParams();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.app.ondeviceintelligence.TokenInfo> CREATOR;
}
}
@@ -12963,12 +12965,14 @@
@FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public abstract class OnDeviceIntelligenceService extends android.app.Service {
ctor public OnDeviceIntelligenceService();
method @Nullable public final android.os.IBinder onBind(@NonNull android.content.Intent);
- method public abstract void onDownloadFeature(@NonNull android.app.ondeviceintelligence.Feature, @Nullable android.os.CancellationSignal, @NonNull android.app.ondeviceintelligence.DownloadCallback);
- method public abstract void onGetFeature(int, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.Feature,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
- method public abstract void onGetFeatureDetails(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.FeatureDetails,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
+ method public abstract void onDownloadFeature(int, @NonNull android.app.ondeviceintelligence.Feature, @Nullable android.os.CancellationSignal, @NonNull android.app.ondeviceintelligence.DownloadCallback);
+ method public abstract void onGetFeature(int, int, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.Feature,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
+ method public abstract void onGetFeatureDetails(int, @NonNull android.app.ondeviceintelligence.Feature, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.FeatureDetails,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
method public abstract void onGetReadOnlyFeatureFileDescriptorMap(@NonNull android.app.ondeviceintelligence.Feature, @NonNull java.util.function.Consumer<java.util.Map<java.lang.String,android.os.ParcelFileDescriptor>>);
method public abstract void onGetVersion(@NonNull java.util.function.LongConsumer);
- method public abstract void onListFeatures(@NonNull android.os.OutcomeReceiver<java.util.List<android.app.ondeviceintelligence.Feature>,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
+ method public abstract void onInferenceServiceConnected();
+ method public abstract void onInferenceServiceDisconnected();
+ method public abstract void onListFeatures(int, @NonNull android.os.OutcomeReceiver<java.util.List<android.app.ondeviceintelligence.Feature>,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException>);
method public final void updateProcessingState(@NonNull android.os.Bundle, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.os.PersistableBundle,android.service.ondeviceintelligence.OnDeviceIntelligenceService.OnDeviceUpdateProcessingException>);
field public static final String SERVICE_INTERFACE = "android.service.ondeviceintelligence.OnDeviceIntelligenceService";
}
@@ -12985,17 +12989,18 @@
field public static final int PROCESSING_UPDATE_STATUS_CONNECTION_FAILED = 1; // 0x1
}
- @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public abstract class OnDeviceTrustedInferenceService extends android.app.Service {
- ctor public OnDeviceTrustedInferenceService();
+ @FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence") public abstract class OnDeviceSandboxedInferenceService extends android.app.Service {
+ ctor public OnDeviceSandboxedInferenceService();
method public final void fetchFeatureFileInputStreamMap(@NonNull android.app.ondeviceintelligence.Feature, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.util.Map<java.lang.String,java.io.FileInputStream>>);
+ method @NonNull public java.util.concurrent.Executor getCallbackExecutor();
method @Nullable public final android.os.IBinder onBind(@NonNull android.content.Intent);
- method @NonNull public abstract void onCountTokens(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, @Nullable android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<java.lang.Long,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
- method @NonNull public abstract void onProcessRequest(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
- method @NonNull public abstract void onProcessRequestStreaming(@NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull android.app.ondeviceintelligence.StreamingResponseReceiver<android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.Content,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
+ method @NonNull public abstract void onProcessRequest(int, @NonNull android.app.ondeviceintelligence.Feature, @Nullable android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull android.app.ondeviceintelligence.ProcessingOutcomeReceiver);
+ method @NonNull public abstract void onProcessRequestStreaming(int, @NonNull android.app.ondeviceintelligence.Feature, @Nullable android.app.ondeviceintelligence.Content, int, @Nullable android.os.CancellationSignal, @Nullable android.app.ondeviceintelligence.ProcessingSignal, @NonNull android.app.ondeviceintelligence.StreamedProcessingOutcomeReceiver);
+ method @NonNull public abstract void onTokenInfoRequest(int, @NonNull android.app.ondeviceintelligence.Feature, @NonNull android.app.ondeviceintelligence.Content, @Nullable android.os.CancellationSignal, @NonNull android.os.OutcomeReceiver<android.app.ondeviceintelligence.TokenInfo,android.app.ondeviceintelligence.OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException>);
method public abstract void onUpdateProcessingState(@NonNull android.os.Bundle, @NonNull android.os.OutcomeReceiver<android.os.PersistableBundle,android.service.ondeviceintelligence.OnDeviceIntelligenceService.OnDeviceUpdateProcessingException>);
method public final java.io.FileInputStream openFileInput(@NonNull String) throws java.io.FileNotFoundException;
method public final void openFileInputAsync(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.io.FileInputStream>) throws java.io.FileNotFoundException;
- field public static final String SERVICE_INTERFACE = "android.service.ondeviceintelligence.OnDeviceTrustedInferenceService";
+ field public static final String SERVICE_INTERFACE = "android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService";
}
}
diff --git a/core/api/system-lint-baseline.txt b/core/api/system-lint-baseline.txt
index 1923641..1e72a06 100644
--- a/core/api/system-lint-baseline.txt
+++ b/core/api/system-lint-baseline.txt
@@ -511,9 +511,9 @@
InvalidNullabilityOverride: android.service.ondeviceintelligence.OnDeviceIntelligenceService#onBind(android.content.Intent) parameter #0:
Invalid nullability on parameter `intent` in method `onBind`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: android.service.ondeviceintelligence.OnDeviceTrustedInferenceService#onBind(android.content.Intent) parameter #0:
+InvalidNullabilityOverride: android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService#onBind(android.content.Intent) parameter #0:
Invalid nullability on parameter `intent` in method `onBind`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
-InvalidNullabilityOverride: android.service.ondeviceintelligence.OnDeviceTrustedInferenceService#openFileInput(String) parameter #0:
+InvalidNullabilityOverride: android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService#openFileInput(String) parameter #0:
Invalid nullability on parameter `filename` in method `openFileInput`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
InvalidNullabilityOverride: android.service.textclassifier.TextClassifierService#onUnbind(android.content.Intent) parameter #0:
Invalid nullability on parameter `intent` in method `onUnbind`. Parameters of overrides cannot be NonNull if the super parameter is unannotated.
@@ -571,7 +571,7 @@
Missing nullability on parameter `args` in method `dump`
MissingNullability: android.service.notification.NotificationAssistantService#attachBaseContext(android.content.Context) parameter #0:
Missing nullability on parameter `base` in method `attachBaseContext`
-MissingNullability: android.service.ondeviceintelligence.OnDeviceTrustedInferenceService#openFileInput(String):
+MissingNullability: android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService#openFileInput(String):
Missing nullability on method `openFileInput` return
MissingNullability: android.telephony.NetworkService#onUnbind(android.content.Intent) parameter #0:
Missing nullability on parameter `intent` in method `onUnbind`
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index f6ec370..5e2397d 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -173,8 +173,8 @@
* interrupt the user (e.g. via sound & vibration) while this rule
* is active.
* @param enabled Whether the rule is enabled.
- * @deprecated use {@link #AutomaticZenRule(String, ComponentName, ComponentName, Uri,
- * ZenPolicy, int, boolean)}.
+ *
+ * @deprecated Use {@link AutomaticZenRule.Builder} to construct an {@link AutomaticZenRule}.
*/
@Deprecated
public AutomaticZenRule(String name, ComponentName owner, Uri conditionId,
@@ -206,8 +206,10 @@
* while this rule is active. This overrides the global policy while this rule is
* action ({@link Condition#STATE_TRUE}).
* @param enabled Whether the rule is enabled.
+ *
+ * @deprecated Use {@link AutomaticZenRule.Builder} to construct an {@link AutomaticZenRule}.
*/
- // TODO (b/309088420): deprecate this constructor in favor of the builder
+ @Deprecated
public AutomaticZenRule(@NonNull String name, @Nullable ComponentName owner,
@Nullable ComponentName configurationActivity, @NonNull Uri conditionId,
@Nullable ZenPolicy policy, int interruptionFilter, boolean enabled) {
@@ -368,6 +370,9 @@
/**
* Sets the zen policy.
+ *
+ * <p>When updating an existing rule via {@link NotificationManager#updateAutomaticZenRule},
+ * a {@code null} value here means the previous policy is retained.
*/
public void setZenPolicy(@Nullable ZenPolicy zenPolicy) {
this.mZenPolicy = (zenPolicy == null ? null : zenPolicy.copy());
@@ -390,7 +395,12 @@
* Sets the configuration activity - an activity that handles
* {@link NotificationManager#ACTION_AUTOMATIC_ZEN_RULE} that shows the user more information
* about this rule and/or allows them to configure it. This is required to be non-null for rules
- * that are not backed by {@link android.service.notification.ConditionProviderService}.
+ * that are not backed by a {@link android.service.notification.ConditionProviderService}.
+ *
+ * <p>This is exclusive with the {@code owner} supplied in the constructor; rules where a
+ * configuration activity is set will not use the
+ * {@link android.service.notification.ConditionProviderService} supplied there to determine
+ * whether the rule should be active.
*/
public void setConfigurationActivity(@Nullable ComponentName componentName) {
this.configurationActivity = getTrimmedComponentName(componentName);
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index 1129f9d..79cb09d 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -6068,11 +6068,19 @@
}
/**
- * Construct a RemoteViews for the final 1U notification layout. In order:
- * 1. Custom contentView from the caller
- * 2. Style's proposed content view
- * 3. Standard template view
+ * Construct a RemoteViews representing the standard notification layout.
+ *
+ * @deprecated For performance and system health reasons, this API is no longer required to
+ * be used directly by the System UI when rendering Notifications to the user. While the UI
+ * returned by this method will still represent the content of the Notification being
+ * built, it may differ from the visual style of the system.
+ *
+ * NOTE: this API has always had severe limitations; for example it does not support any
+ * interactivity, it ignores the app theme, it hard-codes the colors from the system theme
+ * at the time it is called, and it does Bitmap decoding on the main thread which can cause
+ * UI jank.
*/
+ @Deprecated
public RemoteViews createContentView() {
return createContentView(false /* increasedheight */ );
}
@@ -6181,8 +6189,19 @@
}
/**
- * Construct a RemoteViews for the final big notification layout.
+ * Construct a RemoteViews representing the expanded notification layout.
+ *
+ * @deprecated For performance and system health reasons, this API is no longer required to
+ * be used directly by the System UI when rendering Notifications to the user. While the UI
+ * returned by this method will still represent the content of the Notification being
+ * built, it may differ from the visual style of the system.
+ *
+ * NOTE: this API has always had severe limitations; for example it does not support any
+ * interactivity, it ignores the app theme, it hard-codes the colors from the system theme
+ * at the time it is called, and it does Bitmap decoding on the main thread which can cause
+ * UI jank.
*/
+ @Deprecated
public RemoteViews createBigContentView() {
RemoteViews result = null;
if (useExistingRemoteView(mN.bigContentView)) {
@@ -6315,8 +6334,19 @@
}
/**
- * Construct a RemoteViews for the final heads-up notification layout.
+ * Construct a RemoteViews representing the heads up notification layout.
+ *
+ * @deprecated For performance and system health reasons, this API is no longer required to
+ * be used directly by the System UI when rendering Notifications to the user. While the UI
+ * returned by this method will still represent the content of the Notification being
+ * built, it may differ from the visual style of the system.
+ *
+ * NOTE: this API has always had severe limitations; for example it does not support any
+ * interactivity, it ignores the app theme, it hard-codes the colors from the system theme
+ * at the time it is called, and it does Bitmap decoding on the main thread which can cause
+ * UI jank.
*/
+ @Deprecated
public RemoteViews createHeadsUpContentView() {
return createHeadsUpContentView(false /* useIncreasedHeight */);
}
diff --git a/core/java/android/app/NotificationManager.java b/core/java/android/app/NotificationManager.java
index 283e21a..b82a1e3 100644
--- a/core/java/android/app/NotificationManager.java
+++ b/core/java/android/app/NotificationManager.java
@@ -270,13 +270,16 @@
* Integer extra for {@link #ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED} containing the state of
* the {@link AutomaticZenRule}.
*
- * <p>
- * The value will be one of {@link #AUTOMATIC_RULE_STATUS_ENABLED},
- * {@link #AUTOMATIC_RULE_STATUS_DISABLED}, {@link #AUTOMATIC_RULE_STATUS_REMOVED},
- * {@link #AUTOMATIC_RULE_STATUS_UNKNOWN}.
- * </p>
+ * <p>The value will be one of {@link #AUTOMATIC_RULE_STATUS_ENABLED},
+ * {@link #AUTOMATIC_RULE_STATUS_DISABLED}, {@link #AUTOMATIC_RULE_STATUS_REMOVED},
+ * {@link #AUTOMATIC_RULE_STATUS_ACTIVATED}, {@link #AUTOMATIC_RULE_STATUS_DEACTIVATED}, or
+ * {@link #AUTOMATIC_RULE_STATUS_UNKNOWN}.
+ *
+ * <p>Note that the {@link #AUTOMATIC_RULE_STATUS_ACTIVATED} and
+ * {@link #AUTOMATIC_RULE_STATUS_DEACTIVATED} statuses are only sent to packages targeting
+ * {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above; apps targeting a lower SDK version
+ * will be sent {@link #AUTOMATIC_RULE_STATUS_UNKNOWN} in their place instead.
*/
- // TODO (b/309101513): Add new status types to javadoc
public static final String EXTRA_AUTOMATIC_ZEN_RULE_STATUS =
"android.app.extra.AUTOMATIC_ZEN_RULE_STATUS";
@@ -370,11 +373,15 @@
= "android.app.action.NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED";
/**
- * Intent that is broadcast when the state of getNotificationPolicy() changes.
+ * Intent that is broadcast when the state of {@link #getNotificationPolicy()} changes.
*
* <p>This broadcast is only sent to registered receivers and (starting from
* {@link Build.VERSION_CODES#Q}) receivers in packages that have been granted Do Not
* Disturb access (see {@link #isNotificationPolicyAccessGranted()}).
+ *
+ * <p>Starting with {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, most calls to
+ * {@link #setNotificationPolicy(Policy)} will update the app's implicit rule policy instead of
+ * the global policy, so this broadcast will be sent much less frequently.
*/
@SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String ACTION_NOTIFICATION_POLICY_CHANGED
@@ -1378,12 +1385,16 @@
/**
* Updates the given zen rule.
*
- * <p>
- * Throws a SecurityException if policy access is not granted to this package.
+ * <p>Before {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, updating a rule that is not backed
+ * up by a {@link android.service.notification.ConditionProviderService} will deactivate it if
+ * it was previously active. Starting with {@link Build.VERSION_CODES#VANILLA_ICE_CREAM}, this
+ * will only happen if the rule's definition is actually changing.
+ *
+ * <p>Throws a SecurityException if policy access is not granted to this package.
* See {@link #isNotificationPolicyAccessGranted}.
*
- * <p>
- * Callers can only update rules that they own. See {@link AutomaticZenRule#getOwner}.
+ * <p>Callers can only update rules that they own. See {@link AutomaticZenRule#getOwner}.
+ *
* @param id The id of the rule to update
* @param automaticZenRule the rule to update.
* @return Whether the rule was successfully updated.
@@ -1744,9 +1755,11 @@
/**
* Gets the current user-specified default notification policy.
*
- * <p>
+ * <p>For apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above (with some
+ * exceptions, such as companion device managers) this method will return the policy associated
+ * to their implicit {@link AutomaticZenRule} instead, if it exists. See
+ * {@link #setNotificationPolicy(Policy)}.
*/
- // TODO(b/309457271): Update documentation with VANILLA_ICE_CREAM behavior.
public Policy getNotificationPolicy() {
INotificationManager service = getService();
try {
@@ -1757,15 +1770,20 @@
}
/**
- * Sets the current notification policy.
+ * Sets the current notification policy (which applies when {@link #setInterruptionFilter} is
+ * called with the {@link #INTERRUPTION_FILTER_PRIORITY} value).
*
- * <p>
- * Only available if policy access is granted to this package.
- * See {@link #isNotificationPolicyAccessGranted}.
+ * <p>Apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above (with some
+ * exceptions, such as companion device managers) cannot modify the global notification policy.
+ * Calling this method will instead create or update an {@link AutomaticZenRule} associated to
+ * the app, using a {@link ZenPolicy} corresponding to the {@link Policy} supplied here, and
+ * which will be activated/deactivated by calls to {@link #setInterruptionFilter(int)}.
+ *
+ * <p>Only available if policy access is granted to this package. See
+ * {@link #isNotificationPolicyAccessGranted}.
*
* @param policy The new desired policy.
*/
- // TODO(b/309457271): Update documentation with VANILLA_ICE_CREAM behavior.
public void setNotificationPolicy(@NonNull Policy policy) {
setNotificationPolicy(policy, /* fromUser= */ false);
}
@@ -2786,11 +2804,17 @@
* The interruption filter defines which notifications are allowed to
* interrupt the user (e.g. via sound & vibration) and is applied
* globally.
- * <p>
- * Only available if policy access is granted to this package. See
+ *
+ * <p>Apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above (with some
+ * exceptions, such as companion device managers) cannot modify the global interruption filter.
+ * Calling this method will instead activate or deactivate an {@link AutomaticZenRule}
+ * associated to the app, using a {@link ZenPolicy} that corresponds to the {@link Policy}
+ * supplied to {@link #setNotificationPolicy(Policy)} (or the global policy when one wasn't
+ * provided).
+ *
+ * <p> Only available if policy access is granted to this package. See
* {@link #isNotificationPolicyAccessGranted}.
*/
- // TODO(b/309457271): Update documentation with VANILLA_ICE_CREAM behavior.
public final void setInterruptionFilter(@InterruptionFilter int interruptionFilter) {
setInterruptionFilter(interruptionFilter, /* fromUser= */ false);
}
diff --git a/core/java/android/app/ondeviceintelligence/Feature.java b/core/java/android/app/ondeviceintelligence/Feature.java
index 5107354..4a38c92 100644
--- a/core/java/android/app/ondeviceintelligence/Feature.java
+++ b/core/java/android/app/ondeviceintelligence/Feature.java
@@ -199,24 +199,13 @@
private long mBuilderFieldsSet = 0L;
- public Builder(
- int id,
- int type,
- int variant,
- @NonNull PersistableBundle featureParams) {
+ /**
+ * Provides a builder instance to create a feature for given id.
+ * @param id the unique identifier for the feature.
+ */
+ public Builder(int id) {
mId = id;
- mType = type;
- mVariant = variant;
- mFeatureParams = featureParams;
- com.android.internal.util.AnnotationValidations.validate(
- NonNull.class, null, mFeatureParams);
- }
-
- public @NonNull Builder setId(int value) {
- checkNotUsed();
- mBuilderFieldsSet |= 0x1;
- mId = value;
- return this;
+ mFeatureParams = new PersistableBundle();
}
public @NonNull Builder setName(@NonNull String value) {
diff --git a/core/java/android/app/ondeviceintelligence/FeatureDetails.java b/core/java/android/app/ondeviceintelligence/FeatureDetails.java
index 92f3513..f3cbd26 100644
--- a/core/java/android/app/ondeviceintelligence/FeatureDetails.java
+++ b/core/java/android/app/ondeviceintelligence/FeatureDetails.java
@@ -41,7 +41,7 @@
@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
public final class FeatureDetails implements Parcelable {
@Status
- private final int mStatus;
+ private final int mFeatureStatus;
@NonNull
private final PersistableBundle mFeatureDetailParams;
@@ -73,21 +73,21 @@
}
public FeatureDetails(
- @Status int status,
+ @Status int featureStatus,
@NonNull PersistableBundle featureDetailParams) {
- this.mStatus = status;
+ this.mFeatureStatus = featureStatus;
com.android.internal.util.AnnotationValidations.validate(
- Status.class, null, mStatus);
+ Status.class, null, mFeatureStatus);
this.mFeatureDetailParams = featureDetailParams;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mFeatureDetailParams);
}
public FeatureDetails(
- @Status int status) {
- this.mStatus = status;
+ @Status int featureStatus) {
+ this.mFeatureStatus = featureStatus;
com.android.internal.util.AnnotationValidations.validate(
- Status.class, null, mStatus);
+ Status.class, null, mFeatureStatus);
this.mFeatureDetailParams = new PersistableBundle();
}
@@ -95,8 +95,8 @@
/**
* Returns an integer value associated with the feature status.
*/
- public @Status int getStatus() {
- return mStatus;
+ public @Status int getFeatureStatus() {
+ return mFeatureStatus;
}
@@ -111,7 +111,7 @@
public String toString() {
return MessageFormat.format("FeatureDetails '{' status = {0}, "
+ "persistableBundle = {1} '}'",
- mStatus,
+ mFeatureStatus,
mFeatureDetailParams);
}
@@ -121,21 +121,21 @@
if (o == null || getClass() != o.getClass()) return false;
@SuppressWarnings("unchecked")
FeatureDetails that = (FeatureDetails) o;
- return mStatus == that.mStatus
+ return mFeatureStatus == that.mFeatureStatus
&& java.util.Objects.equals(mFeatureDetailParams, that.mFeatureDetailParams);
}
@Override
public int hashCode() {
int _hash = 1;
- _hash = 31 * _hash + mStatus;
+ _hash = 31 * _hash + mFeatureStatus;
_hash = 31 * _hash + java.util.Objects.hashCode(mFeatureDetailParams);
return _hash;
}
@Override
public void writeToParcel(@NonNull android.os.Parcel dest, int flags) {
- dest.writeInt(mStatus);
+ dest.writeInt(mFeatureStatus);
dest.writeTypedObject(mFeatureDetailParams, flags);
}
@@ -151,9 +151,9 @@
PersistableBundle persistableBundle = (PersistableBundle) in.readTypedObject(
PersistableBundle.CREATOR);
- this.mStatus = status;
+ this.mFeatureStatus = status;
com.android.internal.util.AnnotationValidations.validate(
- Status.class, null, mStatus);
+ Status.class, null, mFeatureStatus);
this.mFeatureDetailParams = persistableBundle;
com.android.internal.util.AnnotationValidations.validate(
NonNull.class, null, mFeatureDetailParams);
diff --git a/core/java/android/app/ondeviceintelligence/FilePart.java b/core/java/android/app/ondeviceintelligence/FilePart.java
deleted file mode 100644
index e9fb5f2..0000000
--- a/core/java/android/app/ondeviceintelligence/FilePart.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app.ondeviceintelligence;
-
-import static android.app.ondeviceintelligence.flags.Flags.FLAG_ENABLE_ON_DEVICE_INTELLIGENCE;
-
-import android.annotation.FlaggedApi;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.ParcelFileDescriptor;
-import android.os.Parcelable;
-import android.os.PersistableBundle;
-
-import android.annotation.NonNull;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Objects;
-
-/**
- * Represents file data with an associated file descriptor sent to and received from remote
- * processing. The interface ensures that the underlying file-descriptor is always opened in
- * read-only mode.
- *
- * @hide
- */
-@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
-@SystemApi
-public final class FilePart implements Parcelable {
- private final String mPartKey;
- private final PersistableBundle mPartParams;
- private final ParcelFileDescriptor mParcelFileDescriptor;
-
- private FilePart(@NonNull String partKey, @NonNull PersistableBundle partParams,
- @NonNull ParcelFileDescriptor parcelFileDescriptor) {
- Objects.requireNonNull(partKey);
- Objects.requireNonNull(partParams);
- this.mPartKey = partKey;
- this.mPartParams = partParams;
- this.mParcelFileDescriptor = Objects.requireNonNull(parcelFileDescriptor);
- }
-
- /**
- * Create a file part using a filePath and any additional params.
- */
- public FilePart(@NonNull String partKey, @NonNull PersistableBundle partParams,
- @NonNull String filePath)
- throws FileNotFoundException {
- this(partKey, partParams, Objects.requireNonNull(ParcelFileDescriptor.open(
- new File(Objects.requireNonNull(filePath)), ParcelFileDescriptor.MODE_READ_ONLY)));
- }
-
- /**
- * Create a file part using a file input stream and any additional params.
- * It is the caller's responsibility to close the stream. It is safe to do so as soon as this
- * call returns.
- */
- public FilePart(@NonNull String partKey, @NonNull PersistableBundle partParams,
- @NonNull FileInputStream fileInputStream)
- throws IOException {
- this(partKey, partParams, ParcelFileDescriptor.dup(fileInputStream.getFD()));
- }
-
- /**
- * Returns a FileInputStream for the associated File.
- * Caller must close the associated stream when done reading from it.
- *
- * @return the FileInputStream associated with the FilePart.
- */
- @NonNull
- public FileInputStream getFileInputStream() {
- return new FileInputStream(mParcelFileDescriptor.getFileDescriptor());
- }
-
- /**
- * Returns the unique key associated with the part. Each Part key added to a content object
- * should be ensured to be unique.
- */
- @NonNull
- public String getFilePartKey() {
- return mPartKey;
- }
-
- /**
- * Returns the params associated with Part.
- */
- @NonNull
- public PersistableBundle getFilePartParams() {
- return mPartParams;
- }
-
-
- @Override
- public int describeContents() {
- return CONTENTS_FILE_DESCRIPTOR;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeString8(getFilePartKey());
- dest.writePersistableBundle(getFilePartParams());
- mParcelFileDescriptor.writeToParcel(dest, flags
- | Parcelable.PARCELABLE_WRITE_RETURN_VALUE); // This flag ensures that the sender's
- // copy of the Pfd is closed as soon as the Binder call succeeds.
- }
-
- @NonNull
- public static final Creator<FilePart> CREATOR = new Creator<>() {
- @Override
- public FilePart createFromParcel(Parcel in) {
- return new FilePart(in.readString(), in.readTypedObject(PersistableBundle.CREATOR),
- in.readParcelable(
- getClass().getClassLoader(), ParcelFileDescriptor.class));
- }
-
- @Override
- public FilePart[] newArray(int size) {
- return new FilePart[size];
- }
- };
-}
diff --git a/core/java/android/app/ondeviceintelligence/IOnDeviceIntelligenceManager.aidl b/core/java/android/app/ondeviceintelligence/IOnDeviceIntelligenceManager.aidl
index b925f48..360a809 100644
--- a/core/java/android/app/ondeviceintelligence/IOnDeviceIntelligenceManager.aidl
+++ b/core/java/android/app/ondeviceintelligence/IOnDeviceIntelligenceManager.aidl
@@ -31,7 +31,7 @@
import android.app.ondeviceintelligence.IResponseCallback;
import android.app.ondeviceintelligence.IStreamingResponseCallback;
import android.app.ondeviceintelligence.IProcessingSignal;
- import android.app.ondeviceintelligence.ITokenCountCallback;
+ import android.app.ondeviceintelligence.ITokenInfoCallback;
/**
@@ -56,8 +56,8 @@
void requestFeatureDownload(in Feature feature, ICancellationSignal signal, in IDownloadCallback callback) = 5;
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)")
- void requestTokenCount(in Feature feature, in Content request, in ICancellationSignal signal,
- in ITokenCountCallback tokenCountcallback) = 6;
+ void requestTokenInfo(in Feature feature, in Content request, in ICancellationSignal signal,
+ in ITokenInfoCallback tokenInfocallback) = 6;
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)")
void processRequest(in Feature feature, in Content request, int requestType, in ICancellationSignal cancellationSignal, in IProcessingSignal signal,
diff --git a/core/java/android/app/ondeviceintelligence/IResponseCallback.aidl b/core/java/android/app/ondeviceintelligence/IResponseCallback.aidl
index 9848e1d..0adf305 100644
--- a/core/java/android/app/ondeviceintelligence/IResponseCallback.aidl
+++ b/core/java/android/app/ondeviceintelligence/IResponseCallback.aidl
@@ -3,6 +3,7 @@
import android.app.ondeviceintelligence.Content;
import android.app.ondeviceintelligence.IProcessingSignal;
import android.os.PersistableBundle;
+import android.os.RemoteCallback;
/**
* Interface for a IResponseCallback for receiving response from on-device intelligence service.
@@ -12,4 +13,5 @@
interface IResponseCallback {
void onSuccess(in Content result) = 1;
void onFailure(int errorCode, in String errorMessage, in PersistableBundle errorParams) = 2;
+ void onDataAugmentRequest(in Content content, in RemoteCallback contentCallback) = 3;
}
diff --git a/core/java/android/app/ondeviceintelligence/IStreamingResponseCallback.aidl b/core/java/android/app/ondeviceintelligence/IStreamingResponseCallback.aidl
index a680574..132e53e 100644
--- a/core/java/android/app/ondeviceintelligence/IStreamingResponseCallback.aidl
+++ b/core/java/android/app/ondeviceintelligence/IStreamingResponseCallback.aidl
@@ -4,6 +4,7 @@
import android.app.ondeviceintelligence.IResponseCallback;
import android.app.ondeviceintelligence.IProcessingSignal;
import android.os.PersistableBundle;
+import android.os.RemoteCallback;
/**
@@ -15,4 +16,5 @@
void onNewContent(in Content result) = 1;
void onSuccess(in Content result) = 2;
void onFailure(int errorCode, in String errorMessage, in PersistableBundle errorParams) = 3;
+ void onDataAugmentRequest(in Content content, in RemoteCallback contentCallback) = 4;
}
diff --git a/core/java/android/app/ondeviceintelligence/ITokenCountCallback.aidl b/core/java/android/app/ondeviceintelligence/ITokenCountCallback.aidl
deleted file mode 100644
index b724e03..0000000
--- a/core/java/android/app/ondeviceintelligence/ITokenCountCallback.aidl
+++ /dev/null
@@ -1,13 +0,0 @@
-package android.app.ondeviceintelligence;
-
-import android.os.PersistableBundle;
-
-/**
- * Interface for receiving the token count of a request for a given features.
- *
- * @hide
- */
-interface ITokenCountCallback {
- void onSuccess(long tokenCount) = 1;
- void onFailure(int errorCode, in String errorMessage, in PersistableBundle errorParams) = 2;
-}
diff --git a/core/java/android/app/ondeviceintelligence/ITokenInfoCallback.aidl b/core/java/android/app/ondeviceintelligence/ITokenInfoCallback.aidl
new file mode 100644
index 0000000..9219a89
--- /dev/null
+++ b/core/java/android/app/ondeviceintelligence/ITokenInfoCallback.aidl
@@ -0,0 +1,14 @@
+package android.app.ondeviceintelligence;
+
+import android.os.PersistableBundle;
+import android.app.ondeviceintelligence.TokenInfo;
+
+/**
+ * Interface for receiving the token info of a request for a given feature.
+ *
+ * @hide
+ */
+interface ITokenInfoCallback {
+ void onSuccess(in TokenInfo tokenInfo) = 1;
+ void onFailure(int errorCode, in String errorMessage, in PersistableBundle errorParams) = 2;
+}
diff --git a/core/java/android/app/ondeviceintelligence/OnDeviceIntelligenceManager.java b/core/java/android/app/ondeviceintelligence/OnDeviceIntelligenceManager.java
index 4d8e0d5..d195c4d 100644
--- a/core/java/android/app/ondeviceintelligence/OnDeviceIntelligenceManager.java
+++ b/core/java/android/app/ondeviceintelligence/OnDeviceIntelligenceManager.java
@@ -26,8 +26,10 @@
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.annotation.SystemService;
+import android.content.ComponentName;
import android.content.Context;
import android.os.Binder;
+import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ICancellationSignal;
import android.os.OutcomeReceiver;
@@ -37,6 +39,8 @@
import androidx.annotation.IntDef;
+import com.android.internal.R;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -60,7 +64,16 @@
@SystemService(Context.ON_DEVICE_INTELLIGENCE_SERVICE)
@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
public class OnDeviceIntelligenceManager {
+ /**
+ * @hide
+ */
public static final String API_VERSION_BUNDLE_KEY = "ApiVersionBundleKey";
+
+ /**
+ * @hide
+ */
+ public static final String AUGMENT_REQUEST_CONTENT_BUNDLE_KEY =
+ "AugmentRequestContentBundleKey";
private final Context mContext;
private final IOnDeviceIntelligenceManager mService;
@@ -82,8 +95,6 @@
public void getVersion(
@NonNull @CallbackExecutor Executor callbackExecutor,
@NonNull LongConsumer versionConsumer) {
- // TODO explore modifying this method into getServicePackageDetails and return both
- // version and package name of the remote service implementing this.
try {
RemoteCallback callback = new RemoteCallback(result -> {
if (result == null) {
@@ -100,6 +111,23 @@
}
}
+
+ /**
+ * Get package name configured for providing the remote implementation for this system service.
+ */
+ @Nullable
+ @RequiresPermission(Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)
+ public String getRemoteServicePackageName() {
+ String serviceConfigValue = mContext.getResources().getString(
+ R.string.config_defaultOnDeviceSandboxedInferenceService);
+ ComponentName componentName = ComponentName.unflattenFromString(serviceConfigValue);
+ if (componentName != null) {
+ return componentName.getPackageName();
+ }
+
+ return null;
+ }
+
/**
* Asynchronously get feature for a given id.
*
@@ -273,29 +301,29 @@
}
/**
- * The methods computes the token-count for a given request payload using the provided Feature
- * details.
+ * The methods computes the token related information for a given request payload using the
+ * provided {@link Feature}.
*
* @param feature feature associated with the request.
* @param request request that contains the content data and associated params.
- * @param outcomeReceiver callback to populate the token count or exception in case of
+ * @param outcomeReceiver callback to populate the token info or exception in case of
* failure.
* @param cancellationSignal signal to invoke cancellation on the operation in the remote
* implementation.
* @param callbackExecutor executor to run the callback on.
*/
@RequiresPermission(Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)
- public void requestTokenCount(@NonNull Feature feature, @NonNull Content request,
+ public void requestTokenInfo(@NonNull Feature feature, @NonNull Content request,
@Nullable CancellationSignal cancellationSignal,
@NonNull @CallbackExecutor Executor callbackExecutor,
- @NonNull OutcomeReceiver<Long,
+ @NonNull OutcomeReceiver<TokenInfo,
OnDeviceIntelligenceManagerException> outcomeReceiver) {
try {
- ITokenCountCallback callback = new ITokenCountCallback.Stub() {
+ ITokenInfoCallback callback = new ITokenInfoCallback.Stub() {
@Override
- public void onSuccess(long tokenCount) {
+ public void onSuccess(TokenInfo tokenInfo) {
Binder.withCleanCallingIdentity(() -> callbackExecutor.execute(
- () -> outcomeReceiver.onResult(tokenCount)));
+ () -> outcomeReceiver.onResult(tokenInfo)));
}
@Override
@@ -314,7 +342,7 @@
cancellationSignal.setRemote(transport);
}
- mService.requestTokenCount(feature, request, transport, callback);
+ mService.requestTokenInfo(feature, request, transport, callback);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -328,33 +356,31 @@
* was a
* failure.
*
- * @param feature feature associated with the request.
- * @param request request that contains the Content data and
- * associated params.
- * @param requestType type of request being sent for processing the content.
- * @param responseOutcomeReceiver callback to populate the response content and
- * associated
- * params.
- * @param processingSignal signal to invoke custom actions in the
- * remote implementation.
- * @param cancellationSignal signal to invoke cancellation or
- * @param callbackExecutor executor to run the callback on.
+ * @param feature feature associated with the request.
+ * @param request request that contains the Content data and
+ * associated params.
+ * @param requestType type of request being sent for processing the content.
+ * @param cancellationSignal signal to invoke cancellation.
+ * @param processingSignal signal to send custom signals in the
+ * remote implementation.
+ * @param callbackExecutor executor to run the callback on.
+ * @param responseCallback callback to populate the response content and
+ * associated params.
*/
@RequiresPermission(Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)
- public void processRequest(@NonNull Feature feature, @NonNull Content request,
+ public void processRequest(@NonNull Feature feature, @Nullable Content request,
@RequestType int requestType,
@Nullable CancellationSignal cancellationSignal,
@Nullable ProcessingSignal processingSignal,
@NonNull @CallbackExecutor Executor callbackExecutor,
- @NonNull OutcomeReceiver<Content,
- OnDeviceIntelligenceManagerProcessingException> responseOutcomeReceiver) {
+ @NonNull ProcessingOutcomeReceiver responseCallback) {
try {
IResponseCallback callback = new IResponseCallback.Stub() {
@Override
public void onSuccess(Content result) {
Binder.withCleanCallingIdentity(() -> {
- callbackExecutor.execute(() -> responseOutcomeReceiver.onResult(result));
+ callbackExecutor.execute(() -> responseCallback.onResult(result));
});
}
@@ -362,12 +388,24 @@
public void onFailure(int errorCode, String errorMessage,
PersistableBundle errorParams) {
Binder.withCleanCallingIdentity(() -> callbackExecutor.execute(
- () -> responseOutcomeReceiver.onError(
+ () -> responseCallback.onError(
new OnDeviceIntelligenceManagerProcessingException(
errorCode, errorMessage, errorParams))));
}
+
+ @Override
+ public void onDataAugmentRequest(@NonNull Content content,
+ @NonNull RemoteCallback contentCallback) {
+ Binder.withCleanCallingIdentity(() -> callbackExecutor.execute(
+ () -> responseCallback.onDataAugmentRequest(content, result -> {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(AUGMENT_REQUEST_CONTENT_BUNDLE_KEY, result);
+ callbackExecutor.execute(() -> contentCallback.sendResult(bundle));
+ })));
+ }
};
+
IProcessingSignal transport = null;
if (processingSignal != null) {
transport = ProcessingSignal.createTransport();
@@ -389,46 +427,48 @@
}
/**
- * Variation of {@link #processRequest} that asynchronously processes a request in a streaming
+ * Variation of {@link #processRequest} that asynchronously processes a request in a
+ * streaming
* fashion, where new content is pushed to caller in chunks via the
- * {@link StreamingResponseReceiver#onNewContent}. After the streaming is complete,
- * the service should call {@link StreamingResponseReceiver#onResult} and can optionally
- * populate the complete {@link Response}'s Content as part of the callback when the final
- * {@link Response} contains an enhanced aggregation of the Contents already streamed.
+ * {@link StreamedProcessingOutcomeReceiver#onNewContent}. After the streaming is complete,
+ * the service should call {@link StreamedProcessingOutcomeReceiver#onResult} and can optionally
+ * populate the complete the full response {@link Content} as part of the callback in cases
+ * when the final response contains an enhanced aggregation of the Contents already
+ * streamed.
*
* @param feature feature associated with the request.
* @param request request that contains the Content data and associated
* params.
* @param requestType type of request being sent for processing the content.
- * @param processingSignal signal to invoke other custom actions in the
+ * @param cancellationSignal signal to invoke cancellation.
+ * @param processingSignal signal to send custom signals in the
* remote implementation.
- * @param cancellationSignal signal to invoke cancellation
- * @param streamingResponseReceiver streaming callback to populate the response content and
+ * @param streamingResponseCallback streaming callback to populate the response content and
* associated params.
* @param callbackExecutor executor to run the callback on.
*/
@RequiresPermission(Manifest.permission.USE_ON_DEVICE_INTELLIGENCE)
- public void processRequestStreaming(@NonNull Feature feature, @NonNull Content request,
+ public void processRequestStreaming(@NonNull Feature feature, @Nullable Content request,
@RequestType int requestType,
@Nullable CancellationSignal cancellationSignal,
@Nullable ProcessingSignal processingSignal,
@NonNull @CallbackExecutor Executor callbackExecutor,
- @NonNull StreamingResponseReceiver<Content, Content,
- OnDeviceIntelligenceManagerProcessingException> streamingResponseReceiver) {
+ @NonNull StreamedProcessingOutcomeReceiver streamingResponseCallback) {
try {
IStreamingResponseCallback callback = new IStreamingResponseCallback.Stub() {
@Override
public void onNewContent(Content result) {
Binder.withCleanCallingIdentity(() -> {
callbackExecutor.execute(
- () -> streamingResponseReceiver.onNewContent(result));
+ () -> streamingResponseCallback.onNewContent(result));
});
}
@Override
public void onSuccess(Content result) {
Binder.withCleanCallingIdentity(() -> {
- callbackExecutor.execute(() -> streamingResponseReceiver.onResult(result));
+ callbackExecutor.execute(
+ () -> streamingResponseCallback.onResult(result));
});
}
@@ -437,11 +477,26 @@
PersistableBundle errorParams) {
Binder.withCleanCallingIdentity(() -> {
callbackExecutor.execute(
- () -> streamingResponseReceiver.onError(
+ () -> streamingResponseCallback.onError(
new OnDeviceIntelligenceManagerProcessingException(
errorCode, errorMessage, errorParams)));
});
}
+
+
+ @Override
+ public void onDataAugmentRequest(@NonNull Content content,
+ @NonNull RemoteCallback contentCallback) {
+ Binder.withCleanCallingIdentity(() -> callbackExecutor.execute(
+ () -> streamingResponseCallback.onDataAugmentRequest(content,
+ contentResponse -> {
+ Bundle bundle = new Bundle();
+ bundle.putParcelable(AUGMENT_REQUEST_CONTENT_BUNDLE_KEY,
+ contentResponse);
+ callbackExecutor.execute(
+ () -> contentCallback.sendResult(bundle));
+ })));
+ }
};
IProcessingSignal transport = null;
@@ -468,7 +523,8 @@
public static final int REQUEST_TYPE_INFERENCE = 0;
/**
- * Prepares the remote implementation environment for e.g.loading inference runtime etc.which
+ * Prepares the remote implementation environment for e.g.loading inference runtime etc
+ * .which
* are time consuming beforehand to remove overhead and allow quick processing of requests
* thereof.
*/
@@ -485,7 +541,8 @@
REQUEST_TYPE_PREPARE,
REQUEST_TYPE_EMBEDDINGS
}, open = true)
- @Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
+ @Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.PARAMETER,
+ ElementType.FIELD})
@Retention(RetentionPolicy.SOURCE)
public @interface RequestType {
}
@@ -501,17 +558,32 @@
*/
public static final int ON_DEVICE_INTELLIGENCE_SERVICE_UNAVAILABLE = 1000;
+ /**
+ * Error code to be used for on device intelligence manager failures.
+ *
+ * @hide
+ */
+ @IntDef(
+ value = {
+ ON_DEVICE_INTELLIGENCE_SERVICE_UNAVAILABLE
+ }, open = true)
+ @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
+ @interface OnDeviceIntelligenceManagerErrorCode {
+ }
+
private final int mErrorCode;
private final PersistableBundle errorParams;
- public OnDeviceIntelligenceManagerException(int errorCode, @NonNull String errorMessage,
+ public OnDeviceIntelligenceManagerException(
+ @OnDeviceIntelligenceManagerErrorCode int errorCode, @NonNull String errorMessage,
@NonNull PersistableBundle errorParams) {
super(errorMessage);
this.mErrorCode = errorCode;
this.errorParams = errorParams;
}
- public OnDeviceIntelligenceManagerException(int errorCode,
+ public OnDeviceIntelligenceManagerException(
+ @OnDeviceIntelligenceManagerErrorCode int errorCode,
@NonNull PersistableBundle errorParams) {
this.mErrorCode = errorCode;
this.errorParams = errorParams;
@@ -573,11 +645,15 @@
/** Inference suspended so that higher-priority inference can run. */
public static final int PROCESSING_ERROR_SUSPENDED = 13;
- /** Underlying processing encountered an internal error, like a violated precondition. */
+ /**
+ * Underlying processing encountered an internal error, like a violated precondition
+ * .
+ */
public static final int PROCESSING_ERROR_INTERNAL = 14;
/**
- * The processing was not able to be passed on to the remote implementation, as the service
+ * The processing was not able to be passed on to the remote implementation, as the
+ * service
* was unavailable.
*/
public static final int PROCESSING_ERROR_SERVICE_UNAVAILABLE = 15;
diff --git a/core/java/android/app/ondeviceintelligence/ProcessingOutcomeReceiver.java b/core/java/android/app/ondeviceintelligence/ProcessingOutcomeReceiver.java
new file mode 100644
index 0000000..b0b6e19
--- /dev/null
+++ b/core/java/android/app/ondeviceintelligence/ProcessingOutcomeReceiver.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.ondeviceintelligence;
+
+import static android.app.ondeviceintelligence.flags.Flags.FLAG_ENABLE_ON_DEVICE_INTELLIGENCE;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.os.OutcomeReceiver;
+
+import java.util.function.Consumer;
+
+/**
+ * Response Callback to populate the processed response or any error that occurred during the
+ * request processing. This callback also provides a method to request additional data to be
+ * augmented to the request-processing, using the partial {@link Content} that was already
+ * processed in the remote implementation.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
+public interface ProcessingOutcomeReceiver extends
+ OutcomeReceiver<Content,
+ OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> {
+ /**
+ * Callback to be invoked in cases where the remote service needs to perform retrieval or
+ * transformation operations based on a partially processed request, in order to augment the
+ * final response, by using the additional context sent via this callback.
+ *
+ * @param content The content payload that should be used to augment ongoing request.
+ * @param contentConsumer The augmentation data that should be sent to remote
+ * service for further processing a request.
+ */
+ default void onDataAugmentRequest(@NonNull Content content,
+ @NonNull Consumer<Content> contentConsumer) {
+ contentConsumer.accept(null);
+ }
+}
diff --git a/core/java/android/app/ondeviceintelligence/StreamingResponseReceiver.java b/core/java/android/app/ondeviceintelligence/StreamedProcessingOutcomeReceiver.java
similarity index 71%
rename from core/java/android/app/ondeviceintelligence/StreamingResponseReceiver.java
rename to core/java/android/app/ondeviceintelligence/StreamedProcessingOutcomeReceiver.java
index ebcf61c..ac2b032 100644
--- a/core/java/android/app/ondeviceintelligence/StreamingResponseReceiver.java
+++ b/core/java/android/app/ondeviceintelligence/StreamedProcessingOutcomeReceiver.java
@@ -21,23 +21,19 @@
import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.SystemApi;
-import android.os.OutcomeReceiver;
/**
* Streaming variant of outcome receiver to populate response while processing a given request,
- * possibly in
- * chunks to provide a async processing behaviour to the caller.
+ * possibly in chunks to provide a async processing behaviour to the caller.
*
* @hide
*/
@SystemApi
@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
-public interface StreamingResponseReceiver<R, T, E extends Throwable> extends
- OutcomeReceiver<R, E> {
+public interface StreamedProcessingOutcomeReceiver extends ProcessingOutcomeReceiver {
/**
- * Callback to be invoked when a part of the response i.e. some {@link Content} is already
- * processed and
- * needs to be passed onto the caller.
+ * Callback that would be invoked when a part of the response i.e. some {@link Content} is
+ * already processed and needs to be passed onto the caller.
*/
- void onNewContent(@NonNull T content);
+ void onNewContent(@NonNull Content content);
}
diff --git a/core/java/android/app/ondeviceintelligence/TokenInfo.aidl b/core/java/android/app/ondeviceintelligence/TokenInfo.aidl
new file mode 100644
index 0000000..2c19c1e
--- /dev/null
+++ b/core/java/android/app/ondeviceintelligence/TokenInfo.aidl
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.ondeviceintelligence;
+
+/**
+ * @hide
+ */
+parcelable TokenInfo;
diff --git a/core/java/android/app/ondeviceintelligence/TokenInfo.java b/core/java/android/app/ondeviceintelligence/TokenInfo.java
new file mode 100644
index 0000000..035cc4b
--- /dev/null
+++ b/core/java/android/app/ondeviceintelligence/TokenInfo.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app.ondeviceintelligence;
+
+import static android.app.ondeviceintelligence.flags.Flags.FLAG_ENABLE_ON_DEVICE_INTELLIGENCE;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.os.PersistableBundle;
+
+/**
+ * This class is used to provide a token count response for the
+ * {@link OnDeviceIntelligenceManager#requestTokenInfo} outcome receiver.
+ *
+ * @hide
+ */
+@SystemApi
+@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
+public final class TokenInfo implements Parcelable {
+ private final long mCount;
+ private final PersistableBundle mInfoParams;
+
+ /**
+ * Construct a token count using the count value and associated params.
+ */
+ public TokenInfo(long count, @NonNull PersistableBundle persistableBundle) {
+ this.mCount = count;
+ mInfoParams = persistableBundle;
+ }
+
+ /**
+ * Construct a token count using the count value.
+ */
+ public TokenInfo(long count) {
+ this.mCount = count;
+ this.mInfoParams = new PersistableBundle();
+ }
+
+ /**
+ * Returns the token count associated with a request payload.
+ */
+ public long getCount() {
+ return mCount;
+ }
+
+ /**
+ * Returns the params representing token info.
+ */
+ @NonNull
+ public PersistableBundle getInfoParams() {
+ return mInfoParams;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeLong(mCount);
+ dest.writePersistableBundle(mInfoParams);
+ }
+
+ public static final @NonNull Parcelable.Creator<TokenInfo> CREATOR
+ = new Parcelable.Creator<>() {
+ @Override
+ public TokenInfo[] newArray(int size) {
+ return new TokenInfo[size];
+ }
+
+ @Override
+ public TokenInfo createFromParcel(@NonNull Parcel in) {
+ return new TokenInfo(in.readLong(), in.readPersistableBundle());
+ }
+ };
+}
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index eea6464..cdb35ff 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -19992,6 +19992,13 @@
@Readable
public static final String CONSISTENT_NOTIFICATION_BLOCKING_ENABLED =
"consistent_notification_blocking_enabled";
+
+ /**
+ * Whether the Auto Bedtime Mode experience is enabled.
+ *
+ * @hide
+ */
+ public static final String AUTO_BEDTIME_MODE = "auto_bedtime_mode";
}
}
diff --git a/core/java/android/service/notification/NotificationListenerService.java b/core/java/android/service/notification/NotificationListenerService.java
index 694a457a..bd9ab86 100644
--- a/core/java/android/service/notification/NotificationListenerService.java
+++ b/core/java/android/service/notification/NotificationListenerService.java
@@ -1212,6 +1212,11 @@
* <p>
* Listen for updates using {@link #onInterruptionFilterChanged(int)}.
*
+ * <p>Apps targeting {@link Build.VERSION_CODES#VANILLA_ICE_CREAM} and above (with some
+ * exceptions, such as companion device managers) cannot modify the global interruption filter.
+ * Calling this method will instead activate or deactivate an
+ * {@link android.app.AutomaticZenRule} associated to the app.
+ *
* <p>The service should wait for the {@link #onListenerConnected()} event
* before performing this operation.
*
diff --git a/core/java/android/service/ondeviceintelligence/IOnDeviceIntelligenceService.aidl b/core/java/android/service/ondeviceintelligence/IOnDeviceIntelligenceService.aidl
index e44c69c..6dbff71 100644
--- a/core/java/android/service/ondeviceintelligence/IOnDeviceIntelligenceService.aidl
+++ b/core/java/android/service/ondeviceintelligence/IOnDeviceIntelligenceService.aidl
@@ -36,11 +36,13 @@
*/
oneway interface IOnDeviceIntelligenceService {
void getVersion(in RemoteCallback remoteCallback);
- void getFeature(in int featureId, in IFeatureCallback featureCallback);
- void listFeatures(in IListFeaturesCallback listFeaturesCallback);
- void getFeatureDetails(in Feature feature, in IFeatureDetailsCallback featureDetailsCallback);
+ void getFeature(int callerUid, int featureId, in IFeatureCallback featureCallback);
+ void listFeatures(int callerUid, in IListFeaturesCallback listFeaturesCallback);
+ void getFeatureDetails(int callerUid, in Feature feature, in IFeatureDetailsCallback featureDetailsCallback);
void getReadOnlyFileDescriptor(in String fileName, in AndroidFuture<ParcelFileDescriptor> future);
void getReadOnlyFeatureFileDescriptorMap(in Feature feature, in RemoteCallback remoteCallback);
- void requestFeatureDownload(in Feature feature, in ICancellationSignal cancellationSignal, in IDownloadCallback downloadCallback);
+ void requestFeatureDownload(int callerUid, in Feature feature, in ICancellationSignal cancellationSignal, in IDownloadCallback downloadCallback);
void registerRemoteServices(in IRemoteProcessingService remoteProcessingService);
+ void notifyInferenceServiceConnected();
+ void notifyInferenceServiceDisconnected();
}
\ No newline at end of file
diff --git a/core/java/android/service/ondeviceintelligence/IOnDeviceTrustedInferenceService.aidl b/core/java/android/service/ondeviceintelligence/IOnDeviceSandboxedInferenceService.aidl
similarity index 74%
rename from core/java/android/service/ondeviceintelligence/IOnDeviceTrustedInferenceService.aidl
rename to core/java/android/service/ondeviceintelligence/IOnDeviceSandboxedInferenceService.aidl
index e3fda04..73257ed 100644
--- a/core/java/android/service/ondeviceintelligence/IOnDeviceTrustedInferenceService.aidl
+++ b/core/java/android/service/ondeviceintelligence/IOnDeviceSandboxedInferenceService.aidl
@@ -18,7 +18,7 @@
import android.app.ondeviceintelligence.IStreamingResponseCallback;
import android.app.ondeviceintelligence.IResponseCallback;
-import android.app.ondeviceintelligence.ITokenCountCallback;
+import android.app.ondeviceintelligence.ITokenInfoCallback;
import android.app.ondeviceintelligence.IProcessingSignal;
import android.app.ondeviceintelligence.Content;
import android.app.ondeviceintelligence.Feature;
@@ -29,18 +29,18 @@
import android.service.ondeviceintelligence.IProcessingUpdateStatusCallback;
/**
- * Interface for a concrete implementation to provide on device trusted inference.
+ * Interface for a concrete implementation to provide on-device sandboxed inference.
*
* @hide
*/
-oneway interface IOnDeviceTrustedInferenceService {
+oneway interface IOnDeviceSandboxedInferenceService {
void registerRemoteStorageService(in IRemoteStorageService storageService);
- void requestTokenCount(in Feature feature, in Content request, in ICancellationSignal cancellationSignal,
- in ITokenCountCallback tokenCountCallback);
- void processRequest(in Feature feature, in Content request, in int requestType,
+ void requestTokenInfo(int callerUid, in Feature feature, in Content request, in ICancellationSignal cancellationSignal,
+ in ITokenInfoCallback tokenInfoCallback);
+ void processRequest(int callerUid, in Feature feature, in Content request, in int requestType,
in ICancellationSignal cancellationSignal, in IProcessingSignal processingSignal,
in IResponseCallback callback);
- void processRequestStreaming(in Feature feature, in Content request, in int requestType,
+ void processRequestStreaming(int callerUid, in Feature feature, in Content request, in int requestType,
in ICancellationSignal cancellationSignal, in IProcessingSignal processingSignal,
in IStreamingResponseCallback callback);
void updateProcessingState(in Bundle processingState,
diff --git a/core/java/android/service/ondeviceintelligence/OnDeviceIntelligenceService.java b/core/java/android/service/ondeviceintelligence/OnDeviceIntelligenceService.java
index 46ba25d..fce3689 100644
--- a/core/java/android/service/ondeviceintelligence/OnDeviceIntelligenceService.java
+++ b/core/java/android/service/ondeviceintelligence/OnDeviceIntelligenceService.java
@@ -65,7 +65,7 @@
/**
* Abstract base class for performing setup for on-device inference and providing file access to
- * the isolated counter part {@link OnDeviceTrustedInferenceService}.
+ * the isolated counter part {@link OnDeviceSandboxedInferenceService}.
*
* <p> A service that provides configuration and model files relevant to performing inference on
* device. The system's default OnDeviceIntelligenceService implementation is configured in
@@ -110,6 +110,8 @@
@Override
public final IBinder onBind(@NonNull Intent intent) {
if (SERVICE_INTERFACE.equals(intent.getAction())) {
+ // TODO(326052028) : Move the remote method calls to an app handler from the binder
+ // thread.
return new IOnDeviceIntelligenceService.Stub() {
/** {@inheritDoc} */
@Override
@@ -123,38 +125,40 @@
}
@Override
- public void listFeatures(IListFeaturesCallback listFeaturesCallback) {
+ public void listFeatures(int callerUid,
+ IListFeaturesCallback listFeaturesCallback) {
Objects.requireNonNull(listFeaturesCallback);
- OnDeviceIntelligenceService.this.onListFeatures(
+ OnDeviceIntelligenceService.this.onListFeatures(callerUid,
wrapListFeaturesCallback(listFeaturesCallback));
}
@Override
- public void getFeature(int id, IFeatureCallback featureCallback) {
+ public void getFeature(int callerUid, int id, IFeatureCallback featureCallback) {
Objects.requireNonNull(featureCallback);
- OnDeviceIntelligenceService.this.onGetFeature(id,
- wrapFeatureCallback(featureCallback));
+ OnDeviceIntelligenceService.this.onGetFeature(callerUid,
+ id, wrapFeatureCallback(featureCallback));
}
@Override
- public void getFeatureDetails(Feature feature,
+ public void getFeatureDetails(int callerUid, Feature feature,
IFeatureDetailsCallback featureDetailsCallback) {
Objects.requireNonNull(feature);
Objects.requireNonNull(featureDetailsCallback);
- OnDeviceIntelligenceService.this.onGetFeatureDetails(feature,
- wrapFeatureDetailsCallback(featureDetailsCallback));
+ OnDeviceIntelligenceService.this.onGetFeatureDetails(callerUid,
+ feature, wrapFeatureDetailsCallback(featureDetailsCallback));
}
@Override
- public void requestFeatureDownload(Feature feature,
+ public void requestFeatureDownload(int callerUid, Feature feature,
ICancellationSignal cancellationSignal,
IDownloadCallback downloadCallback) {
Objects.requireNonNull(feature);
Objects.requireNonNull(downloadCallback);
- OnDeviceIntelligenceService.this.onDownloadFeature(feature,
+ OnDeviceIntelligenceService.this.onDownloadFeature(callerUid,
+ feature,
CancellationSignal.fromTransport(cancellationSignal),
wrapDownloadCallback(downloadCallback));
}
@@ -188,12 +192,38 @@
IRemoteProcessingService remoteProcessingService) {
mRemoteProcessingService = remoteProcessingService;
}
+
+ @Override
+ public void notifyInferenceServiceConnected() {
+ OnDeviceIntelligenceService.this.onInferenceServiceConnected();
+ }
+
+ @Override
+ public void notifyInferenceServiceDisconnected() {
+ OnDeviceIntelligenceService.this.onInferenceServiceDisconnected();
+ }
};
}
Slog.w(TAG, "Incorrect service interface, returning null.");
return null;
}
+
+ /**
+ * Invoked when a new instance of the remote inference service is created.
+ * This method should be used as a signal to perform any initialization operations, for e.g. by
+ * invoking the {@link #updateProcessingState} method to initialize the remote processing
+ * service.
+ */
+ public abstract void onInferenceServiceConnected();
+
+
+ /**
+ * Invoked when an instance of the remote inference service is disconnected.
+ */
+ public abstract void onInferenceServiceDisconnected();
+
+
/**
* Invoked by the {@link OnDeviceIntelligenceService} inorder to send updates to the inference
* service if there is a state change to be performed.
@@ -391,6 +421,7 @@
* Request download for feature that is requested and listen to download progress updates. If
* the download completes successfully, success callback should be populated.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param feature the feature for which files need to be downlaoded.
* process.
* @param cancellationSignal signal to attach a listener to, and receive cancellation signals
@@ -398,7 +429,7 @@
* @param downloadCallback callback to populate download updates for clients to listen on..
*/
public abstract void onDownloadFeature(
- @NonNull Feature feature,
+ int callerUid, @NonNull Feature feature,
@Nullable CancellationSignal cancellationSignal,
@NonNull DownloadCallback downloadCallback);
@@ -407,20 +438,22 @@
* implementation use the {@link Feature#getFeatureParams()} as a hint to communicate what
* details the client is looking for.
*
- * @param feature the feature for which status needs to be known.
- * @param featureStatusCallback callback to populate the resulting feature status.
+ * @param callerUid UID of the caller that initiated this call chain.
+ * @param feature the feature for which status needs to be known.
+ * @param featureDetailsCallback callback to populate the resulting feature status.
*/
- public abstract void onGetFeatureDetails(@NonNull Feature feature,
+ public abstract void onGetFeatureDetails(int callerUid, @NonNull Feature feature,
@NonNull OutcomeReceiver<FeatureDetails,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException> featureStatusCallback);
+ OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException> featureDetailsCallback);
/**
* Get feature using the provided identifier to the remote implementation.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param featureCallback callback to populate the features list.
*/
- public abstract void onGetFeature(int featureId,
+ public abstract void onGetFeature(int callerUid, int featureId,
@NonNull OutcomeReceiver<Feature,
OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException> featureCallback);
@@ -428,9 +461,10 @@
* List all features which are available in the remote implementation. The implementation might
* choose to provide only a certain list of features based on the caller.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param listFeaturesCallback callback to populate the features list.
*/
- public abstract void onListFeatures(@NonNull OutcomeReceiver<List<Feature>,
+ public abstract void onListFeatures(int callerUid, @NonNull OutcomeReceiver<List<Feature>,
OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException> listFeaturesCallback);
/**
diff --git a/core/java/android/service/ondeviceintelligence/OnDeviceTrustedInferenceService.java b/core/java/android/service/ondeviceintelligence/OnDeviceSandboxedInferenceService.java
similarity index 73%
rename from core/java/android/service/ondeviceintelligence/OnDeviceTrustedInferenceService.java
rename to core/java/android/service/ondeviceintelligence/OnDeviceSandboxedInferenceService.java
index 8600197..7f7f9c2 100644
--- a/core/java/android/service/ondeviceintelligence/OnDeviceTrustedInferenceService.java
+++ b/core/java/android/service/ondeviceintelligence/OnDeviceSandboxedInferenceService.java
@@ -16,6 +16,7 @@
package android.service.ondeviceintelligence;
+import static android.app.ondeviceintelligence.OnDeviceIntelligenceManager.AUGMENT_REQUEST_CONTENT_BUNDLE_KEY;
import static android.app.ondeviceintelligence.flags.Flags.FLAG_ENABLE_ON_DEVICE_INTELLIGENCE;
import android.annotation.CallbackExecutor;
@@ -23,6 +24,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SdkConstant;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.app.Service;
import android.app.ondeviceintelligence.Content;
@@ -30,14 +32,18 @@
import android.app.ondeviceintelligence.IProcessingSignal;
import android.app.ondeviceintelligence.IResponseCallback;
import android.app.ondeviceintelligence.IStreamingResponseCallback;
-import android.app.ondeviceintelligence.ITokenCountCallback;
+import android.app.ondeviceintelligence.ITokenInfoCallback;
import android.app.ondeviceintelligence.OnDeviceIntelligenceManager;
import android.app.ondeviceintelligence.ProcessingSignal;
-import android.app.ondeviceintelligence.StreamingResponseReceiver;
+import android.app.ondeviceintelligence.ProcessingOutcomeReceiver;
+import android.app.ondeviceintelligence.StreamedProcessingOutcomeReceiver;
+import android.app.ondeviceintelligence.TokenInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CancellationSignal;
+import android.os.Handler;
+import android.os.HandlerExecutor;
import android.os.IBinder;
import android.os.ICancellationSignal;
import android.os.OutcomeReceiver;
@@ -75,8 +81,8 @@
*
* <pre>
* {@literal
- * <service android:name=".SampleTrustedInferenceService"
- * android:permission="android.permission.BIND_ONDEVICE_TRUSTED_INFERENCE_SERVICE"
+ * <service android:name=".SampleSandboxedInferenceService"
+ * android:permission="android.permission.BIND_ONDEVICE_SANDBOXED_INFERENCE_SERVICE"
* android:isolatedProcess="true">
* </service>}
* </pre>
@@ -85,18 +91,18 @@
*/
@SystemApi
@FlaggedApi(FLAG_ENABLE_ON_DEVICE_INTELLIGENCE)
-public abstract class OnDeviceTrustedInferenceService extends Service {
- private static final String TAG = OnDeviceTrustedInferenceService.class.getSimpleName();
+public abstract class OnDeviceSandboxedInferenceService extends Service {
+ private static final String TAG = OnDeviceSandboxedInferenceService.class.getSimpleName();
/**
* The {@link Intent} that must be declared as handled by the service. To be supported, the
* service must also require the
- * {@link android.Manifest.permission#BIND_ON_DEVICE_TRUSTED_INFERENCE_SERVICE}
+ * {@link android.Manifest.permission#BIND_ON_DEVICE_SANDBOXED_INFERENCE_SERVICE}
* permission so that other applications can not abuse it.
*/
@SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
public static final String SERVICE_INTERFACE =
- "android.service.ondeviceintelligence.OnDeviceTrustedInferenceService";
+ "android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService";
private IRemoteStorageService mRemoteStorageService;
@@ -107,7 +113,7 @@
@Override
public final IBinder onBind(@NonNull Intent intent) {
if (SERVICE_INTERFACE.equals(intent.getAction())) {
- return new IOnDeviceTrustedInferenceService.Stub() {
+ return new IOnDeviceSandboxedInferenceService.Stub() {
@Override
public void registerRemoteStorageService(IRemoteStorageService storageService) {
Objects.requireNonNull(storageService);
@@ -115,50 +121,48 @@
}
@Override
- public void requestTokenCount(Feature feature, Content request,
+ public void requestTokenInfo(int callerUid, Feature feature, Content request,
ICancellationSignal cancellationSignal,
- ITokenCountCallback tokenCountCallback) {
+ ITokenInfoCallback tokenInfoCallback) {
Objects.requireNonNull(feature);
- Objects.requireNonNull(tokenCountCallback);
- OnDeviceTrustedInferenceService.this.onCountTokens(feature,
+ Objects.requireNonNull(tokenInfoCallback);
+ OnDeviceSandboxedInferenceService.this.onTokenInfoRequest(callerUid,
+ feature,
request,
CancellationSignal.fromTransport(cancellationSignal),
- wrapTokenCountCallback(tokenCountCallback));
+ wrapTokenInfoCallback(tokenInfoCallback));
}
@Override
- public void processRequestStreaming(Feature feature, Content request,
+ public void processRequestStreaming(int callerUid, Feature feature, Content request,
int requestType, ICancellationSignal cancellationSignal,
IProcessingSignal processingSignal,
IStreamingResponseCallback callback) {
Objects.requireNonNull(feature);
- Objects.requireNonNull(request);
Objects.requireNonNull(callback);
- OnDeviceTrustedInferenceService.this.onProcessRequestStreaming(feature,
+ OnDeviceSandboxedInferenceService.this.onProcessRequestStreaming(callerUid,
+ feature,
request,
requestType,
CancellationSignal.fromTransport(cancellationSignal),
ProcessingSignal.fromTransport(processingSignal),
- wrapStreamingResponseCallback(callback)
- );
+ wrapStreamingResponseCallback(callback));
}
@Override
- public void processRequest(Feature feature, Content request,
+ public void processRequest(int callerUid, Feature feature, Content request,
int requestType, ICancellationSignal cancellationSignal,
IProcessingSignal processingSignal,
IResponseCallback callback) {
Objects.requireNonNull(feature);
- Objects.requireNonNull(request);
Objects.requireNonNull(callback);
-
- OnDeviceTrustedInferenceService.this.onProcessRequest(feature, request,
- requestType, CancellationSignal.fromTransport(cancellationSignal),
+ OnDeviceSandboxedInferenceService.this.onProcessRequest(callerUid, feature,
+ request, requestType,
+ CancellationSignal.fromTransport(cancellationSignal),
ProcessingSignal.fromTransport(processingSignal),
- wrapResponseCallback(callback)
- );
+ wrapResponseCallback(callback));
}
@Override
@@ -167,7 +171,7 @@
Objects.requireNonNull(processingState);
Objects.requireNonNull(callback);
- OnDeviceTrustedInferenceService.this.onUpdateProcessingState(processingState,
+ OnDeviceSandboxedInferenceService.this.onUpdateProcessingState(processingState,
wrapOutcomeReceiver(callback)
);
}
@@ -178,35 +182,37 @@
}
/**
- * Invoked when caller wants to obtain a count of number of tokens present in the passed in
- * Request associated with the provided feature.
+ * Invoked when caller wants to obtain token info related to the payload in the passed
+ * content, associated with the provided feature.
* The expectation from the implementation is that when processing is complete, it
- * should provide the token count in the {@link OutcomeReceiver#onResult}.
+ * should provide the token info in the {@link OutcomeReceiver#onResult}.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param feature feature which is associated with the request.
* @param request request that requires processing.
* @param cancellationSignal Cancellation Signal to receive cancellation events from client and
* configure a listener to.
- * @param callback callback to populate failure and full response for the provided
+ * @param callback callback to populate failure or the token info for the provided
* request.
*/
@NonNull
- public abstract void onCountTokens(
- @NonNull Feature feature,
+ public abstract void onTokenInfoRequest(
+ int callerUid, @NonNull Feature feature,
@NonNull Content request,
@Nullable CancellationSignal cancellationSignal,
- @NonNull OutcomeReceiver<Long,
+ @NonNull OutcomeReceiver<TokenInfo,
OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> callback);
/**
* Invoked when caller provides a request for a particular feature to be processed in a
* streaming manner. The expectation from the implementation is that when processing the
* request,
- * it periodically populates the {@link StreamingResponseReceiver#onNewContent} to continuously
+ * it periodically populates the {@link StreamedProcessingOutcomeReceiver#onNewContent} to continuously
* provide partial Content results for the caller to utilize. Optionally the implementation can
- * provide the complete response in the {@link StreamingResponseReceiver#onResult} upon
+ * provide the complete response in the {@link StreamedProcessingOutcomeReceiver#onResult} upon
* processing completion.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param feature feature which is associated with the request.
* @param request request that requires processing.
* @param requestType identifier representing the type of request.
@@ -218,13 +224,12 @@
*/
@NonNull
public abstract void onProcessRequestStreaming(
- @NonNull Feature feature,
- @NonNull Content request,
+ int callerUid, @NonNull Feature feature,
+ @Nullable Content request,
@OnDeviceIntelligenceManager.RequestType int requestType,
@Nullable CancellationSignal cancellationSignal,
@Nullable ProcessingSignal processingSignal,
- @NonNull StreamingResponseReceiver<Content, Content,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> callback);
+ @NonNull StreamedProcessingOutcomeReceiver callback);
/**
* Invoked when caller provides a request for a particular feature to be processed in one shot
@@ -233,6 +238,7 @@
* should
* provide the complete response in the {@link OutcomeReceiver#onResult}.
*
+ * @param callerUid UID of the caller that initiated this call chain.
* @param feature feature which is associated with the request.
* @param request request that requires processing.
* @param requestType identifier representing the type of request.
@@ -244,13 +250,12 @@
*/
@NonNull
public abstract void onProcessRequest(
- @NonNull Feature feature,
- @NonNull Content request,
+ int callerUid, @NonNull Feature feature,
+ @Nullable Content request,
@OnDeviceIntelligenceManager.RequestType int requestType,
@Nullable CancellationSignal cancellationSignal,
@Nullable ProcessingSignal processingSignal,
- @NonNull OutcomeReceiver<Content,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> callback);
+ @NonNull ProcessingOutcomeReceiver callback);
/**
@@ -335,6 +340,26 @@
}
}
+
+ /**
+ * Returns the {@link Executor} to use for incoming IPC from request sender into your service
+ * implementation. For e.g. see
+ * {@link ProcessingOutcomeReceiver#onDataAugmentRequest(Content,
+ * Consumer)} where we use the executor to populate the consumer.
+ * <p>
+ * Override this method in your {@link OnDeviceSandboxedInferenceService} implementation to
+ * provide the executor you want to use for incoming IPC.
+ *
+ * @return the {@link Executor} to use for incoming IPC from {@link OnDeviceIntelligenceManager}
+ * to {@link OnDeviceSandboxedInferenceService}.
+ */
+ @SuppressLint("OnNameExpected")
+ @NonNull
+ public Executor getCallbackExecutor() {
+ return new HandlerExecutor(Handler.createAsync(getMainLooper()));
+ }
+
+
private RemoteCallback wrapResultReceiverAsReadOnly(
@NonNull Consumer<Map<String, FileInputStream>> resultConsumer,
@NonNull Executor executor) {
@@ -355,10 +380,9 @@
});
}
- private OutcomeReceiver<Content,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> wrapResponseCallback(
+ private ProcessingOutcomeReceiver wrapResponseCallback(
IResponseCallback callback) {
- return new OutcomeReceiver<>() {
+ return new ProcessingOutcomeReceiver() {
@Override
public void onResult(@androidx.annotation.NonNull Content response) {
try {
@@ -378,13 +402,23 @@
Slog.e(TAG, "Error sending result: " + e);
}
}
+
+ @Override
+ public void onDataAugmentRequest(@NonNull Content content,
+ @NonNull Consumer<Content> contentCallback) {
+ try {
+ callback.onDataAugmentRequest(content, wrapRemoteCallback(contentCallback));
+
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Error sending augment request: " + e);
+ }
+ }
};
}
- private StreamingResponseReceiver<Content, Content,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> wrapStreamingResponseCallback(
+ private StreamedProcessingOutcomeReceiver wrapStreamingResponseCallback(
IStreamingResponseCallback callback) {
- return new StreamingResponseReceiver<>() {
+ return new StreamedProcessingOutcomeReceiver() {
@Override
public void onNewContent(@androidx.annotation.NonNull Content content) {
try {
@@ -413,17 +447,43 @@
Slog.e(TAG, "Error sending result: " + e);
}
}
+
+ @Override
+ public void onDataAugmentRequest(@NonNull Content content,
+ @NonNull Consumer<Content> contentCallback) {
+ try {
+ callback.onDataAugmentRequest(content, wrapRemoteCallback(contentCallback));
+
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Error sending augment request: " + e);
+ }
+ }
};
}
- private OutcomeReceiver<Long,
- OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> wrapTokenCountCallback(
- ITokenCountCallback tokenCountCallback) {
+ private RemoteCallback wrapRemoteCallback(
+ @androidx.annotation.NonNull Consumer<Content> contentCallback) {
+ return new RemoteCallback(
+ result -> {
+ if (result != null) {
+ getCallbackExecutor().execute(() -> contentCallback.accept(
+ result.getParcelable(AUGMENT_REQUEST_CONTENT_BUNDLE_KEY,
+ Content.class)));
+ } else {
+ getCallbackExecutor().execute(
+ () -> contentCallback.accept(null));
+ }
+ });
+ }
+
+ private OutcomeReceiver<TokenInfo,
+ OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException> wrapTokenInfoCallback(
+ ITokenInfoCallback tokenInfoCallback) {
return new OutcomeReceiver<>() {
@Override
- public void onResult(Long tokenCount) {
+ public void onResult(TokenInfo tokenInfo) {
try {
- tokenCountCallback.onSuccess(tokenCount);
+ tokenInfoCallback.onSuccess(tokenInfo);
} catch (RemoteException e) {
Slog.e(TAG, "Error sending result: " + e);
}
@@ -433,7 +493,7 @@
public void onError(
OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerProcessingException exception) {
try {
- tokenCountCallback.onFailure(exception.getErrorCode(), exception.getMessage(),
+ tokenInfoCallback.onFailure(exception.getErrorCode(), exception.getMessage(),
exception.getErrorParams());
} catch (RemoteException e) {
Slog.e(TAG, "Error sending failure: " + e);
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index 67a3978..0ae3e59 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -1775,9 +1775,9 @@
@CriticalNative
private static native void nativeOffsetLocation(long nativePtr, float deltaX, float deltaY);
@CriticalNative
- private static native float nativeGetXOffset(long nativePtr);
+ private static native float nativeGetRawXOffset(long nativePtr);
@CriticalNative
- private static native float nativeGetYOffset(long nativePtr);
+ private static native float nativeGetRawYOffset(long nativePtr);
@CriticalNative
private static native float nativeGetXPrecision(long nativePtr);
@CriticalNative
@@ -3745,7 +3745,7 @@
nativeGetAction(mNativePtr), nativeGetFlags(mNativePtr),
nativeGetEdgeFlags(mNativePtr), nativeGetMetaState(mNativePtr),
nativeGetButtonState(mNativePtr), nativeGetClassification(mNativePtr),
- nativeGetXOffset(mNativePtr), nativeGetYOffset(mNativePtr),
+ nativeGetRawXOffset(mNativePtr), nativeGetRawYOffset(mNativePtr),
nativeGetXPrecision(mNativePtr), nativeGetYPrecision(mNativePtr),
nativeGetDownTimeNanos(mNativePtr),
nativeGetEventTimeNanos(mNativePtr, HISTORY_CURRENT),
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index d29963c..828004b 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -25,7 +25,6 @@
import static android.view.Surface.FRAME_RATE_CATEGORY_NORMAL;
import static android.view.Surface.FRAME_RATE_CATEGORY_NO_PREFERENCE;
import static android.view.Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
-import static android.view.Surface.FRAME_RATE_COMPATIBILITY_GTE;
import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
import static android.view.accessibility.AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED;
import static android.view.displayhash.DisplayHashResultCallback.DISPLAY_HASH_ERROR_INVALID_BOUNDS;
@@ -5630,7 +5629,7 @@
@Nullable
private ViewTranslationCallback mViewTranslationCallback;
- private float mFrameContentVelocity = -1;
+ private float mFrameContentVelocity = 0;
@Nullable
@@ -5661,9 +5660,6 @@
protected long mMinusTwoFrameIntervalMillis = 0;
private int mLastFrameRateCategory = FRAME_RATE_CATEGORY_NO_PREFERENCE;
- private float mLastFrameX = Float.NaN;
- private float mLastFrameY = Float.NaN;
-
@FlaggedApi(FLAG_TOOLKIT_SET_FRAME_RATE_READ_ONLY)
public static final float REQUESTED_FRAME_RATE_CATEGORY_DEFAULT = Float.NaN;
@FlaggedApi(FLAG_TOOLKIT_SET_FRAME_RATE_READ_ONLY)
@@ -24601,10 +24597,7 @@
public void draw(@NonNull Canvas canvas) {
final int privateFlags = mPrivateFlags;
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
-
- mFrameContentVelocity = -1;
- mLastFrameX = mLeft + mRenderNode.getTranslationX();
- mLastFrameY = mTop + mRenderNode.getTranslationY();
+ mFrameContentVelocity = 0;
/*
* Draw traversal performs several drawing steps which must be executed
@@ -33680,17 +33673,6 @@
if (sToolkitMetricsForFrameRateDecisionFlagValue) {
viewRootImpl.recordViewPercentage(sizePercentage);
}
- if (viewVelocityApi()) {
- float velocity = mFrameContentVelocity;
- if (velocity < 0f) {
- velocity = calculateVelocity();
- }
- if (velocity > 0f) {
- float frameRate = convertVelocityToFrameRate(velocity);
- viewRootImpl.votePreferredFrameRate(frameRate, FRAME_RATE_COMPATIBILITY_GTE);
- return;
- }
- }
if (!Float.isNaN(mPreferredFrameRate)) {
if (mPreferredFrameRate < 0) {
if (mPreferredFrameRate == REQUESTED_FRAME_RATE_CATEGORY_NO_PREFERENCE) {
@@ -33713,23 +33695,6 @@
}
}
- private float convertVelocityToFrameRate(float velocityPps) {
- float density = getResources().getDisplayMetrics().density;
- float velocityDps = velocityPps / density;
- // Choose a frame rate in increments of 10fps
- return Math.min(140f, 60f + (10f * (float) Math.floor(velocityDps / 300f)));
- }
-
- private float calculateVelocity() {
- // This current calculation is very simple. If something on the screen moved, then
- // it votes for the highest velocity. If it doesn't move, then return 0.
- float x = mLeft + mRenderNode.getTranslationX();
- float y = mTop + mRenderNode.getTranslationY();
-
- return (!Float.isNaN(mLastFrameX) && (x != mLastFrameX || y != mLastFrameY))
- ? 100_000f : 0f;
- }
-
/**
* Set the current velocity of the View, we only track positive value.
* We will use the velocity information to adjust the frame rate when applicable.
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 42f6405..02f8e6e 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -31,7 +31,6 @@
import static android.view.Surface.FRAME_RATE_CATEGORY_NORMAL;
import static android.view.Surface.FRAME_RATE_CATEGORY_NO_PREFERENCE;
import static android.view.Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE;
-import static android.view.Surface.FRAME_RATE_COMPATIBILITY_GTE;
import static android.view.View.PFLAG_DRAW_ANIMATION;
import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;
import static android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
@@ -7572,8 +7571,7 @@
}
// For the variable refresh rate project
- if (handled && shouldTouchBoost(action & MotionEvent.ACTION_MASK,
- mWindowAttributes.type)) {
+ if (handled && shouldTouchBoost(action, mWindowAttributes.type)) {
// set the frame rate to the maximum value.
mIsTouchBoosting = true;
setPreferredFrameRateCategory(mPreferredFrameRateCategory);
@@ -12400,17 +12398,6 @@
mFrameRateCompatibility).applyAsyncUnsafe();
mLastPreferredFrameRate = preferredFrameRate;
}
- if (mFrameRateCompatibility == FRAME_RATE_COMPATIBILITY_GTE && mIsTouchBoosting) {
- // We've received a velocity, so we'll let the velocity control the
- // frame rate unless we receive additional motion events.
- mIsTouchBoosting = false;
- if (Trace.isTagEnabled(Trace.TRACE_TAG_VIEW)) {
- Trace.instant(
- Trace.TRACE_TAG_VIEW,
- "ViewRootImpl#setFrameRate velocity used, no touch boost on next frame"
- );
- }
- }
} catch (Exception e) {
Log.e(mTag, "Unable to set frame rate", e);
} finally {
@@ -12436,8 +12423,9 @@
}
private boolean shouldTouchBoost(int motionEventAction, int windowType) {
- // boost for almost all input
- boolean desiredAction = motionEventAction != MotionEvent.ACTION_OUTSIDE;
+ boolean desiredAction = motionEventAction == MotionEvent.ACTION_DOWN
+ || motionEventAction == MotionEvent.ACTION_MOVE
+ || motionEventAction == MotionEvent.ACTION_UP;
boolean undesiredType = windowType == TYPE_INPUT_METHOD
&& sToolkitFrameRateTypingReadOnlyFlagValue;
// use toolkitSetFrameRate flag to gate the change
@@ -12543,14 +12531,6 @@
}
/**
- * Returns whether touch boost is currently enabled.
- */
- @VisibleForTesting
- public boolean getIsTouchBoosting() {
- return mIsTouchBoosting;
- }
-
- /**
* Get the value of mFrameRateCompatibility
*/
@VisibleForTesting
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index fe4ac4e..a2d8d80 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -4299,7 +4299,7 @@
}
if (mode == MODE_NORMAL) {
- mApplication = ApplicationInfo.CREATOR.createFromParcel(parcel);
+ mApplication = parcel.readTypedObject(ApplicationInfo.CREATOR);
mIdealSize = parcel.readInt() == 0 ? null : SizeF.CREATOR.createFromParcel(parcel);
mLayoutId = parcel.readInt();
mViewId = parcel.readInt();
@@ -6805,7 +6805,7 @@
mBitmapCache.writeBitmapsToParcel(dest, flags);
mCollectionCache.writeToParcel(dest, flags, intentsToIgnore);
}
- mApplication.writeToParcel(dest, flags);
+ dest.writeTypedObject(mApplication, flags);
if (mIsRoot || mIdealSize == null) {
dest.writeInt(0);
} else {
@@ -6893,7 +6893,8 @@
* @hide
*/
public boolean hasSameAppInfo(ApplicationInfo info) {
- return mApplication.packageName.equals(info.packageName) && mApplication.uid == info.uid;
+ return mApplication == null || mApplication.packageName.equals(info.packageName)
+ && mApplication.uid == info.uid;
}
/**
@@ -7672,8 +7673,7 @@
byte[] instruction;
final List<byte[]> instructions = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
- instruction = new byte[in.readInt()];
- in.readByteArray(instruction);
+ instruction = in.readBlob();
instructions.add(instruction);
}
return new DrawInstructions(instructions);
@@ -7688,8 +7688,7 @@
final List<byte[]> instructions = drawInstructions.mInstructions;
dest.writeInt(instructions.size());
for (byte[] instruction : instructions) {
- dest.writeInt(instruction.length);
- dest.writeByteArray(instruction);
+ dest.writeBlob(instruction);
}
}
diff --git a/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java b/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
index 30de546..2096ba4 100644
--- a/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/LegacyProtoLogImpl.java
@@ -55,37 +55,38 @@
* A service for the ProtoLog logging system.
*/
public class LegacyProtoLogImpl implements IProtoLog {
- private final TreeMap<String, IProtoLogGroup> mLogGroups = new TreeMap<>();
-
private static final int BUFFER_CAPACITY = 1024 * 1024;
private static final int PER_CHUNK_SIZE = 1024;
private static final String TAG = "ProtoLog";
private static final long MAGIC_NUMBER_VALUE = ((long) MAGIC_NUMBER_H << 32) | MAGIC_NUMBER_L;
static final String PROTOLOG_VERSION = "2.0.0";
- private static final int DEFAULT_PER_CHUNK_SIZE = 0;
private final File mLogFile;
private final String mLegacyViewerConfigFilename;
private final TraceBuffer mBuffer;
private final LegacyProtoLogViewerConfigReader mViewerConfig;
+ private final TreeMap<String, IProtoLogGroup> mLogGroups;
private final int mPerChunkSize;
private boolean mProtoLogEnabled;
private boolean mProtoLogEnabledLockFree;
private final Object mProtoLogEnabledLock = new Object();
- public LegacyProtoLogImpl(String outputFile, String viewerConfigFilename) {
+ public LegacyProtoLogImpl(String outputFile, String viewerConfigFilename,
+ TreeMap<String, IProtoLogGroup> logGroups) {
this(new File(outputFile), viewerConfigFilename, BUFFER_CAPACITY,
- new LegacyProtoLogViewerConfigReader(), PER_CHUNK_SIZE);
+ new LegacyProtoLogViewerConfigReader(), PER_CHUNK_SIZE, logGroups);
}
public LegacyProtoLogImpl(File file, String viewerConfigFilename, int bufferCapacity,
- LegacyProtoLogViewerConfigReader viewerConfig, int perChunkSize) {
+ LegacyProtoLogViewerConfigReader viewerConfig, int perChunkSize,
+ TreeMap<String, IProtoLogGroup> logGroups) {
mLogFile = file;
mBuffer = new TraceBuffer(bufferCapacity);
mLegacyViewerConfigFilename = viewerConfigFilename;
mViewerConfig = viewerConfig;
mPerChunkSize = perChunkSize;
+ this.mLogGroups = logGroups;
}
/**
diff --git a/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java b/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
index 53062d8..bdd9a91 100644
--- a/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/PerfettoProtoLogImpl.java
@@ -22,9 +22,9 @@
import static perfetto.protos.PerfettoTrace.InternedString.STR;
import static perfetto.protos.PerfettoTrace.ProtoLogMessage.BOOLEAN_PARAMS;
import static perfetto.protos.PerfettoTrace.ProtoLogMessage.DOUBLE_PARAMS;
-import static perfetto.protos.PerfettoTrace.ProtoLogMessage.STACKTRACE_IID;
import static perfetto.protos.PerfettoTrace.ProtoLogMessage.MESSAGE_ID;
import static perfetto.protos.PerfettoTrace.ProtoLogMessage.SINT64_PARAMS;
+import static perfetto.protos.PerfettoTrace.ProtoLogMessage.STACKTRACE_IID;
import static perfetto.protos.PerfettoTrace.ProtoLogMessage.STR_PARAM_IIDS;
import static perfetto.protos.PerfettoTrace.ProtoLogViewerConfig.GROUPS;
import static perfetto.protos.PerfettoTrace.ProtoLogViewerConfig.Group.ID;
@@ -78,7 +78,6 @@
* A service for the ProtoLog logging system.
*/
public class PerfettoProtoLogImpl implements IProtoLog {
- private final TreeMap<String, IProtoLogGroup> mLogGroups = new TreeMap<>();
private static final String LOG_TAG = "ProtoLog";
private final AtomicInteger mTracingInstances = new AtomicInteger();
@@ -89,8 +88,10 @@
);
private final ProtoLogViewerConfigReader mViewerConfigReader;
private final ViewerConfigInputStreamProvider mViewerConfigInputStreamProvider;
+ private final TreeMap<String, IProtoLogGroup> mLogGroups;
- public PerfettoProtoLogImpl(String viewerConfigFilePath) {
+ public PerfettoProtoLogImpl(String viewerConfigFilePath,
+ TreeMap<String, IProtoLogGroup> logGroups) {
this(() -> {
try {
return new ProtoInputStream(new FileInputStream(viewerConfigFilePath));
@@ -98,23 +99,28 @@
Slog.w(LOG_TAG, "Failed to load viewer config file " + viewerConfigFilePath, e);
return null;
}
- });
+ }, logGroups);
}
- public PerfettoProtoLogImpl(ViewerConfigInputStreamProvider viewerConfigInputStreamProvider) {
+ public PerfettoProtoLogImpl(
+ ViewerConfigInputStreamProvider viewerConfigInputStreamProvider,
+ TreeMap<String, IProtoLogGroup> logGroups
+ ) {
this(viewerConfigInputStreamProvider,
- new ProtoLogViewerConfigReader(viewerConfigInputStreamProvider));
+ new ProtoLogViewerConfigReader(viewerConfigInputStreamProvider), logGroups);
}
@VisibleForTesting
public PerfettoProtoLogImpl(
ViewerConfigInputStreamProvider viewerConfigInputStreamProvider,
- ProtoLogViewerConfigReader viewerConfigReader
+ ProtoLogViewerConfigReader viewerConfigReader,
+ TreeMap<String, IProtoLogGroup> logGroups
) {
Producer.init(InitArguments.DEFAULTS);
mDataSource.register(DataSourceParams.DEFAULTS);
this.mViewerConfigInputStreamProvider = viewerConfigInputStreamProvider;
this.mViewerConfigReader = viewerConfigReader;
+ this.mLogGroups = logGroups;
}
/**
diff --git a/core/java/com/android/internal/protolog/ProtoLogImpl.java b/core/java/com/android/internal/protolog/ProtoLogImpl.java
index 8965385..487ae814 100644
--- a/core/java/com/android/internal/protolog/ProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/ProtoLogImpl.java
@@ -18,6 +18,7 @@
import static com.android.internal.protolog.common.ProtoLogToolInjected.Value.LEGACY_OUTPUT_FILE_PATH;
import static com.android.internal.protolog.common.ProtoLogToolInjected.Value.LEGACY_VIEWER_CONFIG_PATH;
+import static com.android.internal.protolog.common.ProtoLogToolInjected.Value.LOG_GROUPS;
import static com.android.internal.protolog.common.ProtoLogToolInjected.Value.VIEWER_CONFIG_PATH;
import android.annotation.Nullable;
@@ -28,6 +29,8 @@
import com.android.internal.protolog.common.LogLevel;
import com.android.internal.protolog.common.ProtoLogToolInjected;
+import java.util.TreeMap;
+
/**
* A service for the ProtoLog logging system.
*/
@@ -43,6 +46,9 @@
@ProtoLogToolInjected(LEGACY_OUTPUT_FILE_PATH)
private static String sLegacyOutputFilePath;
+ @ProtoLogToolInjected(LOG_GROUPS)
+ private static TreeMap<String, IProtoLogGroup> sLogGroups;
+
/** Used by the ProtoLogTool, do not call directly - use {@code ProtoLog} class instead. */
public static void d(IProtoLogGroup group, long messageHash, int paramsMask,
@Nullable String messageString,
@@ -99,11 +105,10 @@
public static synchronized IProtoLog getSingleInstance() {
if (sServiceInstance == null) {
if (android.tracing.Flags.perfettoProtologTracing()) {
- sServiceInstance =
- new PerfettoProtoLogImpl(sViewerConfigPath);
+ sServiceInstance = new PerfettoProtoLogImpl(sViewerConfigPath, sLogGroups);
} else {
- sServiceInstance =
- new LegacyProtoLogImpl(sLegacyOutputFilePath, sLegacyViewerConfigPath);
+ sServiceInstance = new LegacyProtoLogImpl(
+ sLegacyOutputFilePath, sLegacyViewerConfigPath, sLogGroups);
}
}
return sServiceInstance;
diff --git a/core/java/com/android/internal/protolog/ProtoLogViewerConfigReader.java b/core/java/com/android/internal/protolog/ProtoLogViewerConfigReader.java
index 3c206ac..ae3d448 100644
--- a/core/java/com/android/internal/protolog/ProtoLogViewerConfigReader.java
+++ b/core/java/com/android/internal/protolog/ProtoLogViewerConfigReader.java
@@ -4,6 +4,7 @@
import static perfetto.protos.PerfettoTrace.ProtoLogViewerConfig.MessageData.MESSAGE;
import static perfetto.protos.PerfettoTrace.ProtoLogViewerConfig.MessageData.MESSAGE_ID;
+import android.util.ArrayMap;
import android.util.proto.ProtoInputStream;
import com.android.internal.protolog.common.ILogger;
@@ -57,6 +58,7 @@
}
private void doLoadViewerConfig() throws IOException {
+ mLogMessageMap = new ArrayMap<>();
final ProtoInputStream pis = mViewerConfigInputStreamProvider.getInputStream();
while (pis.nextField() != ProtoInputStream.NO_MORE_FIELDS) {
diff --git a/core/java/com/android/internal/protolog/common/ProtoLogToolInjected.java b/core/java/com/android/internal/protolog/common/ProtoLogToolInjected.java
index ffd0d76..17c82d7 100644
--- a/core/java/com/android/internal/protolog/common/ProtoLogToolInjected.java
+++ b/core/java/com/android/internal/protolog/common/ProtoLogToolInjected.java
@@ -22,7 +22,9 @@
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface ProtoLogToolInjected {
- enum Value { VIEWER_CONFIG_PATH, LEGACY_OUTPUT_FILE_PATH, LEGACY_VIEWER_CONFIG_PATH }
+ enum Value {
+ VIEWER_CONFIG_PATH, LEGACY_OUTPUT_FILE_PATH, LEGACY_VIEWER_CONFIG_PATH, LOG_GROUPS
+ }
Value value();
}
diff --git a/core/jni/android_view_MotionEvent.cpp b/core/jni/android_view_MotionEvent.cpp
index 23adb8f7..1a86363 100644
--- a/core/jni/android_view_MotionEvent.cpp
+++ b/core/jni/android_view_MotionEvent.cpp
@@ -411,8 +411,8 @@
jniThrowNullPointerException(env, "pointerCoords");
return;
}
- pointerCoordsToNative(env, pointerCoordsObj,
- event->getXOffset(), event->getYOffset(), &rawPointerCoords[i]);
+ pointerCoordsToNative(env, pointerCoordsObj, event->getRawXOffset(), event->getRawYOffset(),
+ &rawPointerCoords[i]);
env->DeleteLocalRef(pointerCoordsObj);
}
@@ -735,14 +735,14 @@
return event->offsetLocation(deltaX, deltaY);
}
-static jfloat android_view_MotionEvent_nativeGetXOffset(jlong nativePtr) {
+static jfloat android_view_MotionEvent_nativeGetRawXOffset(jlong nativePtr) {
MotionEvent* event = reinterpret_cast<MotionEvent*>(nativePtr);
- return event->getXOffset();
+ return event->getRawXOffset();
}
-static jfloat android_view_MotionEvent_nativeGetYOffset(jlong nativePtr) {
+static jfloat android_view_MotionEvent_nativeGetRawYOffset(jlong nativePtr) {
MotionEvent* event = reinterpret_cast<MotionEvent*>(nativePtr);
- return event->getYOffset();
+ return event->getRawYOffset();
}
static jfloat android_view_MotionEvent_nativeGetXPrecision(jlong nativePtr) {
@@ -871,8 +871,8 @@
{"nativeGetClassification", "(J)I",
(void*)android_view_MotionEvent_nativeGetClassification},
{"nativeOffsetLocation", "(JFF)V", (void*)android_view_MotionEvent_nativeOffsetLocation},
- {"nativeGetXOffset", "(J)F", (void*)android_view_MotionEvent_nativeGetXOffset},
- {"nativeGetYOffset", "(J)F", (void*)android_view_MotionEvent_nativeGetYOffset},
+ {"nativeGetRawXOffset", "(J)F", (void*)android_view_MotionEvent_nativeGetRawXOffset},
+ {"nativeGetRawYOffset", "(J)F", (void*)android_view_MotionEvent_nativeGetRawYOffset},
{"nativeGetXPrecision", "(J)F", (void*)android_view_MotionEvent_nativeGetXPrecision},
{"nativeGetYPrecision", "(J)F", (void*)android_view_MotionEvent_nativeGetYPrecision},
{"nativeGetXCursorPosition", "(J)F",
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 52bad21..9d80d153 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -7955,12 +7955,12 @@
android:protectionLevel="signature|privileged" />
- <!-- @SystemApi Allows an app to bind the on-device trusted service.
+ <!-- @SystemApi Allows an app to bind the on-device sandboxed service.
<p>Protection level: signature|privileged
@hide
@FlaggedApi("android.app.ondeviceintelligence.flags.enable_on_device_intelligence")
-->
- <permission android:name="android.permission.BIND_ON_DEVICE_TRUSTED_SERVICE"
+ <permission android:name="android.permission.BIND_ON_DEVICE_SANDBOXED_INFERENCE_SERVICE"
android:protectionLevel="signature"/>
diff --git a/core/res/res/values-watch/themes_device_defaults.xml b/core/res/res/values-watch/themes_device_defaults.xml
index df8158d..6e804c0 100644
--- a/core/res/res/values-watch/themes_device_defaults.xml
+++ b/core/res/res/values-watch/themes_device_defaults.xml
@@ -146,7 +146,7 @@
<item name="windowAnimationStyle">@style/Animation.InputMethod</item>
<item name="imeFullscreenBackground">?colorBackground</item>
<item name="imeExtractEnterAnimation">@anim/input_method_extract_enter</item>
- <item name="windowSwipeToDismiss">false</item>
+ <item name="windowSwipeToDismiss">true</item>
</style>
<!-- DeviceDefault theme for dialog windows and activities. In contrast to Material, the
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 4f20fce..9d902c9 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -4673,8 +4673,8 @@
<!-- The component name for the default system on-device intelligence service, -->
<string name="config_defaultOnDeviceIntelligenceService" translatable="false"></string>
- <!-- The component name for the default system on-device trusted inference service. -->
- <string name="config_defaultOnDeviceTrustedInferenceService" translatable="false"></string>
+ <!-- The component name for the default system on-device sandboxed inference service. -->
+ <string name="config_defaultOnDeviceSandboxedInferenceService" translatable="false"></string>
<!-- Component name that accepts ACTION_SEND intents for requesting ambient context consent for
wearable sensing. -->
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 59066eb..238772f 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -6434,4 +6434,6 @@
<string name="satellite_notification_open_message">Open Messages</string>
<!-- Invoke Satellite setting activity of Settings -->
<string name="satellite_notification_how_it_works">How it works</string>
+ <!-- Initial/System provided label shown for an app which gets unarchived. [CHAR LIMIT=64]. -->
+ <string name="unarchival_session_app_label">Pending...</string>
</resources>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 150951f..4b71654 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -3916,7 +3916,7 @@
<java-symbol type="string" name="config_ambientContextEventArrayExtraKey" />
<java-symbol type="string" name="config_defaultWearableSensingService" />
<java-symbol type="string" name="config_defaultOnDeviceIntelligenceService" />
- <java-symbol type="string" name="config_defaultOnDeviceTrustedInferenceService" />
+ <java-symbol type="string" name="config_defaultOnDeviceSandboxedInferenceService" />
<java-symbol type="string" name="config_retailDemoPackage" />
<java-symbol type="string" name="config_retailDemoPackageSignature" />
@@ -5373,4 +5373,6 @@
<java-symbol type="string" name="config_defaultContextualSearchKey" />
<java-symbol type="string" name="config_defaultContextualSearchEnabled" />
<java-symbol type="string" name="config_defaultContextualSearchLegacyEnabled" />
+
+ <java-symbol type="string" name="unarchival_session_app_label" />
</resources>
diff --git a/core/tests/BroadcastRadioTests/src/com/android/server/broadcastradio/aidl/ConversionUtilsTest.java b/core/tests/BroadcastRadioTests/src/com/android/server/broadcastradio/aidl/ConversionUtilsTest.java
index 15bb66b..8d9fad9 100644
--- a/core/tests/BroadcastRadioTests/src/com/android/server/broadcastradio/aidl/ConversionUtilsTest.java
+++ b/core/tests/BroadcastRadioTests/src/com/android/server/broadcastradio/aidl/ConversionUtilsTest.java
@@ -90,7 +90,7 @@
private static final long TEST_HD_FREQUENCY_VALUE = 95_300;
private static final long TEST_HD_STATION_ID_EXT_VALUE = 0x100000001L
| (TEST_HD_FREQUENCY_VALUE << 36);
- private static final long TEST_HD_LOCATION_VALUE = 0x89CC8E06CCB9ECL;
+ private static final long TEST_HD_LOCATION_VALUE = 0x4E647007665CF6L;
private static final long TEST_VENDOR_ID_VALUE = 9_901;
private static final ProgramSelector.Identifier TEST_DAB_SID_EXT_ID =
diff --git a/core/tests/bugreports/src/com/android/os/bugreports/tests/BugreportManagerTest.java b/core/tests/bugreports/src/com/android/os/bugreports/tests/BugreportManagerTest.java
index 37a499a..6cc5485 100644
--- a/core/tests/bugreports/src/com/android/os/bugreports/tests/BugreportManagerTest.java
+++ b/core/tests/bugreports/src/com/android/os/bugreports/tests/BugreportManagerTest.java
@@ -110,8 +110,6 @@
Paths.get("/data/misc/wmtrace/ime_trace_service.winscope"),
Paths.get("/data/misc/wmtrace/wm_trace.winscope"),
Paths.get("/data/misc/wmtrace/wm_log.winscope"),
- Paths.get("/data/misc/wmtrace/wm_transition_trace.winscope"),
- Paths.get("/data/misc/wmtrace/shell_transition_trace.winscope"),
};
private Handler mHandler;
@@ -257,6 +255,38 @@
assertThatAllFileContentsAreDifferent(preDumpedTraceFiles, actualTraceFiles);
}
+ @LargeTest
+ @Test
+ public void noPreDumpData_then_fullWithUsePreDumpFlag_ignoresFlag() throws Exception {
+ startPreDumpedUiTraces();
+
+ mBrm.preDumpUiData();
+ waitTillDumpstateExitedOrTimeout();
+
+ // Simulate lost of pre-dumped data.
+ // For example it can happen in this scenario:
+ // 1. Pre-dump data
+ // 2. Start bugreport + "use pre-dump" flag (USE AND REMOVE THE PRE-DUMP FROM DISK)
+ // 3. Start bugreport + "use pre-dump" flag (NO PRE-DUMP AVAILABLE ON DISK)
+ removeFilesIfNeeded(UI_TRACES_PREDUMPED);
+
+ // Start bugreport with "use predump" flag. Because the pre-dumped data is not available
+ // the flag will be ignored and data will be dumped as in normal flow.
+ BugreportCallbackImpl callback = new BugreportCallbackImpl();
+ mBrm.startBugreport(mBugreportFd, null, fullWithUsePreDumpFlag(), mExecutor,
+ callback);
+ shareConsentDialog(ConsentReply.ALLOW);
+ waitTillDoneOrTimeout(callback);
+
+ stopPreDumpedUiTraces();
+
+ assertThat(callback.isDone()).isTrue();
+ assertThat(mBugreportFile.length()).isGreaterThan(0L);
+ assertFdsAreClosed(mBugreportFd);
+
+ assertThatBugreportContainsFiles(UI_TRACES_PREDUMPED);
+ }
+
@Test
public void simultaneousBugreportsNotAllowed() throws Exception {
// Start bugreport #1
@@ -506,9 +536,6 @@
InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
"cmd window tracing start"
);
- InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
- "service call SurfaceFlinger 1025 i32 1"
- );
}
private static void stopPreDumpedUiTraces() {
@@ -611,6 +638,14 @@
return files;
}
+ private static void removeFilesIfNeeded(Path[] paths) throws Exception {
+ for (Path path : paths) {
+ InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand(
+ "rm -f " + path.toString()
+ );
+ }
+ }
+
private static ParcelFileDescriptor parcelFd(File file) throws Exception {
return ParcelFileDescriptor.open(file,
ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_APPEND);
diff --git a/core/tests/coretests/res/layout/view_velocity_test.xml b/core/tests/coretests/res/layout/view_velocity_test.xml
deleted file mode 100644
index 98154a4..0000000
--- a/core/tests/coretests/res/layout/view_velocity_test.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2024 The Android Open Source Project
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/frameLayout"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <View
- android:id="@+id/moving_view"
- android:layout_width="50dp"
- android:layout_height="50dp" />
-</FrameLayout>
diff --git a/core/tests/coretests/src/android/view/ViewVelocityTest.java b/core/tests/coretests/src/android/view/ViewVelocityTest.java
deleted file mode 100644
index 128c54b..0000000
--- a/core/tests/coretests/src/android/view/ViewVelocityTest.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2024 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.view;
-
-import static junit.framework.Assert.assertEquals;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import android.app.Activity;
-import android.os.SystemClock;
-
-import androidx.test.annotation.UiThreadTest;
-import androidx.test.filters.SmallTest;
-import androidx.test.rule.ActivityTestRule;
-import androidx.test.runner.AndroidJUnit4;
-
-import com.android.frameworks.coretests.R;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ViewVelocityTest {
-
- @Rule
- public ActivityTestRule<ViewCaptureTestActivity> mActivityRule = new ActivityTestRule<>(
- ViewCaptureTestActivity.class);
-
- private Activity mActivity;
- private View mMovingView;
- private ViewRootImpl mViewRoot;
-
- @Before
- public void setUp() throws Throwable {
- mActivity = mActivityRule.getActivity();
- mActivityRule.runOnUiThread(() -> {
- mActivity.setContentView(R.layout.view_velocity_test);
- mMovingView = mActivity.findViewById(R.id.moving_view);
- });
- ViewParent parent = mActivity.getWindow().getDecorView().getParent();
- while (parent instanceof View) {
- parent = parent.getParent();
- }
- mViewRoot = (ViewRootImpl) parent;
- }
-
- @UiThreadTest
- @Test
- public void frameRateChangesWhenContentMoves() {
- mMovingView.offsetLeftAndRight(100);
- float frameRate = mViewRoot.getPreferredFrameRate();
- assertTrue(frameRate > 0);
- }
-
- @UiThreadTest
- @Test
- public void firstFrameNoMovement() {
- assertEquals(0f, mViewRoot.getPreferredFrameRate(), 0f);
- }
-
- @Test
- public void touchBoostDisable() throws Throwable {
- mActivityRule.runOnUiThread(() -> {
- long now = SystemClock.uptimeMillis();
- MotionEvent down = MotionEvent.obtain(
- /* downTime */ now,
- /* eventTime */ now,
- /* action */ MotionEvent.ACTION_DOWN,
- /* x */ 0f,
- /* y */ 0f,
- /* metaState */ 0
- );
- mActivity.dispatchTouchEvent(down);
- mMovingView.offsetLeftAndRight(10);
- });
- mActivityRule.runOnUiThread(() -> {
- mMovingView.invalidate();
- });
-
- mActivityRule.runOnUiThread(() -> {
- assertFalse(mViewRoot.getIsTouchBoosting());
- });
- }
-}
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index b6ce9b6..f9ac02a 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -789,10 +789,8 @@
* @param m The 4x4 matrix to preconcatenate with the current matrix
*/
@FlaggedApi(Flags.FLAG_MATRIX_44)
- public void concat44(@Nullable Matrix44 m) {
- if (m != null) {
- nConcat(mNativeCanvasWrapper, m.mBackingArray);
- }
+ public void concat(@Nullable Matrix44 m) {
+ if (m != null) nConcat(mNativeCanvasWrapper, m.mBackingArray);
}
/**
diff --git a/graphics/java/android/graphics/Matrix44.java b/graphics/java/android/graphics/Matrix44.java
index 7cc0eb7..a99e201 100644
--- a/graphics/java/android/graphics/Matrix44.java
+++ b/graphics/java/android/graphics/Matrix44.java
@@ -17,6 +17,7 @@
package android.graphics;
import android.annotation.FlaggedApi;
+import android.annotation.IntRange;
import android.annotation.NonNull;
import com.android.graphics.hwui.flags.Flags;
@@ -98,11 +99,11 @@
/**
* Gets the value at the matrix's row and column.
*
- * @param row An integer from 0 to 4 indicating the row of the value to get
- * @param col An integer from 0 to 4 indicating the column of the value to get
+ * @param row An integer from 0 to 3 indicating the row of the value to get
+ * @param col An integer from 0 to 3 indicating the column of the value to get
*/
@FlaggedApi(Flags.FLAG_MATRIX_44)
- public float get(int row, int col) {
+ public float get(@IntRange(from = 0, to = 3) int row, @IntRange(from = 0, to = 3) int col) {
if (row >= 0 && row < 4 && col >= 0 && col < 4) {
return mBackingArray[row * 4 + col];
}
@@ -112,12 +113,13 @@
/**
* Sets the value at the matrix's row and column to the provided value.
*
- * @param row An integer from 0 to 4 indicating the row of the value to change
- * @param col An integer from 0 to 4 indicating the column of the value to change
+ * @param row An integer from 0 to 3 indicating the row of the value to change
+ * @param col An integer from 0 to 3 indicating the column of the value to change
* @param val The value the element at the specified index will be set to
*/
@FlaggedApi(Flags.FLAG_MATRIX_44)
- public void set(int row, int col, float val) {
+ public void set(@IntRange(from = 0, to = 3) int row, @IntRange(from = 0, to = 3) int col,
+ float val) {
if (row >= 0 && row < 4 && col >= 0 && col < 4) {
mBackingArray[row * 4 + col] = val;
} else {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
index 4d47ca9..139cde2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/phone/PipController.java
@@ -983,7 +983,13 @@
// cache current min/max size
Point minSize = mPipBoundsState.getMinSize();
Point maxSize = mPipBoundsState.getMaxSize();
- mPipBoundsState.updateMinMaxSize(pictureInPictureParams.getAspectRatioFloat());
+ final float aspectRatioFloat;
+ if (pictureInPictureParams.hasSetAspectRatio()) {
+ aspectRatioFloat = pictureInPictureParams.getAspectRatioFloat();
+ } else {
+ aspectRatioFloat = mPipBoundsAlgorithm.getDefaultAspectRatio();
+ }
+ mPipBoundsState.updateMinMaxSize(aspectRatioFloat);
final Rect entryBounds = mPipTaskOrganizer.startSwipePipToHome(componentName, activityInfo,
pictureInPictureParams);
// restore min/max size, as this is referenced later in OnDisplayChangingListener and needs
diff --git a/location/java/android/location/provider/ForwardGeocodeRequest.java b/location/java/android/location/provider/ForwardGeocodeRequest.java
index 8f227b1..89d14fb 100644
--- a/location/java/android/location/provider/ForwardGeocodeRequest.java
+++ b/location/java/android/location/provider/ForwardGeocodeRequest.java
@@ -260,7 +260,11 @@
mCallingAttributionTag = null;
}
- /** Sets the attribution tag. */
+ /**
+ * Sets the attribution tag.
+ *
+ * @param attributionTag The attribution tag to associate with the request.
+ */
@NonNull
public Builder setCallingAttributionTag(@NonNull String attributionTag) {
mCallingAttributionTag = attributionTag;
diff --git a/location/java/android/location/provider/ReverseGeocodeRequest.java b/location/java/android/location/provider/ReverseGeocodeRequest.java
index 57c9047..2107707 100644
--- a/location/java/android/location/provider/ReverseGeocodeRequest.java
+++ b/location/java/android/location/provider/ReverseGeocodeRequest.java
@@ -207,7 +207,11 @@
mCallingAttributionTag = null;
}
- /** Sets the attribution tag. */
+ /**
+ * Sets the attribution tag.
+ *
+ * @param attributionTag The attribution tag to associate with the request.
+ */
@NonNull
public Builder setCallingAttributionTag(@NonNull String attributionTag) {
mCallingAttributionTag = attributionTag;
diff --git a/native/android/input.cpp b/native/android/input.cpp
index 53699bc..0a22314 100644
--- a/native/android/input.cpp
+++ b/native/android/input.cpp
@@ -124,11 +124,11 @@
}
float AMotionEvent_getXOffset(const AInputEvent* motion_event) {
- return static_cast<const MotionEvent*>(motion_event)->getXOffset();
+ return static_cast<const MotionEvent*>(motion_event)->getRawXOffset();
}
float AMotionEvent_getYOffset(const AInputEvent* motion_event) {
- return static_cast<const MotionEvent*>(motion_event)->getYOffset();
+ return static_cast<const MotionEvent*>(motion_event)->getRawYOffset();
}
float AMotionEvent_getXPrecision(const AInputEvent* motion_event) {
diff --git a/nfc/Android.bp b/nfc/Android.bp
index b6bc40d..7dd16ba 100644
--- a/nfc/Android.bp
+++ b/nfc/Android.bp
@@ -38,6 +38,7 @@
name: "framework-nfc",
libs: [
"unsupportedappusage", // for android.compat.annotation.UnsupportedAppUsage
+ "framework-permission-s",
],
static_libs: [
"android.nfc.flags-aconfig-java",
diff --git a/nfc/api/current.txt b/nfc/api/current.txt
index c0db089..54f1421 100644
--- a/nfc/api/current.txt
+++ b/nfc/api/current.txt
@@ -194,13 +194,13 @@
package android.nfc.cardemulation {
public final class CardEmulation {
- method public boolean categoryAllowsForegroundPreference(String);
+ method @Deprecated public boolean categoryAllowsForegroundPreference(String);
method @Nullable @RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO) public java.util.List<java.lang.String> getAidsForPreferredPaymentService();
method public java.util.List<java.lang.String> getAidsForService(android.content.ComponentName, String);
- method @Nullable @RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO) public CharSequence getDescriptionForPreferredPaymentService();
+ method @Deprecated @Nullable @RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO) public CharSequence getDescriptionForPreferredPaymentService();
method public static android.nfc.cardemulation.CardEmulation getInstance(android.nfc.NfcAdapter);
- method @Nullable @RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO) public String getRouteDestinationForPreferredPaymentService();
- method public int getSelectionModeForCategory(String);
+ method @Deprecated @Nullable @RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO) public String getRouteDestinationForPreferredPaymentService();
+ method @Deprecated public int getSelectionModeForCategory(String);
method public boolean isDefaultServiceForAid(android.content.ComponentName, String);
method public boolean isDefaultServiceForCategory(android.content.ComponentName, String);
method public boolean registerAidsForService(android.content.ComponentName, String, java.util.List<java.lang.String>);
diff --git a/nfc/java/android/nfc/cardemulation/CardEmulation.java b/nfc/java/android/nfc/cardemulation/CardEmulation.java
index ea58504..e55f540 100644
--- a/nfc/java/android/nfc/cardemulation/CardEmulation.java
+++ b/nfc/java/android/nfc/cardemulation/CardEmulation.java
@@ -27,6 +27,7 @@
import android.annotation.UserHandleAware;
import android.annotation.UserIdInt;
import android.app.Activity;
+import android.app.role.RoleManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
@@ -278,13 +279,22 @@
* @param category The category, e.g. {@link #CATEGORY_PAYMENT}
* @return whether AIDs in the category can be handled by a service
* specified by the foreground app.
+ *
+ * @deprecated see {@link android.app.role.RoleManager#ROLE_WALLET}. The definition of the
+ * Preferred Payment service is no longer valid. All routings will be done in a AID
+ * category agnostic manner.
*/
@SuppressWarnings("NonUserGetterCalled")
+ @Deprecated
public boolean categoryAllowsForegroundPreference(String category) {
+ Context contextAsUser = mContext.createContextAsUser(
+ UserHandle.of(UserHandle.myUserId()), 0);
+ RoleManager roleManager = contextAsUser.getSystemService(RoleManager.class);
+ if (roleManager.isRoleAvailable(RoleManager.ROLE_WALLET)) {
+ return true;
+ }
if (CATEGORY_PAYMENT.equals(category)) {
boolean preferForeground = false;
- Context contextAsUser = mContext.createContextAsUser(
- UserHandle.of(UserHandle.myUserId()), 0);
try {
preferForeground = Settings.Secure.getInt(
contextAsUser.getContentResolver(),
@@ -309,7 +319,12 @@
* to pick a service if there is a conflict.
* @param category The category, for example {@link #CATEGORY_PAYMENT}
* @return the selection mode for the passed in category
+ *
+ * @deprecated see {@link android.app.role.RoleManager#ROLE_WALLET}. The definition of the
+ * Preferred Payment service is no longer valid. All routings will be done in a AID
+ * category agnostic manner.
*/
+ @Deprecated
public int getSelectionModeForCategory(String category) {
if (CATEGORY_PAYMENT.equals(category)) {
boolean paymentRegistered = false;
@@ -792,8 +807,15 @@
* (e.g. eSE/eSE1, eSE2, etc.).
* 2. "OffHost" if the payment service does not specify secure element
* name.
+ *
+ * @deprecated see {@link android.app.role.RoleManager#ROLE_WALLET}. The definition of the
+ * Preferred Payment service is no longer valid. All routings will go to the Wallet Holder app.
+ * A payment service will be selected automatically based on registered AIDs. In the case of
+ * multiple services that register for the same payment AID, the selection will be done on
+ * an alphabetical order based on the component names.
*/
@RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO)
+ @Deprecated
@Nullable
public String getRouteDestinationForPreferredPaymentService() {
try {
@@ -836,8 +858,15 @@
* Returns a user-visible description of the preferred payment service.
*
* @return the preferred payment service description
+ *
+ * @deprecated see {@link android.app.role.RoleManager#ROLE_WALLET}. The definition of the
+ * Preferred Payment service is no longer valid. All routings will go to the Wallet Holder app.
+ * A payment service will be selected automatically based on registered AIDs. In the case of
+ * multiple services that register for the same payment AID, the selection will be done on
+ * an alphabetical order based on the component names.
*/
@RequiresPermission(android.Manifest.permission.NFC_PREFERRED_PAYMENT_INFO)
+ @Deprecated
@Nullable
public CharSequence getDescriptionForPreferredPaymentService() {
try {
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
index 4e1f4ee..3363ac0 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/autofill/CredentialAutofillService.kt
@@ -29,6 +29,7 @@
import android.credentials.selection.Entry
import android.credentials.selection.GetCredentialProviderData
import android.credentials.selection.ProviderData
+import android.graphics.BlendMode
import android.graphics.drawable.Icon
import android.os.Bundle
import android.os.CancellationSignal
@@ -353,6 +354,7 @@
val sliceBuilder = InlineSuggestionUi
.newContentBuilder(pendingIntent)
.setTitle(displayName)
+ icon.setTintBlendMode(BlendMode.DST)
sliceBuilder.setStartIcon(icon)
if (primaryEntry.credentialType ==
CredentialType.PASSKEY && duplicateDisplayNameForPasskeys[displayName] == true) {
diff --git a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/InlinePresentationFactory.kt b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/InlinePresentationFactory.kt
index 3ebdd20..ff421bc 100644
--- a/packages/CredentialManager/src/com/android/credentialmanager/common/ui/InlinePresentationFactory.kt
+++ b/packages/CredentialManager/src/com/android/credentialmanager/common/ui/InlinePresentationFactory.kt
@@ -21,63 +21,20 @@
import android.content.Context
import android.util.Size
import android.widget.inline.InlinePresentationSpec
-import androidx.autofill.inline.common.TextViewStyle
-import androidx.autofill.inline.common.ViewStyle
-import androidx.autofill.inline.UiVersions
-import androidx.autofill.inline.UiVersions.Style
-import androidx.autofill.inline.v1.InlineSuggestionUi
-import androidx.core.content.ContextCompat
-import android.util.TypedValue
-import android.graphics.Typeface
-
class InlinePresentationsFactory {
companion object {
- private const val googleSansMediumFontFamily = "google-sans-medium"
- private const val googleSansTextFontFamily = "google-sans-text"
- // There is no min width required for now but this is needed for the spec builder
- private const val minInlineWidth = 5000
+ // There is no max width required for now but this is needed for the spec builder
+ private const val maxInlineWidth = 5000
fun modifyInlinePresentationSpec(context: Context,
originalSpec: InlinePresentationSpec): InlinePresentationSpec {
return InlinePresentationSpec.Builder(Size(originalSpec.minSize.width, originalSpec
.minSize.height),
- Size(minInlineWidth, originalSpec
+ Size(maxInlineWidth, originalSpec
.maxSize.height))
- .setStyle(UiVersions.newStylesBuilder().addStyle(getStyle(context)).build())
- .build()
- }
-
-
- fun getStyle(context: Context): Style {
- val textColorPrimary = ContextCompat.getColor(context,
- com.android.credentialmanager.R.color.text_primary)
- val textColorSecondary = ContextCompat.getColor(context,
- com.android.credentialmanager.R.color.text_secondary)
- val textColorBackground = ContextCompat.getColor(context,
- com.android.credentialmanager.R.color.inline_background)
- val chipHorizontalPadding = context.resources.getDimensionPixelSize(com.android
- .credentialmanager.R.dimen.horizontal_chip_padding)
- val chipVerticalPadding = context.resources.getDimensionPixelSize(com.android
- .credentialmanager.R.dimen.vertical_chip_padding)
- return InlineSuggestionUi.newStyleBuilder()
- .setChipStyle(
- ViewStyle.Builder().setPadding(chipHorizontalPadding,
- chipVerticalPadding,
- chipHorizontalPadding, chipVerticalPadding).build()
- )
- .setTitleStyle(
- TextViewStyle.Builder().setTextColor(textColorPrimary).setTextSize
- (TypedValue.COMPLEX_UNIT_DIP, 14F)
- .setTypeface(googleSansMediumFontFamily,
- Typeface.NORMAL).setBackgroundColor(textColorBackground)
- .build()
- )
- .setSubtitleStyle(TextViewStyle.Builder().setTextColor(textColorSecondary)
- .setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12F).setTypeface
- (googleSansTextFontFamily, Typeface.NORMAL).setBackgroundColor
- (textColorBackground).build())
+ .setStyle(originalSpec.getStyle())
.build()
}
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
index 33086f98..e489bc5 100644
--- a/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
+++ b/packages/SettingsLib/src/com/android/settingslib/applications/ApplicationsState.java
@@ -1918,16 +1918,6 @@
}
};
- public static final AppFilter FILTER_PERSONAL_OR_PRIVATE = new AppFilter() {
- @Override
- public void init() {}
-
- @Override
- public boolean filterApp(AppEntry entry) {
- return entry.showInPersonalTab || entry.isPrivateProfile();
- }
- };
-
/**
* Displays a combined list with "downloaded" and "visible in launcher" apps only.
*/
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothLeBroadcastMetadataExt.kt b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothLeBroadcastMetadataExt.kt
index da1fd55..0c7d6f0 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothLeBroadcastMetadataExt.kt
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothLeBroadcastMetadataExt.kt
@@ -311,7 +311,7 @@
}
builder.apply {
- setSourceDevice(device, sourceAddrType)
+ setSourceDevice(device, addrType)
setSourceAdvertisingSid(sourceAdvertiserSid)
setBroadcastId(broadcastId)
setBroadcastName(broadcastName)
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
index 5f026c4..e34c50e 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/InfoMediaManager.java
@@ -44,7 +44,6 @@
import static com.android.settingslib.media.LocalMediaManager.MediaDeviceState.STATE_SELECTED;
import android.annotation.TargetApi;
-import android.app.Notification;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
@@ -67,6 +66,7 @@
import com.android.settingslib.media.flags.Flags;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
@@ -81,11 +81,43 @@
/** InfoMediaManager provide interface to get InfoMediaDevice list. */
@RequiresApi(Build.VERSION_CODES.R)
-public abstract class InfoMediaManager extends MediaManager {
+public abstract class InfoMediaManager {
+ /** Callback for notifying device is added, removed and attributes changed. */
+ public interface MediaDeviceCallback {
- private static final String TAG = "InfoMediaManager";
- private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
- protected final List<MediaDevice> mMediaDevices = new CopyOnWriteArrayList<>();
+ /**
+ * Callback for notifying MediaDevice list is added.
+ *
+ * @param devices the MediaDevice list
+ */
+ void onDeviceListAdded(@NonNull List<MediaDevice> devices);
+
+ /**
+ * Callback for notifying MediaDevice list is removed.
+ *
+ * @param devices the MediaDevice list
+ */
+ void onDeviceListRemoved(@NonNull List<MediaDevice> devices);
+
+ /**
+ * Callback for notifying connected MediaDevice is changed.
+ *
+ * @param id the id of MediaDevice
+ */
+ void onConnectedDeviceChanged(@Nullable String id);
+
+ /**
+ * 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);
+ }
/** Checked exception that signals the specified package is not present in the system. */
public static class PackageNotAvailableException extends Exception {
@@ -94,19 +126,22 @@
}
}
+ private static final String TAG = "InfoMediaManager";
+ private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+ protected final List<MediaDevice> mMediaDevices = new CopyOnWriteArrayList<>();
+ @NonNull protected final Context mContext;
@NonNull protected final String mPackageName;
+ private final Collection<MediaDeviceCallback> mCallbacks = new CopyOnWriteArrayList<>();
private MediaDevice mCurrentConnectedDevice;
private final LocalBluetoothManager mBluetoothManager;
private final Map<String, RouteListingPreference.Item> mPreferenceItemMap =
new ConcurrentHashMap<>();
/* package */ InfoMediaManager(
- Context context,
+ @NonNull Context context,
@NonNull String packageName,
- Notification notification,
- LocalBluetoothManager localBluetoothManager) {
- super(context, notification);
-
+ @NonNull LocalBluetoothManager localBluetoothManager) {
+ mContext = context;
mBluetoothManager = localBluetoothManager;
mPackageName = packageName;
}
@@ -115,7 +150,6 @@
public static InfoMediaManager createInstance(
Context context,
@Nullable String packageName,
- Notification notification,
LocalBluetoothManager localBluetoothManager) {
// The caller is only interested in system routes (headsets, built-in speakers, etc), and is
@@ -127,17 +161,14 @@
if (Flags.useMediaRouter2ForInfoMediaManager()) {
try {
- return new RouterInfoMediaManager(
- context, packageName, notification, localBluetoothManager);
+ return new RouterInfoMediaManager(context, packageName, localBluetoothManager);
} catch (PackageNotAvailableException ex) {
// TODO: b/293578081 - Propagate this exception to callers for proper handling.
Log.w(TAG, "Returning a no-op InfoMediaManager for package " + packageName);
- return new NoOpInfoMediaManager(
- context, packageName, notification, localBluetoothManager);
+ return new NoOpInfoMediaManager(context, packageName, localBluetoothManager);
}
} else {
- return new ManagerInfoMediaManager(
- context, packageName, notification, localBluetoothManager);
+ return new ManagerInfoMediaManager(context, packageName, localBluetoothManager);
}
}
@@ -239,6 +270,38 @@
return null;
}
+ protected final void registerCallback(MediaDeviceCallback callback) {
+ if (!mCallbacks.contains(callback)) {
+ mCallbacks.add(callback);
+ }
+ }
+
+ protected final void unregisterCallback(MediaDeviceCallback callback) {
+ mCallbacks.remove(callback);
+ }
+
+ private void dispatchDeviceListAdded(@NonNull List<MediaDevice> devices) {
+ for (MediaDeviceCallback callback : getCallbacks()) {
+ callback.onDeviceListAdded(new ArrayList<>(devices));
+ }
+ }
+
+ private void dispatchConnectedDeviceChanged(String id) {
+ for (MediaDeviceCallback callback : getCallbacks()) {
+ callback.onConnectedDeviceChanged(id);
+ }
+ }
+
+ protected void dispatchOnRequestFailed(int reason) {
+ for (MediaDeviceCallback callback : getCallbacks()) {
+ callback.onRequestFailed(reason);
+ }
+ }
+
+ private Collection<MediaDeviceCallback> getCallbacks() {
+ return new CopyOnWriteArrayList<>(mCallbacks);
+ }
+
/**
* Get current device that played media.
* @return MediaDevice
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
index 5925492..63056b6 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/LocalMediaManager.java
@@ -138,8 +138,7 @@
}
mInfoMediaManager =
- InfoMediaManager.createInstance(
- context, packageName, notification, mLocalBluetoothManager);
+ InfoMediaManager.createInstance(context, packageName, mLocalBluetoothManager);
}
/**
@@ -505,9 +504,9 @@
return new CopyOnWriteArrayList<>(mCallbacks);
}
- class MediaDeviceCallback implements MediaManager.MediaDeviceCallback {
+ class MediaDeviceCallback implements InfoMediaManager.MediaDeviceCallback {
@Override
- public void onDeviceListAdded(List<MediaDevice> devices) {
+ public void onDeviceListAdded(@NonNull List<MediaDevice> devices) {
synchronized (mMediaDevicesLock) {
mMediaDevices.clear();
mMediaDevices.addAll(devices);
@@ -637,7 +636,7 @@
}
@Override
- public void onDeviceListRemoved(List<MediaDevice> devices) {
+ public void onDeviceListRemoved(@NonNull List<MediaDevice> devices) {
synchronized (mMediaDevicesLock) {
mMediaDevices.removeAll(devices);
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/ManagerInfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/ManagerInfoMediaManager.java
index 453e807..c4fac35 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/ManagerInfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/ManagerInfoMediaManager.java
@@ -16,7 +16,6 @@
package com.android.settingslib.media;
-import android.app.Notification;
import android.content.Context;
import android.media.MediaRoute2Info;
import android.media.MediaRouter2Manager;
@@ -54,9 +53,8 @@
/* package */ ManagerInfoMediaManager(
Context context,
@NonNull String packageName,
- Notification notification,
LocalBluetoothManager localBluetoothManager) {
- super(context, packageName, notification, localBluetoothManager);
+ super(context, packageName, localBluetoothManager);
mRouterManager = MediaRouter2Manager.getInstance(context);
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
deleted file mode 100644
index d562c8a..0000000
--- a/packages/SettingsLib/src/com/android/settingslib/media/MediaManager.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright 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.settingslib.media;
-
-import android.annotation.NonNull;
-import android.app.Notification;
-import android.content.Context;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-/**
- * MediaManager provide interface to get MediaDevice list.
- */
-public abstract class MediaManager {
-
- protected final Collection<MediaDeviceCallback> mCallbacks = new CopyOnWriteArrayList<>();
-
- protected Context mContext;
- protected Notification mNotification;
-
- MediaManager(Context context, Notification notification) {
- mContext = context;
- mNotification = notification;
- }
-
- protected void registerCallback(MediaDeviceCallback callback) {
- if (!mCallbacks.contains(callback)) {
- mCallbacks.add(callback);
- }
- }
-
- protected void unregisterCallback(MediaDeviceCallback callback) {
- if (mCallbacks.contains(callback)) {
- mCallbacks.remove(callback);
- }
- }
-
- protected void dispatchDeviceListAdded(@NonNull List<MediaDevice> devices) {
- for (MediaDeviceCallback callback : getCallbacks()) {
- callback.onDeviceListAdded(new ArrayList<>(devices));
- }
- }
-
- protected void dispatchDeviceListRemoved(List<MediaDevice> devices) {
- for (MediaDeviceCallback callback : getCallbacks()) {
- callback.onDeviceListRemoved(devices);
- }
- }
-
- protected void dispatchConnectedDeviceChanged(String id) {
- for (MediaDeviceCallback callback : getCallbacks()) {
- callback.onConnectedDeviceChanged(id);
- }
- }
-
- protected void dispatchOnRequestFailed(int reason) {
- for (MediaDeviceCallback callback : getCallbacks()) {
- callback.onRequestFailed(reason);
- }
- }
-
- private Collection<MediaDeviceCallback> getCallbacks() {
- return new CopyOnWriteArrayList<>(mCallbacks);
- }
-
- /**
- * Callback for notifying device is added, removed and attributes changed.
- */
- public interface MediaDeviceCallback {
-
- /**
- * Callback for notifying MediaDevice list is added.
- *
- * @param devices the MediaDevice list
- */
- void onDeviceListAdded(List<MediaDevice> devices);
-
- /**
- * Callback for notifying MediaDevice list is removed.
- *
- * @param devices the MediaDevice list
- */
- void onDeviceListRemoved(List<MediaDevice> devices);
-
- /**
- * Callback for notifying connected MediaDevice is changed.
- *
- * @param id the id of MediaDevice
- */
- void onConnectedDeviceChanged(String id);
-
- /**
- * 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/media/NoOpInfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/NoOpInfoMediaManager.java
index ea4de39..ff4d4dd 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/NoOpInfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/NoOpInfoMediaManager.java
@@ -16,7 +16,6 @@
package com.android.settingslib.media;
-import android.app.Notification;
import android.content.Context;
import android.media.MediaRoute2Info;
import android.media.RouteListingPreference;
@@ -42,9 +41,8 @@
NoOpInfoMediaManager(
Context context,
@NonNull String packageName,
- Notification notification,
LocalBluetoothManager localBluetoothManager) {
- super(context, packageName, notification, localBluetoothManager);
+ super(context, packageName, localBluetoothManager);
}
@Override
diff --git a/packages/SettingsLib/src/com/android/settingslib/media/RouterInfoMediaManager.java b/packages/SettingsLib/src/com/android/settingslib/media/RouterInfoMediaManager.java
index df03167..9c82cb1 100644
--- a/packages/SettingsLib/src/com/android/settingslib/media/RouterInfoMediaManager.java
+++ b/packages/SettingsLib/src/com/android/settingslib/media/RouterInfoMediaManager.java
@@ -17,7 +17,6 @@
package com.android.settingslib.media;
import android.annotation.SuppressLint;
-import android.app.Notification;
import android.content.Context;
import android.media.MediaRoute2Info;
import android.media.MediaRouter2;
@@ -71,10 +70,9 @@
/* package */ RouterInfoMediaManager(
Context context,
@NonNull String packageName,
- Notification notification,
LocalBluetoothManager localBluetoothManager)
throws PackageNotAvailableException {
- super(context, packageName, notification, localBluetoothManager);
+ super(context, packageName, localBluetoothManager);
MediaRouter2 router = null;
diff --git a/packages/SettingsLib/tests/integ/src/com/android/settingslib/media/InfoMediaManagerIntegTest.java b/packages/SettingsLib/tests/integ/src/com/android/settingslib/media/InfoMediaManagerIntegTest.java
index c647cbb..f0185b9 100644
--- a/packages/SettingsLib/tests/integ/src/com/android/settingslib/media/InfoMediaManagerIntegTest.java
+++ b/packages/SettingsLib/tests/integ/src/com/android/settingslib/media/InfoMediaManagerIntegTest.java
@@ -64,22 +64,21 @@
@RequiresFlagsEnabled(FLAG_USE_MEDIA_ROUTER2_FOR_INFO_MEDIA_MANAGER)
public void createInstance_withMR2FlagOn_returnsRouterInfoMediaManager() {
InfoMediaManager manager =
- InfoMediaManager.createInstance(mContext, mContext.getPackageName(), null, null);
+ InfoMediaManager.createInstance(mContext, mContext.getPackageName(), null);
assertThat(manager).isInstanceOf(RouterInfoMediaManager.class);
}
@Test
@RequiresFlagsEnabled(FLAG_USE_MEDIA_ROUTER2_FOR_INFO_MEDIA_MANAGER)
public void createInstance_withMR2FlagOn_withFakePackage_returnsNoOpInfoMediaManager() {
- InfoMediaManager manager =
- InfoMediaManager.createInstance(mContext, FAKE_PACKAGE, null, null);
+ InfoMediaManager manager = InfoMediaManager.createInstance(mContext, FAKE_PACKAGE, null);
assertThat(manager).isInstanceOf(NoOpInfoMediaManager.class);
}
@Test
@RequiresFlagsEnabled(FLAG_USE_MEDIA_ROUTER2_FOR_INFO_MEDIA_MANAGER)
public void createInstance_withMR2FlagOn_withNullPackage_returnsRouterInfoMediaManager() {
- InfoMediaManager manager = InfoMediaManager.createInstance(mContext, null, null, null);
+ InfoMediaManager manager = InfoMediaManager.createInstance(mContext, null, null);
assertThat(manager).isInstanceOf(RouterInfoMediaManager.class);
}
@@ -87,7 +86,7 @@
@RequiresFlagsDisabled(FLAG_USE_MEDIA_ROUTER2_FOR_INFO_MEDIA_MANAGER)
public void createInstance_withMR2FlagOff_returnsManagerInfoMediaManager() {
InfoMediaManager manager =
- InfoMediaManager.createInstance(mContext, mContext.getPackageName(), null, null);
+ InfoMediaManager.createInstance(mContext, mContext.getPackageName(), null);
assertThat(manager).isInstanceOf(ManagerInfoMediaManager.class);
}
}
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 c159d5e..d85d253 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
@@ -91,7 +91,7 @@
@Mock
private LocalBluetoothManager mLocalBluetoothManager;
@Mock
- private MediaManager.MediaDeviceCallback mCallback;
+ private InfoMediaManager.MediaDeviceCallback mCallback;
@Mock
private MediaSessionManager mMediaSessionManager;
@Mock
@@ -109,8 +109,7 @@
doReturn(mMediaSessionManager).when(mContext).getSystemService(
Context.MEDIA_SESSION_SERVICE);
mInfoMediaManager =
- new ManagerInfoMediaManager(
- mContext, TEST_PACKAGE_NAME, null, mLocalBluetoothManager);
+ new ManagerInfoMediaManager(mContext, TEST_PACKAGE_NAME, mLocalBluetoothManager);
mShadowRouter2Manager = ShadowRouter2Manager.getShadow();
mInfoMediaManager.mRouterManager = MediaRouter2Manager.getInstance(mContext);
}
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 9a7d4f1..693b7d0 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
@@ -26,6 +26,7 @@
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
@@ -35,7 +36,6 @@
import android.media.AudioManager;
import android.media.AudioSystem;
import android.media.MediaRoute2Info;
-import android.media.MediaRouter2Manager;
import android.media.RoutingSessionInfo;
import com.android.settingslib.bluetooth.A2dpProfile;
@@ -75,8 +75,6 @@
private static final String TEST_ADDRESS = "00:01:02:03:04:05";
@Mock
- private InfoMediaManager mInfoMediaManager;
- @Mock
private LocalBluetoothManager mLocalBluetoothManager;
@Mock
private LocalMediaManager.DeviceCallback mCallback;
@@ -87,8 +85,6 @@
@Mock
private LocalBluetoothProfileManager mLocalProfileManager;
@Mock
- private MediaRouter2Manager mMediaRouter2Manager;
- @Mock
private MediaRoute2Info mRouteInfo1;
@Mock
private MediaRoute2Info mRouteInfo2;
@@ -97,6 +93,7 @@
private Context mContext;
private LocalMediaManager mLocalMediaManager;
+ private InfoMediaManager mInfoMediaManager;
private ShadowBluetoothAdapter mShadowBluetoothAdapter;
private InfoMediaDevice mInfoMediaDevice1;
private InfoMediaDevice mInfoMediaDevice2;
@@ -116,10 +113,16 @@
when(mLocalProfileManager.getA2dpProfile()).thenReturn(mA2dpProfile);
when(mLocalProfileManager.getHearingAidProfile()).thenReturn(mHapProfile);
+ // Need to call constructor to initialize final fields.
+ mInfoMediaManager = mock(
+ InfoMediaManager.class,
+ withSettings().useConstructor(mContext, TEST_PACKAGE_NAME, mLocalBluetoothManager));
+
mInfoMediaDevice1 = spy(new InfoMediaDevice(mContext, mRouteInfo1));
mInfoMediaDevice2 = new InfoMediaDevice(mContext, mRouteInfo2);
- mLocalMediaManager = new LocalMediaManager(mContext, mLocalBluetoothManager,
- mInfoMediaManager, "com.test.packagename");
+ mLocalMediaManager =
+ new LocalMediaManager(
+ mContext, mLocalBluetoothManager, mInfoMediaManager, TEST_PACKAGE_NAME);
mLocalMediaManager.mAudioManager = mAudioManager;
}
@@ -146,7 +149,6 @@
mLocalMediaManager.registerCallback(mCallback);
assertThat(mLocalMediaManager.connectDevice(device)).isTrue();
-
verify(mInfoMediaManager).connectToDevice(device);
}
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
deleted file mode 100644
index c3237f0..0000000
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/media/MediaManagerTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.settingslib.media;
-
-
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.content.Context;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.RobolectricTestRunner;
-import org.robolectric.RuntimeEnvironment;
-
-import java.util.Collections;
-
-@RunWith(RobolectricTestRunner.class)
-public class MediaManagerTest {
-
- private static final String TEST_ID = "test_id";
-
- @Mock
- private MediaManager.MediaDeviceCallback mCallback;
- @Mock
- private MediaDevice mDevice;
-
- private MediaManager mMediaManager;
- private Context mContext;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- mContext = RuntimeEnvironment.application;
-
- when(mDevice.getId()).thenReturn(TEST_ID);
-
- mMediaManager = new MediaManager(mContext, null) {};
- }
-
- @Test
- public void dispatchDeviceListAdded_registerCallback_shouldDispatchCallback() {
- mMediaManager.registerCallback(mCallback);
-
- mMediaManager.dispatchDeviceListAdded(Collections.emptyList());
-
- verify(mCallback).onDeviceListAdded(any());
- }
-
- @Test
- public void dispatchDeviceListRemoved_registerCallback_shouldDispatchCallback() {
- mMediaManager.registerCallback(mCallback);
-
- mMediaManager.dispatchDeviceListRemoved(Collections.emptyList());
-
- verify(mCallback).onDeviceListRemoved(Collections.emptyList());
- }
-
- @Test
- public void dispatchActiveDeviceChanged_registerCallback_shouldDispatchCallback() {
- mMediaManager.registerCallback(mCallback);
-
- mMediaManager.dispatchConnectedDeviceChanged(TEST_ID);
-
- verify(mCallback).onConnectedDeviceChanged(TEST_ID);
- }
-
- @Test
- public void dispatchOnRequestFailed_registerCallback_shouldDispatchCallback() {
- mMediaManager.registerCallback(mCallback);
-
- mMediaManager.dispatchOnRequestFailed(1);
-
- verify(mCallback).onRequestFailed(1);
- }
-
-}
diff --git a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
index 3043d54..8f8445d 100644
--- a/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
+++ b/packages/SettingsProvider/src/android/provider/settings/backup/GlobalSettings.java
@@ -115,6 +115,7 @@
Settings.Global.Wearable.SCREEN_UNLOCK_SOUND_ENABLED,
Settings.Global.Wearable.CHARGING_SOUNDS_ENABLED,
Settings.Global.Wearable.WRIST_DETECTION_AUTO_LOCKING_ENABLED,
+ Settings.Global.Wearable.AUTO_BEDTIME_MODE,
Settings.Global.FORCE_ENABLE_PSS_PROFILING,
Settings.Global.Wearable.ACCESSIBILITY_VIBRATION_WATCH_ENABLED,
Settings.Global.Wearable.ACCESSIBILITY_VIBRATION_WATCH_TYPE,
diff --git a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
index c0a0760..6def40b 100644
--- a/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
+++ b/packages/SettingsProvider/src/android/provider/settings/validators/GlobalSettingsValidators.java
@@ -452,6 +452,7 @@
VALIDATORS.put(Global.Wearable.WRIST_DETECTION_AUTO_LOCKING_ENABLED, BOOLEAN_VALIDATOR);
VALIDATORS.put(
Global.Wearable.CONSISTENT_NOTIFICATION_BLOCKING_ENABLED, ANY_INTEGER_VALIDATOR);
+ VALIDATORS.put(Global.Wearable.AUTO_BEDTIME_MODE, BOOLEAN_VALIDATOR);
VALIDATORS.put(Global.FORCE_ENABLE_PSS_PROFILING, BOOLEAN_VALIDATOR);
}
}
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
index 8dc7495..b124025 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/TextAnimator.kt
@@ -27,6 +27,7 @@
import android.text.Layout
import android.util.LruCache
import kotlin.math.roundToInt
+import android.util.Log
private const val DEFAULT_ANIMATION_DURATION: Long = 300
private const val TYPEFACE_CACHE_MAX_ENTRIES = 5
@@ -140,7 +141,6 @@
}
sealed class PositionedGlyph {
-
/** Mutable X coordinate of the glyph position relative from drawing offset. */
var x: Float = 0f
@@ -269,41 +269,53 @@
duration: Long = -1L,
interpolator: TimeInterpolator? = null,
delay: Long = 0,
- onAnimationEnd: Runnable? = null
+ onAnimationEnd: Runnable? = null,
+ ) = setTextStyleInternal(fvar, textSize, color, strokeWidth, animate, duration,
+ interpolator, delay, onAnimationEnd, updateLayoutOnFailure = true)
+
+ private fun setTextStyleInternal(
+ fvar: String?,
+ textSize: Float,
+ color: Int?,
+ strokeWidth: Float,
+ animate: Boolean,
+ duration: Long,
+ interpolator: TimeInterpolator?,
+ delay: Long,
+ onAnimationEnd: Runnable?,
+ updateLayoutOnFailure: Boolean,
) {
- if (animate) {
- animator.cancel()
- textInterpolator.rebase()
- }
+ try {
+ if (animate) {
+ animator.cancel()
+ textInterpolator.rebase()
+ }
- if (textSize >= 0) {
- textInterpolator.targetPaint.textSize = textSize
- }
+ if (textSize >= 0) {
+ textInterpolator.targetPaint.textSize = textSize
+ }
+ if (!fvar.isNullOrBlank()) {
+ textInterpolator.targetPaint.typeface = typefaceCache.getTypefaceForVariant(fvar)
+ }
+ if (color != null) {
+ textInterpolator.targetPaint.color = color
+ }
+ if (strokeWidth >= 0F) {
+ textInterpolator.targetPaint.strokeWidth = strokeWidth
+ }
+ textInterpolator.onTargetPaintModified()
- if (!fvar.isNullOrBlank()) {
- textInterpolator.targetPaint.typeface = typefaceCache.getTypefaceForVariant(fvar)
- }
-
- if (color != null) {
- textInterpolator.targetPaint.color = color
- }
- if (strokeWidth >= 0F) {
- textInterpolator.targetPaint.strokeWidth = strokeWidth
- }
- textInterpolator.onTargetPaintModified()
-
- if (animate) {
- animator.startDelay = delay
- animator.duration =
- if (duration == -1L) {
- DEFAULT_ANIMATION_DURATION
- } else {
- duration
- }
- interpolator?.let { animator.interpolator = it }
- if (onAnimationEnd != null) {
- val listener =
- object : AnimatorListenerAdapter() {
+ if (animate) {
+ animator.startDelay = delay
+ animator.duration =
+ if (duration == -1L) {
+ DEFAULT_ANIMATION_DURATION
+ } else {
+ duration
+ }
+ interpolator?.let { animator.interpolator = it }
+ if (onAnimationEnd != null) {
+ val listener = object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
onAnimationEnd.run()
animator.removeListener(this)
@@ -312,14 +324,25 @@
animator.removeListener(this)
}
}
- animator.addListener(listener)
+ animator.addListener(listener)
+ }
+ animator.start()
+ } else {
+ // No animation is requested, thus set base and target state to the same state.
+ textInterpolator.progress = 1f
+ textInterpolator.rebase()
+ invalidateCallback()
}
- animator.start()
- } else {
- // No animation is requested, thus set base and target state to the same state.
- textInterpolator.progress = 1f
- textInterpolator.rebase()
- invalidateCallback()
+ } catch (ex: IllegalArgumentException) {
+ if (updateLayoutOnFailure) {
+ Log.e(TAG, "setTextStyleInternal: Exception caught but retrying. This is usually" +
+ " due to the layout having changed unexpectedly without being notified.", ex)
+ updateLayout(textInterpolator.layout)
+ setTextStyleInternal(fvar, textSize, color, strokeWidth, animate, duration,
+ interpolator, delay, onAnimationEnd, updateLayoutOnFailure = false)
+ } else {
+ throw ex
+ }
}
}
@@ -355,15 +378,13 @@
interpolator: TimeInterpolator? = null,
delay: Long = 0,
onAnimationEnd: Runnable? = null
- ) {
- val fvar = fontVariationUtils.updateFontVariation(
- weight = weight,
- width = width,
- opticalSize = opticalSize,
- roundness = roundness,
- )
- setTextStyle(
- fvar = fvar,
+ ) = setTextStyleInternal(
+ fvar = fontVariationUtils.updateFontVariation(
+ weight = weight,
+ width = width,
+ opticalSize = opticalSize,
+ roundness = roundness,
+ ),
textSize = textSize,
color = color,
strokeWidth = strokeWidth,
@@ -372,6 +393,10 @@
interpolator = interpolator,
delay = delay,
onAnimationEnd = onAnimationEnd,
+ updateLayoutOnFailure = true,
)
+
+ companion object {
+ private val TAG = TextAnimator::class.simpleName!!
}
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
index 515c816..078da1c86 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalHub.kt
@@ -31,8 +31,8 @@
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -93,7 +93,6 @@
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.dimensionResource
-import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTagsAsResourceId
@@ -119,7 +118,6 @@
import com.android.systemui.communal.ui.compose.extensions.observeTapsWithoutConsuming
import com.android.systemui.communal.ui.viewmodel.BaseCommunalViewModel
import com.android.systemui.communal.ui.viewmodel.CommunalEditModeViewModel
-import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.widgets.WidgetConfigurator
import com.android.systemui.res.R
import kotlinx.coroutines.launch
@@ -199,37 +197,26 @@
}
},
) {
- Column(Modifier.align(Alignment.TopStart)) {
- CommunalHubLazyGrid(
- communalContent = communalContent,
- viewModel = viewModel,
- contentPadding = contentPadding,
- contentOffset = contentOffset,
- setGridCoordinates = { gridCoordinates = it },
- updateDragPositionForRemove = { offset ->
- isDraggingToRemove =
- isPointerWithinCoordinates(
- offset = gridCoordinates?.let { it.positionInWindow() + offset },
- containerToCheck = removeButtonCoordinates
- )
- isDraggingToRemove
- },
- onOpenWidgetPicker = onOpenWidgetPicker,
- gridState = gridState,
- contentListState = contentListState,
- selectedKey = selectedKey,
- widgetConfigurator = widgetConfigurator,
- )
- // TODO(b/326060686): Remove this once keyguard indication area can persist over hub
- if (viewModel is CommunalViewModel) {
- val isUnlocked by viewModel.deviceUnlocked.collectAsState(initial = false)
- Spacer(Modifier.height(24.dp))
- LockStateIcon(
- isUnlocked = isUnlocked,
- modifier = Modifier.align(Alignment.CenterHorizontally),
- )
- }
- }
+ CommunalHubLazyGrid(
+ communalContent = communalContent,
+ viewModel = viewModel,
+ contentPadding = contentPadding,
+ contentOffset = contentOffset,
+ setGridCoordinates = { gridCoordinates = it },
+ updateDragPositionForRemove = { offset ->
+ isDraggingToRemove =
+ isPointerWithinCoordinates(
+ offset = gridCoordinates?.let { it.positionInWindow() + offset },
+ containerToCheck = removeButtonCoordinates
+ )
+ isDraggingToRemove
+ },
+ onOpenWidgetPicker = onOpenWidgetPicker,
+ gridState = gridState,
+ contentListState = contentListState,
+ selectedKey = selectedKey,
+ widgetConfigurator = widgetConfigurator,
+ )
if (viewModel.isEditMode && onOpenWidgetPicker != null && onEditDone != null) {
Toolbar(
@@ -281,7 +268,7 @@
@OptIn(ExperimentalFoundationApi::class)
@Composable
-private fun ColumnScope.CommunalHubLazyGrid(
+private fun BoxScope.CommunalHubLazyGrid(
communalContent: List<CommunalContentModel>,
viewModel: BaseCommunalViewModel,
contentPadding: PaddingValues,
@@ -295,7 +282,7 @@
widgetConfigurator: WidgetConfigurator?,
) {
var gridModifier =
- Modifier.align(Alignment.Start).onGloballyPositioned { setGridCoordinates(it) }
+ Modifier.align(Alignment.TopStart).onGloballyPositioned { setGridCoordinates(it) }
var list = communalContent
var dragDropState: GridDragDropState? = null
if (viewModel.isEditMode && viewModel is CommunalEditModeViewModel) {
@@ -377,26 +364,6 @@
}
}
-@Composable
-private fun LockStateIcon(
- isUnlocked: Boolean,
- modifier: Modifier = Modifier,
-) {
- val colors = LocalAndroidColorScheme.current
- val resource =
- if (isUnlocked) {
- R.drawable.ic_unlocked
- } else {
- R.drawable.ic_lock
- }
- Icon(
- painter = painterResource(id = resource),
- contentDescription = null,
- tint = colors.onPrimaryContainer,
- modifier = modifier.size(52.dp)
- )
-}
-
/**
* Toolbar that contains action buttons to
* 1) open the widget picker
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
index 8f802b8..563aad1 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/view/viewmodel/CommunalViewModelTest.kt
@@ -39,7 +39,6 @@
import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.ui.viewmodel.CommunalViewModel.Companion.POPUP_AUTO_HIDE_TIMEOUT_MS
import com.android.systemui.coroutines.collectLastValue
-import com.android.systemui.deviceentry.domain.interactor.deviceEntryInteractor
import com.android.systemui.flags.Flags.COMMUNAL_SERVICE_ENABLED
import com.android.systemui.flags.fakeFeatureFlagsClassic
import com.android.systemui.keyguard.data.repository.FakeKeyguardRepository
@@ -114,7 +113,6 @@
kosmos.communalInteractor,
kosmos.communalTutorialInteractor,
kosmos.shadeInteractor,
- kosmos.deviceEntryInteractor,
mediaHost,
logcatLogBuffer("CommunalViewModelTest"),
)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileDataInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileDataInteractorTest.kt
new file mode 100644
index 0000000..c80eb13
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileDataInteractorTest.kt
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.doman.interactor
+
+import android.os.UserHandle
+import android.platform.test.annotations.EnabledOnRavenwood
+import android.testing.LeakCheck
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.qs.tiles.base.interactor.DataUpdateTrigger
+import com.android.systemui.qs.tiles.impl.battery.domain.interactor.BatterySaverTileDataInteractor
+import com.android.systemui.utils.leaks.FakeBatteryController
+import com.google.common.truth.Truth
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.toCollection
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@OptIn(ExperimentalCoroutinesApi::class)
+@SmallTest
+@EnabledOnRavenwood
+@RunWith(AndroidJUnit4::class)
+class BatterySaverTileDataInteractorTest : SysuiTestCase() {
+ private val kosmos = Kosmos()
+ private val testScope = kosmos.testScope
+ private val batteryController = FakeBatteryController(LeakCheck())
+ private val testUser = UserHandle.of(1)
+ private val underTest =
+ BatterySaverTileDataInteractor(testScope.testScheduler, batteryController)
+
+ @Test
+ fun availability_isTrue() =
+ testScope.runTest {
+ val availability = underTest.availability(testUser).toCollection(mutableListOf())
+
+ Truth.assertThat(availability).hasSize(1)
+ Truth.assertThat(availability.last()).isTrue()
+ }
+
+ @Test
+ fun tileData_matchesBatteryControllerPowerSaving() =
+ testScope.runTest {
+ val data by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ runCurrent()
+ Truth.assertThat(data!!.isPowerSaving).isFalse()
+
+ batteryController.setPowerSaveMode(true)
+ runCurrent()
+ Truth.assertThat(data!!.isPowerSaving).isTrue()
+
+ batteryController.setPowerSaveMode(false)
+ runCurrent()
+ Truth.assertThat(data!!.isPowerSaving).isFalse()
+ }
+
+ @Test
+ fun tileData_matchesBatteryControllerIsPluggedIn() =
+ testScope.runTest {
+ val data by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ runCurrent()
+ Truth.assertThat(data!!.isPluggedIn).isFalse()
+
+ batteryController.isPluggedIn = true
+ runCurrent()
+ Truth.assertThat(data!!.isPluggedIn).isTrue()
+
+ batteryController.isPluggedIn = false
+ runCurrent()
+ Truth.assertThat(data!!.isPluggedIn).isFalse()
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileUserActionInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileUserActionInteractorTest.kt
new file mode 100644
index 0000000..62c51e6
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/doman/interactor/BatterySaverTileUserActionInteractorTest.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.doman.interactor
+
+import android.platform.test.annotations.EnabledOnRavenwood
+import android.provider.Settings
+import android.testing.LeakCheck
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.qs.tiles.base.actions.FakeQSTileIntentUserInputHandler
+import com.android.systemui.qs.tiles.base.actions.QSTileIntentUserInputHandlerSubject
+import com.android.systemui.qs.tiles.base.interactor.QSTileInputTestKtx
+import com.android.systemui.qs.tiles.impl.battery.domain.interactor.BatterySaverTileUserActionInteractor
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.utils.leaks.FakeBatteryController
+import com.google.common.truth.Truth
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@EnabledOnRavenwood
+@RunWith(AndroidJUnit4::class)
+class BatterySaverTileUserActionInteractorTest : SysuiTestCase() {
+ private val inputHandler = FakeQSTileIntentUserInputHandler()
+ private val controller = FakeBatteryController(LeakCheck())
+ private val underTest = BatterySaverTileUserActionInteractor(inputHandler, controller)
+
+ @Test
+ fun handleClickWhenNotPluggedIn_flipsPowerSaverMode() = runTest {
+ val originalPowerSaveMode = controller.isPowerSave
+ controller.isPluggedIn = false
+
+ underTest.handleInput(
+ QSTileInputTestKtx.click(BatterySaverTileModel.Standard(false, originalPowerSaveMode))
+ )
+
+ Truth.assertThat(controller.isPowerSave).isNotEqualTo(originalPowerSaveMode)
+ }
+
+ @Test
+ fun handleClickWhenPluggedIn_doesNotTurnOnPowerSaverMode() = runTest {
+ controller.setPowerSaveMode(false)
+ val originalPowerSaveMode = controller.isPowerSave
+ controller.isPluggedIn = true
+
+ underTest.handleInput(
+ QSTileInputTestKtx.click(
+ BatterySaverTileModel.Standard(controller.isPluggedIn, originalPowerSaveMode)
+ )
+ )
+
+ Truth.assertThat(controller.isPowerSave).isEqualTo(originalPowerSaveMode)
+ }
+
+ @Test
+ fun handleLongClick() = runTest {
+ underTest.handleInput(
+ QSTileInputTestKtx.longClick(BatterySaverTileModel.Standard(false, false))
+ )
+
+ QSTileIntentUserInputHandlerSubject.assertThat(inputHandler).handledOneIntentInput {
+ Truth.assertThat(it.intent.action).isEqualTo(Settings.ACTION_BATTERY_SAVER_SETTINGS)
+ }
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapperTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapperTest.kt
new file mode 100644
index 0000000..6e9db2c
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapperTest.kt
@@ -0,0 +1,270 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.ui
+
+import android.graphics.drawable.TestStubDrawable
+import android.widget.Switch
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.qs.tiles.impl.battery.qsBatterySaverTileConfig
+import com.android.systemui.qs.tiles.impl.custom.QSTileStateSubject
+import com.android.systemui.qs.tiles.viewmodel.QSTileState
+import com.android.systemui.res.R
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class BatterySaverTileMapperTest : SysuiTestCase() {
+ private val kosmos = Kosmos()
+ private val batterySaverTileConfig = kosmos.qsBatterySaverTileConfig
+ private lateinit var mapper: BatterySaverTileMapper
+
+ @Before
+ fun setup() {
+ mapper =
+ BatterySaverTileMapper(
+ context.orCreateTestableResources
+ .apply {
+ addOverride(R.drawable.qs_battery_saver_icon_off, TestStubDrawable())
+ addOverride(R.drawable.qs_battery_saver_icon_on, TestStubDrawable())
+ }
+ .resources,
+ context.theme,
+ )
+ }
+
+ @Test
+ fun map_standard_notPluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Standard(false, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.INACTIVE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_standard_notPluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Standard(false, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.ACTIVE,
+ "",
+ R.drawable.qs_battery_saver_icon_on,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_standard_pluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Standard(true, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_on,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_standard_pluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Standard(true, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverDisabledNotPluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(false, false, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.INACTIVE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverDisabledNotPluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(false, true, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.ACTIVE,
+ context.getString(R.string.standard_battery_saver_text),
+ R.drawable.qs_battery_saver_icon_on,
+ context.getString(R.string.standard_battery_saver_text),
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverDisabledPluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(true, true, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_on,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverDisabledPluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(true, false, false)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverEnabledNotPluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(false, false, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.INACTIVE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverEnabledNotPluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(false, true, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.ACTIVE,
+ context.getString(R.string.extreme_battery_saver_text),
+ R.drawable.qs_battery_saver_icon_on,
+ context.getString(R.string.extreme_battery_saver_text),
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverEnabledPluggedInPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(true, true, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_on,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun map_extremeSaverEnabledPluggedInNotPowerSaving() {
+ val inputModel = BatterySaverTileModel.Extreme(true, false, true)
+
+ val outputState = mapper.map(batterySaverTileConfig, inputModel)
+
+ val expectedState =
+ createBatterySaverTileState(
+ QSTileState.ActivationState.UNAVAILABLE,
+ "",
+ R.drawable.qs_battery_saver_icon_off,
+ null,
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ private fun createBatterySaverTileState(
+ activationState: QSTileState.ActivationState,
+ secondaryLabel: String,
+ iconRes: Int,
+ stateDescription: CharSequence?,
+ ): QSTileState {
+ val label = context.getString(R.string.battery_detail_switch_title)
+ return QSTileState(
+ { Icon.Loaded(context.getDrawable(iconRes)!!, null) },
+ label,
+ activationState,
+ secondaryLabel,
+ if (activationState == QSTileState.ActivationState.UNAVAILABLE)
+ setOf(QSTileState.UserAction.LONG_CLICK)
+ else setOf(QSTileState.UserAction.CLICK, QSTileState.UserAction.LONG_CLICK),
+ label,
+ stateDescription,
+ QSTileState.SideViewIcon.None,
+ QSTileState.EnabledState.ENABLED,
+ Switch::class.qualifiedName
+ )
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapperTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapperTest.kt
new file mode 100644
index 0000000..39755bf
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapperTest.kt
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain
+
+import android.graphics.drawable.TestStubDrawable
+import android.widget.Switch
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.common.shared.model.ContentDescription
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.common.shared.model.Text
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.qs.tiles.impl.custom.QSTileStateSubject
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.qs.tiles.impl.internet.qsInternetTileConfig
+import com.android.systemui.qs.tiles.viewmodel.QSTileState
+import com.android.systemui.res.R
+import com.android.systemui.statusbar.connectivity.WifiIcons.WIFI_FULL_ICONS
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class InternetTileMapperTest : SysuiTestCase() {
+ private val kosmos = Kosmos()
+ private val internetTileConfig = kosmos.qsInternetTileConfig
+ private val mapper by lazy {
+ InternetTileMapper(
+ context.orCreateTestableResources
+ .apply {
+ addOverride(R.drawable.ic_qs_no_internet_unavailable, TestStubDrawable())
+ addOverride(wifiRes, TestStubDrawable())
+ }
+ .resources,
+ context.theme,
+ context
+ )
+ }
+
+ @Test
+ fun withActiveModel_mappedStateMatchesDataModel() {
+ val inputModel =
+ InternetTileModel.Active(
+ secondaryLabel = Text.Resource(R.string.quick_settings_networks_available),
+ iconId = wifiRes,
+ stateDescription = null,
+ contentDescription =
+ ContentDescription.Resource(R.string.quick_settings_internet_label),
+ )
+
+ val outputState = mapper.map(internetTileConfig, inputModel)
+
+ val expectedState =
+ createInternetTileState(
+ QSTileState.ActivationState.ACTIVE,
+ context.getString(R.string.quick_settings_networks_available),
+ Icon.Loaded(context.getDrawable(wifiRes)!!, contentDescription = null),
+ context.getString(R.string.quick_settings_internet_label)
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ @Test
+ fun withInactiveModel_mappedStateMatchesDataModel() {
+ val inputModel =
+ InternetTileModel.Inactive(
+ secondaryLabel = Text.Resource(R.string.quick_settings_networks_unavailable),
+ iconId = R.drawable.ic_qs_no_internet_unavailable,
+ stateDescription = null,
+ contentDescription =
+ ContentDescription.Resource(R.string.quick_settings_networks_unavailable),
+ )
+
+ val outputState = mapper.map(internetTileConfig, inputModel)
+
+ val expectedState =
+ createInternetTileState(
+ QSTileState.ActivationState.INACTIVE,
+ context.getString(R.string.quick_settings_networks_unavailable),
+ Icon.Loaded(
+ context.getDrawable(R.drawable.ic_qs_no_internet_unavailable)!!,
+ contentDescription = null
+ ),
+ context.getString(R.string.quick_settings_networks_unavailable)
+ )
+ QSTileStateSubject.assertThat(outputState).isEqualTo(expectedState)
+ }
+
+ private fun createInternetTileState(
+ activationState: QSTileState.ActivationState,
+ secondaryLabel: String,
+ icon: Icon,
+ contentDescription: String,
+ ): QSTileState {
+ val label = context.getString(R.string.quick_settings_internet_label)
+ return QSTileState(
+ { icon },
+ label,
+ activationState,
+ secondaryLabel,
+ setOf(QSTileState.UserAction.CLICK, QSTileState.UserAction.LONG_CLICK),
+ contentDescription,
+ null,
+ QSTileState.SideViewIcon.Chevron,
+ QSTileState.EnabledState.ENABLED,
+ Switch::class.qualifiedName
+ )
+ }
+
+ private companion object {
+ val wifiRes = WIFI_FULL_ICONS[4]
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractorTest.kt
new file mode 100644
index 0000000..37ef6ad
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractorTest.kt
@@ -0,0 +1,548 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain.interactor
+
+import android.graphics.drawable.TestStubDrawable
+import android.os.UserHandle
+import android.testing.TestableLooper
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.settingslib.AccessibilityContentDescriptions
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.common.shared.model.ContentDescription
+import com.android.systemui.common.shared.model.ContentDescription.Companion.loadContentDescription
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.common.shared.model.Text
+import com.android.systemui.common.shared.model.Text.Companion.loadText
+import com.android.systemui.coroutines.collectLastValue
+import com.android.systemui.flags.FakeFeatureFlagsClassic
+import com.android.systemui.flags.Flags
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.log.table.TableLogBuffer
+import com.android.systemui.qs.tiles.base.interactor.DataUpdateTrigger
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.res.R
+import com.android.systemui.statusbar.connectivity.WifiIcons
+import com.android.systemui.statusbar.pipeline.airplane.data.repository.FakeAirplaneModeRepository
+import com.android.systemui.statusbar.pipeline.ethernet.domain.EthernetInteractor
+import com.android.systemui.statusbar.pipeline.mobile.data.model.DataConnectionState
+import com.android.systemui.statusbar.pipeline.mobile.data.model.NetworkNameModel
+import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionRepository
+import com.android.systemui.statusbar.pipeline.mobile.data.repository.FakeMobileConnectionsRepository
+import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconsInteractor
+import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconsInteractorImpl
+import com.android.systemui.statusbar.pipeline.mobile.util.FakeMobileMappingsProxy
+import com.android.systemui.statusbar.pipeline.shared.data.model.DefaultConnectionModel
+import com.android.systemui.statusbar.pipeline.shared.data.repository.FakeConnectivityRepository
+import com.android.systemui.statusbar.pipeline.wifi.data.repository.FakeWifiRepository
+import com.android.systemui.statusbar.pipeline.wifi.domain.interactor.WifiInteractorImpl
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiScanEntry
+import com.android.systemui.statusbar.pipeline.wifi.ui.model.WifiIcon
+import com.android.systemui.statusbar.policy.data.repository.FakeUserSetupRepository
+import com.android.systemui.util.CarrierConfigTracker
+import com.android.systemui.util.mockito.mock
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@TestableLooper.RunWithLooper
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class InternetTileDataInteractorTest : SysuiTestCase() {
+ private val testUser = UserHandle.of(1)
+ private val kosmos = Kosmos()
+ private val testScope = kosmos.testScope
+
+ private lateinit var underTest: InternetTileDataInteractor
+ private lateinit var mobileIconsInteractor: MobileIconsInteractor
+
+ private val airplaneModeRepository = FakeAirplaneModeRepository()
+ private val connectivityRepository = FakeConnectivityRepository()
+ private val ethernetInteractor = EthernetInteractor(connectivityRepository)
+ private val wifiRepository = FakeWifiRepository()
+ private val userSetupRepo = FakeUserSetupRepository()
+ private val wifiInteractor =
+ WifiInteractorImpl(connectivityRepository, wifiRepository, testScope.backgroundScope)
+
+ private val tableLogBuffer: TableLogBuffer = mock()
+ private val carrierConfigTracker: CarrierConfigTracker = mock()
+
+ private val mobileConnectionsRepository =
+ FakeMobileConnectionsRepository(FakeMobileMappingsProxy(), tableLogBuffer)
+ private val mobileConnectionRepository =
+ FakeMobileConnectionRepository(SUB_1_ID, tableLogBuffer)
+
+ private val flags =
+ FakeFeatureFlagsClassic().also {
+ it.set(Flags.FILTER_PROVISIONING_NETWORK_SUBSCRIPTIONS, true)
+ }
+
+ private val internet = context.getString(R.string.quick_settings_internet_label)
+
+ @Before
+ fun setUp() {
+ mobileConnectionRepository.apply {
+ setNetworkTypeKey(mobileConnectionsRepository.GSM_KEY)
+ isInService.value = true
+ dataConnectionState.value = DataConnectionState.Connected
+ dataEnabled.value = true
+ }
+
+ mobileConnectionsRepository.apply {
+ activeMobileDataRepository.value = mobileConnectionRepository
+ activeMobileDataSubscriptionId.value = SUB_1_ID
+ setMobileConnectionRepositoryMap(mapOf(SUB_1_ID to mobileConnectionRepository))
+ }
+
+ mobileIconsInteractor =
+ MobileIconsInteractorImpl(
+ mobileConnectionsRepository,
+ carrierConfigTracker,
+ tableLogBuffer,
+ connectivityRepository,
+ userSetupRepo,
+ testScope.backgroundScope,
+ context,
+ flags,
+ )
+
+ context.orCreateTestableResources.apply {
+ addOverride(com.android.internal.R.drawable.ic_signal_cellular, TestStubDrawable())
+ addOverride(
+ com.android.settingslib.R.drawable.ic_no_internet_wifi_signal_0,
+ TestStubDrawable()
+ )
+ addOverride(
+ com.android.settingslib.R.drawable.ic_no_internet_wifi_signal_1,
+ TestStubDrawable()
+ )
+ addOverride(
+ com.android.settingslib.R.drawable.ic_no_internet_wifi_signal_2,
+ TestStubDrawable()
+ )
+ addOverride(
+ com.android.settingslib.R.drawable.ic_no_internet_wifi_signal_3,
+ TestStubDrawable()
+ )
+ addOverride(
+ com.android.settingslib.R.drawable.ic_no_internet_wifi_signal_4,
+ TestStubDrawable()
+ )
+ addOverride(com.android.settingslib.R.drawable.ic_hotspot_phone, TestStubDrawable())
+ addOverride(com.android.settingslib.R.drawable.ic_hotspot_laptop, TestStubDrawable())
+ addOverride(com.android.settingslib.R.drawable.ic_hotspot_tablet, TestStubDrawable())
+ addOverride(com.android.settingslib.R.drawable.ic_hotspot_watch, TestStubDrawable())
+ addOverride(com.android.settingslib.R.drawable.ic_hotspot_auto, TestStubDrawable())
+ }
+
+ underTest =
+ InternetTileDataInteractor(
+ context,
+ testScope.backgroundScope,
+ airplaneModeRepository,
+ connectivityRepository,
+ ethernetInteractor,
+ mobileIconsInteractor,
+ wifiInteractor,
+ )
+ }
+
+ @Test
+ fun noDefault_noNetworksAvailable() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ connectivityRepository.defaultConnections.value = DefaultConnectionModel()
+
+ assertThat(latest?.secondaryLabel)
+ .isEqualTo(Text.Resource(R.string.quick_settings_networks_unavailable))
+ assertThat(latest?.iconId).isEqualTo(R.drawable.ic_qs_no_internet_unavailable)
+ }
+
+ @Test
+ fun noDefault_networksAvailable() =
+ testScope.runTest {
+ // TODO(b/328419203): support [WifiInteractor.areNetworksAvailable]
+ }
+
+ @Test
+ fun wifiDefaultAndActive() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ val networkModel =
+ WifiNetworkModel.Active(
+ networkId = 1,
+ level = 4,
+ ssid = "test ssid",
+ )
+ val wifiIcon =
+ WifiIcon.fromModel(model = networkModel, context = context, showHotspotInfo = true)
+ as WifiIcon.Visible
+
+ connectivityRepository.setWifiConnected()
+ wifiRepository.setIsWifiDefault(true)
+ wifiRepository.setWifiNetwork(networkModel)
+
+ assertThat(latest?.secondaryTitle).isEqualTo("test ssid")
+ assertThat(latest?.secondaryLabel).isNull()
+ val expectedIcon =
+ Icon.Loaded(context.getDrawable(WifiIcons.WIFI_NO_INTERNET_ICONS[4])!!, null)
+
+ val actualIcon = latest?.icon
+ assertThat(actualIcon).isEqualTo(expectedIcon)
+ assertThat(latest?.iconId).isNull()
+ assertThat(latest?.contentDescription.loadContentDescription(context))
+ .isEqualTo("$internet,test ssid")
+ val expectedSd = wifiIcon.contentDescription
+ assertThat(latest?.stateDescription).isEqualTo(expectedSd)
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotNone() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ val networkModel =
+ WifiNetworkModel.Active(
+ networkId = 1,
+ level = 4,
+ ssid = "test ssid",
+ hotspotDeviceType = WifiNetworkModel.HotspotDeviceType.NONE,
+ )
+
+ connectivityRepository.setWifiConnected()
+ wifiRepository.setIsWifiDefault(true)
+ wifiRepository.setWifiNetwork(networkModel)
+
+ val expectedIcon =
+ Icon.Loaded(context.getDrawable(WifiIcons.WIFI_NO_INTERNET_ICONS[4])!!, null)
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .doesNotContain(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotTablet() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.TABLET)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_tablet)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotLaptop() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.LAPTOP)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_laptop)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotWatch() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.WATCH)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_watch)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotAuto() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.AUTO)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_auto)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotPhone() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.PHONE)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_phone)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotUnknown() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.UNKNOWN)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_phone)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndActive_hotspotInvalid() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ setWifiNetworkWithHotspot(WifiNetworkModel.HotspotDeviceType.INVALID)
+
+ val expectedIcon =
+ Icon.Loaded(
+ context.getDrawable(com.android.settingslib.R.drawable.ic_hotspot_phone)!!,
+ null
+ )
+ assertThat(latest?.icon).isEqualTo(expectedIcon)
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(
+ context.getString(AccessibilityContentDescriptions.WIFI_OTHER_DEVICE_CONNECTION)
+ )
+ }
+
+ @Test
+ fun wifiDefaultAndNotActive_noNetworksAvailable() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+ val networkModel = WifiNetworkModel.Inactive
+
+ connectivityRepository.setWifiConnected(validated = false)
+ wifiRepository.setIsWifiDefault(true)
+ wifiRepository.setWifiNetwork(networkModel)
+ wifiRepository.wifiScanResults.value = emptyList()
+
+ assertThat(latest).isEqualTo(NOT_CONNECTED_NETWORKS_UNAVAILABLE)
+ }
+
+ @Test
+ fun wifiDefaultAndNotActive_networksAvailable() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ val networkModel = WifiNetworkModel.Inactive
+
+ connectivityRepository.setWifiConnected(validated = false)
+ wifiRepository.setIsWifiDefault(true)
+ wifiRepository.setWifiNetwork(networkModel)
+ wifiRepository.wifiScanResults.value = listOf(WifiScanEntry("test 1"))
+
+ assertThat(latest?.secondaryLabel).isNull()
+ assertThat(latest?.secondaryTitle)
+ .isEqualTo(context.getString(R.string.quick_settings_networks_available))
+ assertThat(latest?.icon).isNull()
+ assertThat(latest?.iconId).isEqualTo(R.drawable.ic_qs_no_internet_available)
+ assertThat(latest?.stateDescription).isNull()
+ val expectedCd =
+ "$internet,${context.getString(R.string.quick_settings_networks_available)}"
+ assertThat(latest?.contentDescription.loadContentDescription(context))
+ .isEqualTo(expectedCd)
+ }
+
+ @Test
+ fun mobileDefault_usesNetworkNameAndIcon() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+
+ connectivityRepository.setMobileConnected()
+ mobileConnectionsRepository.mobileIsDefault.value = true
+ mobileConnectionRepository.apply {
+ setAllLevels(3)
+ setAllRoaming(false)
+ networkName.value = NetworkNameModel.Default("test network")
+ }
+
+ assertThat(latest).isNotNull()
+ assertThat(latest?.secondaryTitle).isNotNull()
+ assertThat(latest?.secondaryTitle.toString()).contains("test network")
+ assertThat(latest?.secondaryLabel).isNull()
+ assertThat(latest?.icon).isInstanceOf(Icon.Loaded::class.java)
+ assertThat(latest?.iconId).isNull()
+ assertThat(latest?.stateDescription.loadContentDescription(context))
+ .isEqualTo(latest?.secondaryTitle.toString())
+ assertThat(latest?.contentDescription.loadContentDescription(context))
+ .isEqualTo(internet)
+ }
+
+ @Test
+ fun ethernetDefault_validated_matchesInteractor() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+ val ethernetIcon by collectLastValue(ethernetInteractor.icon)
+
+ connectivityRepository.setEthernetConnected(default = true, validated = true)
+
+ assertThat(latest?.secondaryLabel.loadText(context))
+ .isEqualTo(ethernetIcon!!.contentDescription.loadContentDescription(context))
+ assertThat(latest?.secondaryTitle).isNull()
+ assertThat(latest?.iconId).isEqualTo(R.drawable.stat_sys_ethernet_fully)
+ assertThat(latest?.icon).isNull()
+ assertThat(latest?.stateDescription).isNull()
+ assertThat(latest?.contentDescription.loadContentDescription(context))
+ .isEqualTo(latest?.secondaryLabel.loadText(context))
+ }
+
+ @Test
+ fun ethernetDefault_notValidated_matchesInteractor() =
+ testScope.runTest {
+ val latest by
+ collectLastValue(
+ underTest.tileData(testUser, flowOf(DataUpdateTrigger.InitialRequest))
+ )
+ val ethernetIcon by collectLastValue(ethernetInteractor.icon)
+
+ connectivityRepository.setEthernetConnected(default = true, validated = false)
+
+ assertThat(latest?.secondaryLabel.loadText(context))
+ .isEqualTo(ethernetIcon!!.contentDescription.loadContentDescription(context))
+ assertThat(latest?.secondaryTitle).isNull()
+ assertThat(latest?.iconId).isEqualTo(R.drawable.stat_sys_ethernet)
+ assertThat(latest?.icon).isNull()
+ assertThat(latest?.stateDescription).isNull()
+ assertThat(latest?.contentDescription.loadContentDescription(context))
+ .isEqualTo(latest?.secondaryLabel.loadText(context))
+ }
+
+ private fun setWifiNetworkWithHotspot(hotspot: WifiNetworkModel.HotspotDeviceType) {
+ val networkModel =
+ WifiNetworkModel.Active(
+ networkId = 1,
+ level = 4,
+ ssid = "test ssid",
+ hotspotDeviceType = hotspot,
+ )
+
+ connectivityRepository.setWifiConnected()
+ wifiRepository.setIsWifiDefault(true)
+ wifiRepository.setWifiNetwork(networkModel)
+ }
+
+ private companion object {
+ const val SUB_1_ID = 1
+
+ val NOT_CONNECTED_NETWORKS_UNAVAILABLE =
+ InternetTileModel.Inactive(
+ secondaryLabel = Text.Resource(R.string.quick_settings_networks_unavailable),
+ iconId = R.drawable.ic_qs_no_internet_unavailable,
+ stateDescription = null,
+ contentDescription =
+ ContentDescription.Resource(R.string.quick_settings_networks_unavailable),
+ )
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractorTest.kt
new file mode 100644
index 0000000..e1f3d97
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractorTest.kt
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain.interactor
+
+import android.platform.test.annotations.EnabledOnRavenwood
+import android.provider.Settings
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.qs.tiles.base.actions.FakeQSTileIntentUserInputHandler
+import com.android.systemui.qs.tiles.base.actions.QSTileIntentUserInputHandlerSubject
+import com.android.systemui.qs.tiles.base.interactor.QSTileInputTestKtx
+import com.android.systemui.qs.tiles.dialog.InternetDialogManager
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.statusbar.connectivity.AccessPointController
+import com.android.systemui.util.mockito.mock
+import com.android.systemui.util.mockito.nullable
+import com.google.common.truth.Truth
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.Mock
+import org.mockito.Mockito.verify
+
+@SmallTest
+@EnabledOnRavenwood
+@RunWith(AndroidJUnit4::class)
+class InternetTileUserActionInteractorTest : SysuiTestCase() {
+ private val kosmos = Kosmos()
+ private val inputHandler = FakeQSTileIntentUserInputHandler()
+
+ private lateinit var underTest: InternetTileUserActionInteractor
+
+ @Mock private lateinit var internetDialogManager: InternetDialogManager
+ @Mock private lateinit var controller: AccessPointController
+
+ @Before
+ fun setup() {
+ internetDialogManager = mock<InternetDialogManager>()
+ controller = mock<AccessPointController>()
+
+ underTest =
+ InternetTileUserActionInteractor(
+ kosmos.testScope.coroutineContext,
+ internetDialogManager,
+ controller,
+ inputHandler,
+ )
+ }
+
+ @Test
+ fun handleClickWhenActive() =
+ kosmos.testScope.runTest {
+ val input = InternetTileModel.Active()
+
+ underTest.handleInput(QSTileInputTestKtx.click(input))
+
+ verify(internetDialogManager).create(eq(true), anyBoolean(), anyBoolean(), nullable())
+ }
+
+ @Test
+ fun handleClickWhenInactive() =
+ kosmos.testScope.runTest {
+ val input = InternetTileModel.Inactive()
+
+ underTest.handleInput(QSTileInputTestKtx.click(input))
+
+ verify(internetDialogManager).create(eq(true), anyBoolean(), anyBoolean(), nullable())
+ }
+
+ @Test
+ fun handleLongClickWhenActive() =
+ kosmos.testScope.runTest {
+ val input = InternetTileModel.Active()
+
+ underTest.handleInput(QSTileInputTestKtx.longClick(input))
+
+ QSTileIntentUserInputHandlerSubject.assertThat(inputHandler).handledOneIntentInput {
+ Truth.assertThat(it.intent.action).isEqualTo(Settings.ACTION_WIFI_SETTINGS)
+ }
+ }
+
+ @Test
+ fun handleLongClickWhenInactive() =
+ kosmos.testScope.runTest {
+ val input = InternetTileModel.Inactive()
+
+ underTest.handleInput(QSTileInputTestKtx.longClick(input))
+
+ QSTileIntentUserInputHandlerSubject.assertThat(inputHandler).handledOneIntentInput {
+ Truth.assertThat(it.intent.action).isEqualTo(Settings.ACTION_WIFI_SETTINGS)
+ }
+ }
+}
diff --git a/packages/SystemUI/res/layout/keyboard_shortcuts_search_view.xml b/packages/SystemUI/res/layout/keyboard_shortcuts_search_view.xml
index 61f69c0..f6042e4 100644
--- a/packages/SystemUI/res/layout/keyboard_shortcuts_search_view.xml
+++ b/packages/SystemUI/res/layout/keyboard_shortcuts_search_view.xml
@@ -128,7 +128,8 @@
android:layout_marginStart="49dp"
android:layout_marginEnd="49dp"
android:overScrollMode="never"
- android:layout_marginBottom="16dp">
+ android:layout_marginBottom="16dp"
+ android:scrollbars="none">
<LinearLayout
android:id="@+id/keyboard_shortcuts_container"
android:layout_width="match_parent"
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index e181d07..35f6a08 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -345,9 +345,6 @@
the notification is not swiped enough to dismiss it. -->
<bool name="config_showNotificationGear">true</bool>
- <!-- Whether or not a background should be drawn behind a notification. -->
- <bool name="config_drawNotificationBackground">false</bool>
-
<!-- Whether or the notifications can be shown and dismissed with a drag. -->
<bool name="config_enableNotificationShadeDrag">true</bool>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index b713417..5dbdd18 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -75,6 +75,11 @@
<!-- Battery saver notification dismiss action: Do not turn on battery saver. [CHAR LIMIT=NONE]-->
<string name="battery_saver_dismiss_action">No thanks</string>
+ <!-- Secondary label for Battery Saver tile when Battery Saver is enabled. [CHAR LIMIT=20] -->
+ <string name="standard_battery_saver_text">Standard</string>
+ <!-- Secondary label for Battery Saver tile when Extreme Battery Saver is enabled. [CHAR LIMIT=20] -->
+ <string name="extreme_battery_saver_text">Extreme</string>
+
<!-- Name of the button that links to the Settings app. [CHAR LIMIT=NONE] -->
<!-- Name of the button that links to the Wifi settings screen. [CHAR LIMIT=NONE] -->
diff --git a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
index f28d405..8a2245d 100644
--- a/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
+++ b/packages/SystemUI/src/com/android/keyguard/ClockEventController.kt
@@ -404,7 +404,9 @@
if (nextAlarmMillis > 0) nextAlarmMillis else null,
SysuiR.string::status_bar_alarm.name
)
- .also { data -> clock?.run { events.onAlarmDataChanged(data) } }
+ .also { data ->
+ mainExecutor.execute { clock?.run { events.onAlarmDataChanged(data) } }
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
index 31698a3..01c2cc4 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatteryMeterView.java
@@ -345,11 +345,25 @@
}
}
- private TextView loadPercentView() {
+ private TextView inflatePercentView() {
return (TextView) LayoutInflater.from(getContext())
.inflate(R.layout.battery_percentage_view, null);
}
+ private void addPercentView(TextView inflatedPercentView) {
+ mBatteryPercentView = inflatedPercentView;
+
+ if (mPercentageStyleId != 0) { // Only set if specified as attribute
+ mBatteryPercentView.setTextAppearance(mPercentageStyleId);
+ }
+ float fontHeight = mBatteryPercentView.getPaint().getFontMetricsInt(null);
+ mBatteryPercentView.setLineHeight(TypedValue.COMPLEX_UNIT_PX, fontHeight);
+ if (mTextColor != 0) mBatteryPercentView.setTextColor(mTextColor);
+ addView(mBatteryPercentView, new LayoutParams(
+ LayoutParams.WRAP_CONTENT,
+ (int) Math.ceil(fontHeight)));
+ }
+
/**
* Updates percent view by removing old one and reinflating if necessary
*/
@@ -388,7 +402,9 @@
mBatteryEstimateFetcher.fetchBatteryTimeRemainingEstimate(
(String estimate) -> {
if (mBatteryPercentView == null) {
- mBatteryPercentView = loadPercentView();
+ // Similar to the legacy behavior, inflate and add the view. We will
+ // only use it for the estimate text
+ addPercentView(inflatePercentView());
}
if (estimate != null && mShowPercentMode == MODE_ESTIMATE) {
mEstimateText = estimate;
@@ -401,6 +417,10 @@
}
});
} else {
+ if (mBatteryPercentView != null) {
+ mEstimateText = null;
+ mBatteryPercentView.setText(null);
+ }
updateContentDescription();
}
}
@@ -485,22 +505,19 @@
return;
}
- if (mUnifiedBattery == null) {
- return;
+ if (!mShowPercentAvailable || mUnifiedBattery == null) return;
+
+ boolean shouldShow = mShowPercentMode == MODE_ON || mShowPercentMode == MODE_ESTIMATE;
+ if (!mBatteryStateUnknown && !shouldShow && (mShowPercentMode != MODE_OFF)) {
+ // Slow case: fall back to the system setting
+ // TODO(b/140051051)
+ shouldShow = 0 != whitelistIpcs(() -> Settings.System
+ .getIntForUser(getContext().getContentResolver(),
+ SHOW_BATTERY_PERCENT, getContext().getResources().getBoolean(
+ com.android.internal.R.bool.config_defaultBatteryPercentageSetting)
+ ? 1 : 0, UserHandle.USER_CURRENT));
}
- // TODO(b/140051051)
- final boolean systemSetting = 0 != whitelistIpcs(() -> Settings.System
- .getIntForUser(getContext().getContentResolver(),
- SHOW_BATTERY_PERCENT, getContext().getResources().getBoolean(
- com.android.internal.R.bool.config_defaultBatteryPercentageSetting)
- ? 1 : 0, UserHandle.USER_CURRENT));
-
- boolean shouldShow =
- (mShowPercentAvailable && systemSetting && mShowPercentMode != MODE_OFF)
- || mShowPercentMode == MODE_ON;
- shouldShow = shouldShow && !mBatteryStateUnknown;
-
setBatteryDrawableState(
new BatteryDrawableState(
mUnifiedBatteryState.getLevel(),
@@ -534,17 +551,8 @@
if (shouldShow) {
if (!showing) {
- mBatteryPercentView = loadPercentView();
- if (mPercentageStyleId != 0) { // Only set if specified as attribute
- mBatteryPercentView.setTextAppearance(mPercentageStyleId);
- }
- float fontHeight = mBatteryPercentView.getPaint().getFontMetricsInt(null);
- mBatteryPercentView.setLineHeight(TypedValue.COMPLEX_UNIT_PX, fontHeight);
- if (mTextColor != 0) mBatteryPercentView.setTextColor(mTextColor);
+ addPercentView(inflatePercentView());
updatePercentText();
- addView(mBatteryPercentView, new LayoutParams(
- LayoutParams.WRAP_CONTENT,
- (int) Math.ceil(fontHeight)));
}
} else {
if (showing) {
diff --git a/packages/SystemUI/src/com/android/systemui/battery/BatterySaverModule.kt b/packages/SystemUI/src/com/android/systemui/battery/BatterySaverModule.kt
index 8c9ae62..10a0d95 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/BatterySaverModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/BatterySaverModule.kt
@@ -1,9 +1,21 @@
package com.android.systemui.battery
+import com.android.systemui.qs.QsEventLogger
+import com.android.systemui.qs.pipeline.shared.TileSpec
import com.android.systemui.qs.tileimpl.QSTileImpl
import com.android.systemui.qs.tiles.BatterySaverTile
+import com.android.systemui.qs.tiles.base.viewmodel.QSTileViewModelFactory
+import com.android.systemui.qs.tiles.impl.battery.domain.interactor.BatterySaverTileDataInteractor
+import com.android.systemui.qs.tiles.impl.battery.domain.interactor.BatterySaverTileUserActionInteractor
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.qs.tiles.impl.battery.ui.BatterySaverTileMapper
+import com.android.systemui.qs.tiles.viewmodel.QSTileConfig
+import com.android.systemui.qs.tiles.viewmodel.QSTileUIConfig
+import com.android.systemui.qs.tiles.viewmodel.QSTileViewModel
+import com.android.systemui.res.R
import dagger.Binds
import dagger.Module
+import dagger.Provides
import dagger.multibindings.IntoMap
import dagger.multibindings.StringKey
@@ -15,4 +27,39 @@
@IntoMap
@StringKey(BatterySaverTile.TILE_SPEC)
fun bindBatterySaverTile(batterySaverTile: BatterySaverTile): QSTileImpl<*>
+
+ companion object {
+ private const val BATTERY_SAVER_TILE_SPEC = "battery"
+
+ @Provides
+ @IntoMap
+ @StringKey(BATTERY_SAVER_TILE_SPEC)
+ fun provideBatterySaverTileConfig(uiEventLogger: QsEventLogger): QSTileConfig =
+ QSTileConfig(
+ tileSpec = TileSpec.create(BATTERY_SAVER_TILE_SPEC),
+ uiConfig =
+ QSTileUIConfig.Resource(
+ iconRes = R.drawable.qs_battery_saver_icon_off,
+ labelRes = R.string.battery_detail_switch_title,
+ ),
+ instanceId = uiEventLogger.getNewInstanceId(),
+ )
+
+ /** Inject BatterySaverTile into tileViewModelMap in QSModule */
+ @Provides
+ @IntoMap
+ @StringKey(BATTERY_SAVER_TILE_SPEC)
+ fun provideBatterySaverTileViewModel(
+ factory: QSTileViewModelFactory.Static<BatterySaverTileModel>,
+ mapper: BatterySaverTileMapper,
+ stateInteractor: BatterySaverTileDataInteractor,
+ userActionInteractor: BatterySaverTileUserActionInteractor
+ ): QSTileViewModel =
+ factory.create(
+ TileSpec.create(BATTERY_SAVER_TILE_SPEC),
+ userActionInteractor,
+ stateInteractor,
+ mapper,
+ )
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt
index 1b8495a..f3652b8 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryAttributionDrawable.kt
@@ -23,6 +23,7 @@
import android.graphics.drawable.Drawable
import android.graphics.drawable.DrawableWrapper
import android.view.Gravity
+import kotlin.math.ceil
import kotlin.math.min
import kotlin.math.roundToInt
@@ -36,7 +37,7 @@
*/
@Suppress("RtlHardcoded")
class BatteryAttributionDrawable(dr: Drawable?) : DrawableWrapper(dr) {
- /** One of [CENTER, LEFT]. Note that RTL is handled in the parent */
+ /** One of [CENTER, LEFT]. Note that number text does not RTL. */
var gravity = Gravity.CENTER
set(value) {
field = value
@@ -67,8 +68,8 @@
dr.setBounds(
bounds.left,
bounds.top,
- (bounds.left + dw).roundToInt(),
- (bounds.top + dh).roundToInt()
+ ceil(bounds.left + dw).toInt(),
+ ceil(bounds.top + dh).toInt()
)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt
index 6d32067..5e34d29 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryFillDrawable.kt
@@ -26,6 +26,7 @@
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Drawable
+import android.view.View
import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
import kotlin.math.floor
import kotlin.math.roundToInt
@@ -103,6 +104,11 @@
// saveLayer is needed here so we don't clip the other layers of our drawable
canvas.saveLayer(null, null)
+ // Fill from the opposite direction in rtl mode
+ if (layoutDirection == View.LAYOUT_DIRECTION_RTL) {
+ canvas.scale(-1f, 1f, bounds.width() / 2f, bounds.height() / 2f)
+ }
+
// We need to use 3 draw commands:
// 1. Clip to the current level
// 2. Clip anything outside of the path
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt
index 199dd1f..706b9ec 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryLayersDrawable.kt
@@ -26,7 +26,10 @@
import android.graphics.drawable.LayerDrawable
import android.util.PathParser
import android.view.Gravity
+import android.view.View
import com.android.systemui.res.R
+import kotlin.math.ceil
+import kotlin.math.floor
import kotlin.math.roundToInt
/**
@@ -69,8 +72,11 @@
) : LayerDrawable(arrayOf(frameBg, frame, fill, textOnly, spaceSharingText, attribution)) {
private val scaleMatrix = Matrix().also { it.setScale(1f, 1f) }
- private val scaledAttrFullCanvas = RectF(Metrics.AttrFullCanvas)
- private val scaledAttrRightCanvas = RectF(Metrics.AttrRightCanvas)
+
+ private val attrFullCanvas = RectF()
+ private val attrRightCanvas = RectF()
+ private val scaledAttrFullCanvas = RectF()
+ private val scaledAttrRightCanvas = RectF()
var batteryState = batteryState
set(value) {
@@ -88,6 +94,12 @@
updateColors(batteryState.showErrorState, value)
}
+ init {
+ isAutoMirrored = true
+ // Initialize the canvas rects since they are not static
+ setAttrRects(layoutDirection == View.LAYOUT_DIRECTION_RTL)
+ }
+
private fun handleUpdateState(old: BatteryDrawableState, new: BatteryDrawableState) {
if (new.showErrorState != old.showErrorState) {
updateColors(new.showErrorState, colors)
@@ -144,9 +156,42 @@
bounds.height() / Metrics.ViewportHeight
)
- // Scale the attribution bounds
- scaleMatrix.mapRect(scaledAttrFullCanvas, Metrics.AttrFullCanvas)
- scaleMatrix.mapRect(scaledAttrRightCanvas, Metrics.AttrRightCanvas)
+ scaleAttributionBounds()
+ }
+
+ override fun onLayoutDirectionChanged(layoutDirection: Int): Boolean {
+ setAttrRects(layoutDirection == View.LAYOUT_DIRECTION_RTL)
+ scaleAttributionBounds()
+
+ return super.onLayoutDirectionChanged(layoutDirection)
+ }
+
+ private fun setAttrRects(rtl: Boolean) {
+ // Local refs make the math easier to parse
+ val full = Metrics.AttrFullCanvasInsets
+ val side = Metrics.AttrRightCanvasInsets
+ val sideRtl = Metrics.AttrRightCanvasInsetsRtl
+ val vh = Metrics.ViewportHeight
+ val vw = Metrics.ViewportWidth
+
+ attrFullCanvas.set(
+ if (rtl) full.right else full.left,
+ full.top,
+ vw - if (rtl) full.left else full.right,
+ vh - full.bottom,
+ )
+ attrRightCanvas.set(
+ if (rtl) sideRtl.left else side.left,
+ side.top,
+ vw - (if (rtl) sideRtl.right else side.right),
+ vh - side.bottom,
+ )
+ }
+
+ /** If bounds (i.e., scale), or RTL properties change, we have to recalculate the attr bounds */
+ private fun scaleAttributionBounds() {
+ scaleMatrix.mapRect(scaledAttrFullCanvas, attrFullCanvas)
+ scaleMatrix.mapRect(scaledAttrRightCanvas, attrRightCanvas)
}
override fun draw(canvas: Canvas) {
@@ -163,13 +208,14 @@
if (batteryState.showPercent && batteryState.attribution != null) {
// 4a. percent & attribution. Implies space-sharing
- // Configure the attribute to draw in a smaller bounding box and align left
+ // Configure the attribute to draw in a smaller bounding box and align left and use
+ // floor/ceil math to make sure we get every available pixel
attribution.gravity = Gravity.LEFT
attribution.setBounds(
- scaledAttrRightCanvas.left.roundToInt(),
- scaledAttrRightCanvas.top.roundToInt(),
- scaledAttrRightCanvas.right.roundToInt(),
- scaledAttrRightCanvas.bottom.roundToInt(),
+ floor(scaledAttrRightCanvas.left).toInt(),
+ floor(scaledAttrRightCanvas.top).toInt(),
+ ceil(scaledAttrRightCanvas.right).toInt(),
+ ceil(scaledAttrRightCanvas.bottom).toInt(),
)
attribution.draw(canvas)
@@ -196,16 +242,44 @@
*/
override fun setAlpha(alpha: Int) {}
+ /**
+ * Interface that describes relevant top-level metrics for the proper rendering of this icon.
+ * The overall canvas is defined as ViewportWidth x ViewportHeight, which is hard coded to 24x14
+ * points.
+ *
+ * The attr canvas insets are rect inset definitions. That is, they are defined as l,t,r,b
+ * points from the nearest edge. Note that for RTL, we don't actually flip the text since
+ * numbers do not reverse for RTL locales.
+ */
interface M {
val ViewportWidth: Float
val ViewportHeight: Float
- // Bounds, oriented in the above viewport, where we will fit-center and center-align
- // an attribution that is the sole foreground element
- val AttrFullCanvas: RectF
- // Bounds, oriented in the above viewport, where we will fit-center and left-align
- // an attribution that is sharing space with the percent text of the drawable
- val AttrRightCanvas: RectF
+ /**
+ * Insets, oriented in the above viewport in LTR, that define the full canvas for a single
+ * foreground element. The element will be fit-center and center-aligned on this canvas
+ *
+ * 18x8 point size
+ */
+ val AttrFullCanvasInsets: RectF
+
+ /**
+ * Insets, oriented in the above viewport in LTR, that define the partial canvas for a
+ * foreground element that shares space with the percent text. The element will be
+ * fit-center and left-aligned on this canvas.
+ *
+ * 6x6 point size
+ */
+ val AttrRightCanvasInsets: RectF
+
+ /**
+ * Insets, oriented in the above viewport in RTL, that define the partial canvas for a
+ * foreground element that shares space with the percent text. The element will be
+ * fit-center and left-aligned on this canvas.
+ *
+ * 6x6 point size
+ */
+ val AttrRightCanvasInsetsRtl: RectF
}
companion object {
@@ -220,20 +294,9 @@
override val ViewportWidth: Float = 24f
override val ViewportHeight: Float = 14f
- /**
- * Bounds, oriented in the above viewport, where we will fit-center and center-align
- * an attribution that is the sole foreground element
- *
- * 18x8 point size
- */
- override val AttrFullCanvas: RectF = RectF(4f, 3f, 22f, 11f)
- /**
- * Bounds, oriented in the above viewport, where we will fit-center and left-align
- * an attribution that is sharing space with the percent text of the drawable
- *
- * 6x6 point size
- */
- override val AttrRightCanvas: RectF = RectF(16f, 4f, 22f, 10f)
+ override val AttrFullCanvasInsets = RectF(4f, 3f, 2f, 3f)
+ override val AttrRightCanvasInsets = RectF(16f, 4f, 2f, 4f)
+ override val AttrRightCanvasInsetsRtl = RectF(14f, 4f, 4f, 4f)
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt
index 123d6ba..aa0e373 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatteryPercentTextOnlyDrawable.kt
@@ -23,6 +23,7 @@
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.Drawable
+import android.view.View
import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
/**
@@ -71,6 +72,7 @@
}
override fun draw(canvas: Canvas) {
+ val rtl = layoutDirection == View.LAYOUT_DIRECTION_RTL
val totalAvailableHeight = CanvasHeight * vScale
// Distribute the vertical whitespace around the text. This is a simplified version of
@@ -81,11 +83,12 @@
val totalAvailableWidth = CanvasWidth * hScale
val textWidth = textPaint.measureText(percentText)
val offsetX = (totalAvailableWidth - textWidth) / 2
+ val startOffset = if (rtl) ViewportInsetRight else ViewportInsetLeft
// Draw the text centered in the available area
canvas.drawText(
percentText,
- (ViewportInsetLeft * hScale) + offsetX,
+ (startOffset * hScale) + offsetX,
(ViewportInsetTop * vScale) + offsetY,
textPaint
)
diff --git a/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt b/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt
index 0c418b9..3b4c779 100644
--- a/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt
+++ b/packages/SystemUI/src/com/android/systemui/battery/unified/BatterySpaceSharingPercentTextDrawable.kt
@@ -23,6 +23,7 @@
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.Drawable
+import android.view.View
import com.android.systemui.battery.unified.BatteryLayersDrawable.Companion.Metrics
/**
@@ -94,6 +95,7 @@
}
override fun draw(canvas: Canvas) {
+ val rtl = layoutDirection == View.LAYOUT_DIRECTION_RTL
val totalAvailableHeight = CanvasHeight * vScale
// Distribute the vertical whitespace around the text. This is a simplified version of
@@ -107,7 +109,7 @@
canvas.drawText(
percentText,
- (ViewportInsetLeft * hScale) + offsetX,
+ ((if (rtl) ViewportInsetLeftRtl else ViewportInsetLeft) * hScale) + offsetX,
(ViewportInsetTop * vScale) + offsetY,
textPaint
)
@@ -128,6 +130,7 @@
companion object {
private const val ViewportInsetLeft = 4f
+ private const val ViewportInsetLeftRtl = 2f
private const val ViewportInsetTop = 2f
private const val CanvasWidth = 12f
diff --git a/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogDelegate.java b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogDelegate.java
index 6af0fa0..66aeda6 100644
--- a/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogDelegate.java
+++ b/packages/SystemUI/src/com/android/systemui/bluetooth/BroadcastDialogDelegate.java
@@ -42,7 +42,7 @@
import com.android.systemui.broadcast.BroadcastSender;
import com.android.systemui.dagger.qualifiers.Background;
import com.android.systemui.media.controls.util.MediaDataUtils;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.phone.SystemUIDialog;
@@ -69,7 +69,7 @@
private final Context mContext;
private final UiEventLogger mUiEventLogger;
- private final MediaOutputDialogFactory mMediaOutputDialogFactory;
+ private final MediaOutputDialogManager mMediaOutputDialogManager;
private final LocalBluetoothManager mLocalBluetoothManager;
private final BroadcastSender mBroadcastSender;
private final SystemUIDialog.Factory mSystemUIDialogFactory;
@@ -157,7 +157,7 @@
@AssistedInject
BroadcastDialogDelegate(
Context context,
- MediaOutputDialogFactory mediaOutputDialogFactory,
+ MediaOutputDialogManager mediaOutputDialogManager,
@Nullable LocalBluetoothManager localBluetoothManager,
UiEventLogger uiEventLogger,
@Background Executor bgExecutor,
@@ -166,7 +166,7 @@
@Assisted(CURRENT_BROADCAST_APP) String currentBroadcastApp,
@Assisted(OUTPUT_PKG_NAME) String outputPkgName) {
mContext = context;
- mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ mMediaOutputDialogManager = mediaOutputDialogManager;
mLocalBluetoothManager = localBluetoothManager;
mSystemUIDialogFactory = systemUIDialogFactory;
mCurrentBroadcastApp = currentBroadcastApp;
@@ -218,7 +218,7 @@
R.string.bt_le_audio_broadcast_dialog_switch_app, switchBroadcastApp), null);
mSwitchBroadcast.setOnClickListener((view) -> startSwitchBroadcast());
changeOutput.setOnClickListener((view) -> {
- mMediaOutputDialogFactory.create(mOutputPackageName, true, null);
+ mMediaOutputDialogManager.createAndShow(mOutputPackageName, true, null);
dialog.dismiss();
});
cancelBtn.setOnClickListener((view) -> {
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
index 35b27aa..fc9a7df 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
@@ -21,7 +21,6 @@
import com.android.systemui.communal.domain.model.CommunalContentModel
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
-import com.android.systemui.deviceentry.domain.interactor.DeviceEntryInteractor
import com.android.systemui.log.LogBuffer
import com.android.systemui.log.core.Logger
import com.android.systemui.log.dagger.CommunalLog
@@ -47,7 +46,6 @@
import kotlinx.coroutines.launch
/** The default view model used for showing the communal hub. */
-@OptIn(ExperimentalCoroutinesApi::class)
@SysUISingleton
class CommunalViewModel
@Inject
@@ -56,7 +54,6 @@
private val communalInteractor: CommunalInteractor,
tutorialInteractor: CommunalTutorialInteractor,
shadeInteractor: ShadeInteractor,
- deviceEntryInteractor: DeviceEntryInteractor,
@Named(MediaModule.COMMUNAL_HUB) mediaHost: MediaHost,
@CommunalLog logBuffer: LogBuffer,
) : BaseCommunalViewModel(communalInteractor, mediaHost) {
@@ -90,8 +87,6 @@
/** Whether touches should be disabled in communal */
val touchesAllowed: Flow<Boolean> = not(shadeInteractor.isAnyFullyExpanded)
- val deviceUnlocked: Flow<Boolean> = deviceEntryInteractor.isUnlocked
-
init {
// Initialize our media host for the UMO. This only needs to happen once and must be done
// before the MediaHierarchyManager attempts to move the UMO to the hub.
diff --git a/packages/SystemUI/src/com/android/systemui/haptics/slider/SeekableSliderHapticPlugin.kt b/packages/SystemUI/src/com/android/systemui/haptics/slider/SeekableSliderHapticPlugin.kt
index 931a869..ed82278 100644
--- a/packages/SystemUI/src/com/android/systemui/haptics/slider/SeekableSliderHapticPlugin.kt
+++ b/packages/SystemUI/src/com/android/systemui/haptics/slider/SeekableSliderHapticPlugin.kt
@@ -163,6 +163,6 @@
}
companion object {
- const val KEY_UP_TIMEOUT = 100L
+ const val KEY_UP_TIMEOUT = 60L
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
index 840b309..26c63f3 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
@@ -109,7 +109,7 @@
import com.android.systemui.media.controls.util.MediaFlags;
import com.android.systemui.media.controls.util.MediaUiEventLogger;
import com.android.systemui.media.controls.util.SmallHash;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.monet.ColorScheme;
import com.android.systemui.monet.Style;
import com.android.systemui.plugins.ActivityStarter;
@@ -223,7 +223,7 @@
protected int mUid = Process.INVALID_UID;
private int mSmartspaceMediaItemsCount;
private MediaCarouselController mMediaCarouselController;
- private final MediaOutputDialogFactory mMediaOutputDialogFactory;
+ private final MediaOutputDialogManager mMediaOutputDialogManager;
private final FalsingManager mFalsingManager;
private MetadataAnimationHandler mMetadataAnimationHandler;
private ColorSchemeTransition mColorSchemeTransition;
@@ -304,7 +304,7 @@
MediaViewController mediaViewController,
SeekBarViewModel seekBarViewModel,
Lazy<MediaDataManager> lazyMediaDataManager,
- MediaOutputDialogFactory mediaOutputDialogFactory,
+ MediaOutputDialogManager mediaOutputDialogManager,
MediaCarouselController mediaCarouselController,
FalsingManager falsingManager,
SystemClock systemClock,
@@ -324,7 +324,7 @@
mSeekBarViewModel = seekBarViewModel;
mMediaViewController = mediaViewController;
mMediaDataManagerLazy = lazyMediaDataManager;
- mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ mMediaOutputDialogManager = mediaOutputDialogManager;
mMediaCarouselController = mediaCarouselController;
mFalsingManager = falsingManager;
mSystemClock = systemClock;
@@ -737,7 +737,7 @@
mPackageName, mMediaViewHolder.getSeamlessButton());
} else {
mLogger.logOpenOutputSwitcher(mUid, mPackageName, mInstanceId);
- mMediaOutputDialogFactory.create(mPackageName, true,
+ mMediaOutputDialogManager.createAndShow(mPackageName, true,
mMediaViewHolder.getSeamlessButton());
}
} else {
@@ -761,7 +761,7 @@
}
}
} else {
- mMediaOutputDialogFactory.create(mPackageName, true,
+ mMediaOutputDialogManager.createAndShow(mPackageName, true,
mMediaViewHolder.getSeamlessButton());
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/util/LocalMediaManagerFactory.kt b/packages/SystemUI/src/com/android/systemui/media/controls/util/LocalMediaManagerFactory.kt
index 5d113a9..452cb7e 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/util/LocalMediaManagerFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/util/LocalMediaManagerFactory.kt
@@ -31,7 +31,8 @@
) {
/** Creates a [LocalMediaManager] for the given package. */
fun create(packageName: String?): LocalMediaManager {
- return InfoMediaManager.createInstance(context, packageName, null, localBluetoothManager)
- .run { LocalMediaManager(context, localBluetoothManager, this, packageName) }
+ return InfoMediaManager.createInstance(context, packageName, localBluetoothManager).run {
+ LocalMediaManager(context, localBluetoothManager, this, packageName)
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt
deleted file mode 100644
index b6e3937..0000000
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogFactory.kt
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2022 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.dialog
-
-import android.app.KeyguardManager
-import android.content.Context
-import android.media.AudioManager
-import android.media.session.MediaSessionManager
-import android.os.PowerExemptionManager
-import android.view.View
-import com.android.internal.logging.UiEventLogger
-import com.android.settingslib.bluetooth.LocalBluetoothManager
-import com.android.systemui.animation.DialogTransitionAnimator
-import com.android.systemui.broadcast.BroadcastSender
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.media.nearby.NearbyMediaDevicesManager
-import com.android.systemui.plugins.ActivityStarter
-import com.android.systemui.settings.UserTracker
-import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
-import javax.inject.Inject
-
-/**
- * Factory to create [MediaOutputBroadcastDialog] objects.
- */
-class MediaOutputBroadcastDialogFactory @Inject constructor(
- private val context: Context,
- private val mediaSessionManager: MediaSessionManager,
- private val lbm: LocalBluetoothManager?,
- private val starter: ActivityStarter,
- private val broadcastSender: BroadcastSender,
- private val notifCollection: CommonNotifCollection,
- private val uiEventLogger: UiEventLogger,
- private val dialogTransitionAnimator: DialogTransitionAnimator,
- private val nearbyMediaDevicesManager: NearbyMediaDevicesManager,
- private val audioManager: AudioManager,
- private val powerExemptionManager: PowerExemptionManager,
- private val keyGuardManager: KeyguardManager,
- private val featureFlags: FeatureFlags,
- private val userTracker: UserTracker
-) {
- var mediaOutputBroadcastDialog: MediaOutputBroadcastDialog? = null
-
- /** Creates a [MediaOutputBroadcastDialog] for the given package. */
- fun create(packageName: String, aboveStatusBar: Boolean, view: View? = null) {
- // Dismiss the previous dialog, if any.
- mediaOutputBroadcastDialog?.dismiss()
-
- val controller = MediaOutputController(context, packageName,
- mediaSessionManager, lbm, starter, notifCollection,
- dialogTransitionAnimator, nearbyMediaDevicesManager, audioManager,
- powerExemptionManager, keyGuardManager, featureFlags, userTracker)
- val dialog =
- MediaOutputBroadcastDialog(context, aboveStatusBar, broadcastSender, controller)
- mediaOutputBroadcastDialog = dialog
-
- // Show the dialog.
- if (view != null) {
- dialogTransitionAnimator.showFromView(dialog, view)
- } else {
- dialog.show()
- }
- }
-
- /** dismiss [MediaOutputBroadcastDialog] if exist. */
- fun dismiss() {
- mediaOutputBroadcastDialog?.dismiss()
- mediaOutputBroadcastDialog = null
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogManager.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogManager.kt
new file mode 100644
index 0000000..54d175c
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputBroadcastDialogManager.kt
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2022 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.dialog
+
+import android.content.Context
+import android.view.View
+import com.android.systemui.animation.DialogTransitionAnimator
+import com.android.systemui.broadcast.BroadcastSender
+import javax.inject.Inject
+
+/** Manager to create and show a [MediaOutputBroadcastDialog]. */
+class MediaOutputBroadcastDialogManager
+@Inject
+constructor(
+ private val context: Context,
+ private val broadcastSender: BroadcastSender,
+ private val dialogTransitionAnimator: DialogTransitionAnimator,
+ private val mediaOutputControllerFactory: MediaOutputController.Factory
+) {
+ var mediaOutputBroadcastDialog: MediaOutputBroadcastDialog? = null
+
+ /** Creates a [MediaOutputBroadcastDialog] for the given package. */
+ fun createAndShow(packageName: String, aboveStatusBar: Boolean, view: View? = null) {
+ // Dismiss the previous dialog, if any.
+ mediaOutputBroadcastDialog?.dismiss()
+
+ val controller = mediaOutputControllerFactory.create(packageName)
+ val dialog =
+ MediaOutputBroadcastDialog(context, aboveStatusBar, broadcastSender, controller)
+ mediaOutputBroadcastDialog = dialog
+
+ // Show the dialog.
+ if (view != null) {
+ dialogTransitionAnimator.showFromView(dialog, view)
+ } else {
+ dialog.show()
+ }
+ }
+
+ /** dismiss [MediaOutputBroadcastDialog] if exist. */
+ fun dismiss() {
+ mediaOutputBroadcastDialog?.dismiss()
+ mediaOutputBroadcastDialog = null
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
index b3b7bce..adee7f2c 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputController.java
@@ -64,6 +64,7 @@
import android.view.WindowManager;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.core.graphics.drawable.IconCompat;
@@ -91,6 +92,10 @@
import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection;
import com.android.systemui.statusbar.phone.SystemUIDialog;
+import dagger.assisted.Assisted;
+import dagger.assisted.AssistedFactory;
+import dagger.assisted.AssistedInject;
+
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
@@ -105,8 +110,6 @@
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
-import javax.inject.Inject;
-
/**
* Controller for media output dialog
*/
@@ -170,10 +173,13 @@
ACTION_BROADCAST_INFO_ICON
}
- @Inject
- public MediaOutputController(@NonNull Context context, String packageName,
- MediaSessionManager mediaSessionManager, LocalBluetoothManager
- lbm, ActivityStarter starter,
+ @AssistedInject
+ public MediaOutputController(
+ Context context,
+ @Assisted String packageName,
+ MediaSessionManager mediaSessionManager,
+ @Nullable LocalBluetoothManager lbm,
+ ActivityStarter starter,
CommonNotifCollection notifCollection,
DialogTransitionAnimator dialogTransitionAnimator,
NearbyMediaDevicesManager nearbyMediaDevicesManager,
@@ -193,7 +199,7 @@
mKeyGuardManager = keyGuardManager;
mFeatureFlags = featureFlags;
mUserTracker = userTracker;
- InfoMediaManager imm = InfoMediaManager.createInstance(mContext, packageName, null, lbm);
+ InfoMediaManager imm = InfoMediaManager.createInstance(mContext, packageName, lbm);
mLocalMediaManager = new LocalMediaManager(mContext, lbm, imm, packageName);
mMetricLogger = new MediaOutputMetricLogger(mContext, mPackageName);
mDialogTransitionAnimator = dialogTransitionAnimator;
@@ -222,6 +228,12 @@
R.dimen.media_output_dialog_selectable_margin_end);
}
+ @AssistedFactory
+ public interface Factory {
+ /** Construct a MediaOutputController */
+ MediaOutputController create(String packageName);
+ }
+
protected void start(@NonNull Callback cb) {
synchronized (mMediaDevicesLock) {
mCachedMediaDevices.clear();
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogManager.kt
similarity index 62%
rename from packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt
rename to packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogManager.kt
index 02be0c1..e7816a4 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogFactory.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogManager.kt
@@ -16,43 +16,24 @@
package com.android.systemui.media.dialog
-import android.app.KeyguardManager
import android.content.Context
-import android.media.AudioManager
-import android.media.session.MediaSessionManager
-import android.os.PowerExemptionManager
import android.view.View
import com.android.internal.jank.InteractionJankMonitor
import com.android.internal.logging.UiEventLogger
-import com.android.settingslib.bluetooth.LocalBluetoothManager
import com.android.systemui.animation.DialogCuj
import com.android.systemui.animation.DialogTransitionAnimator
import com.android.systemui.broadcast.BroadcastSender
-import com.android.systemui.flags.FeatureFlags
-import com.android.systemui.media.nearby.NearbyMediaDevicesManager
-import com.android.systemui.plugins.ActivityStarter
-import com.android.systemui.settings.UserTracker
-import com.android.systemui.statusbar.notification.collection.notifcollection.CommonNotifCollection
import javax.inject.Inject
-/** Factory to create [MediaOutputDialog] objects. */
-open class MediaOutputDialogFactory
+/** Manager to create and show a [MediaOutputDialog]. */
+open class MediaOutputDialogManager
@Inject
constructor(
private val context: Context,
- private val mediaSessionManager: MediaSessionManager,
- private val lbm: LocalBluetoothManager?,
- private val starter: ActivityStarter,
private val broadcastSender: BroadcastSender,
- private val notifCollection: CommonNotifCollection,
private val uiEventLogger: UiEventLogger,
private val dialogTransitionAnimator: DialogTransitionAnimator,
- private val nearbyMediaDevicesManager: NearbyMediaDevicesManager,
- private val audioManager: AudioManager,
- private val powerExemptionManager: PowerExemptionManager,
- private val keyGuardManager: KeyguardManager,
- private val featureFlags: FeatureFlags,
- private val userTracker: UserTracker
+ private val mediaOutputControllerFactory: MediaOutputController.Factory,
) {
companion object {
const val INTERACTION_JANK_TAG = "media_output"
@@ -60,8 +41,8 @@
}
/** Creates a [MediaOutputDialog] for the given package. */
- open fun create(packageName: String, aboveStatusBar: Boolean, view: View? = null) {
- createWithController(
+ open fun createAndShow(packageName: String, aboveStatusBar: Boolean, view: View? = null) {
+ createAndShowWithController(
packageName,
aboveStatusBar,
controller =
@@ -78,12 +59,12 @@
}
/** Creates a [MediaOutputDialog] for the given package. */
- open fun createWithController(
+ open fun createAndShowWithController(
packageName: String,
aboveStatusBar: Boolean,
controller: DialogTransitionAnimator.Controller?,
) {
- create(
+ createAndShow(
packageName,
aboveStatusBar,
dialogTransitionAnimatorController = controller,
@@ -91,8 +72,10 @@
)
}
- open fun createDialogForSystemRouting(controller: DialogTransitionAnimator.Controller? = null) {
- create(
+ open fun createAndShowForSystemRouting(
+ controller: DialogTransitionAnimator.Controller? = null
+ ) {
+ createAndShow(
packageName = null,
aboveStatusBar = false,
dialogTransitionAnimatorController = null,
@@ -100,7 +83,7 @@
)
}
- private fun create(
+ private fun createAndShow(
packageName: String?,
aboveStatusBar: Boolean,
dialogTransitionAnimatorController: DialogTransitionAnimator.Controller?,
@@ -109,23 +92,9 @@
// Dismiss the previous dialog, if any.
mediaOutputDialog?.dismiss()
- val controller =
- MediaOutputController(
- context,
- packageName,
- mediaSessionManager,
- lbm,
- starter,
- notifCollection,
- dialogTransitionAnimator,
- nearbyMediaDevicesManager,
- audioManager,
- powerExemptionManager,
- keyGuardManager,
- featureFlags,
- userTracker
- )
- val dialog =
+ val controller = mediaOutputControllerFactory.create(packageName)
+
+ val mediaOutputDialog =
MediaOutputDialog(
context,
aboveStatusBar,
@@ -135,16 +104,15 @@
uiEventLogger,
includePlaybackAndAppMetadata
)
- mediaOutputDialog = dialog
// Show the dialog.
if (dialogTransitionAnimatorController != null) {
dialogTransitionAnimator.show(
- dialog,
+ mediaOutputDialog,
dialogTransitionAnimatorController,
)
} else {
- dialog.show()
+ mediaOutputDialog.show()
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogReceiver.kt b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogReceiver.kt
index 38d31ed..774792f 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogReceiver.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputDialogReceiver.kt
@@ -31,8 +31,8 @@
* BroadcastReceiver for handling media output intent
*/
class MediaOutputDialogReceiver @Inject constructor(
- private val mediaOutputDialogFactory: MediaOutputDialogFactory,
- private val mediaOutputBroadcastDialogFactory: MediaOutputBroadcastDialogFactory
+ private val mediaOutputDialogManager: MediaOutputDialogManager,
+ private val mediaOutputBroadcastDialogManager: MediaOutputBroadcastDialogManager
) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
@@ -42,7 +42,7 @@
launchMediaOutputDialogIfPossible(packageName)
}
MediaOutputConstants.ACTION_LAUNCH_SYSTEM_MEDIA_OUTPUT_DIALOG -> {
- mediaOutputDialogFactory.createDialogForSystemRouting()
+ mediaOutputDialogManager.createAndShowForSystemRouting()
}
MediaOutputConstants.ACTION_LAUNCH_MEDIA_OUTPUT_BROADCAST_DIALOG -> {
if (!legacyLeAudioSharing()) return
@@ -55,7 +55,7 @@
private fun launchMediaOutputDialogIfPossible(packageName: String?) {
if (!packageName.isNullOrEmpty()) {
- mediaOutputDialogFactory.create(packageName, false)
+ mediaOutputDialogManager.createAndShow(packageName, false)
} else if (DEBUG) {
Log.e(TAG, "Unable to launch media output dialog. Package name is empty.")
}
@@ -63,7 +63,7 @@
private fun launchMediaOutputBroadcastDialogIfPossible(packageName: String?) {
if (!packageName.isNullOrEmpty()) {
- mediaOutputBroadcastDialogFactory.create(
+ mediaOutputBroadcastDialogManager.createAndShow(
packageName, aboveStatusBar = true, view = null)
} else if (DEBUG) {
Log.e(TAG, "Unable to launch media output broadcast dialog. Package name is empty.")
diff --git a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSwitcherDialogUI.java b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSwitcherDialogUI.java
index b5b1f0f..6e7e0f2 100644
--- a/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSwitcherDialogUI.java
+++ b/packages/SystemUI/src/com/android/systemui/media/dialog/MediaOutputSwitcherDialogUI.java
@@ -34,15 +34,15 @@
private static final String TAG = "MediaOutputSwitcherDialogUI";
private final CommandQueue mCommandQueue;
- private final MediaOutputDialogFactory mMediaOutputDialogFactory;
+ private final MediaOutputDialogManager mMediaOutputDialogManager;
@Inject
public MediaOutputSwitcherDialogUI(
Context context,
CommandQueue commandQueue,
- MediaOutputDialogFactory mediaOutputDialogFactory) {
+ MediaOutputDialogManager mediaOutputDialogManager) {
mCommandQueue = commandQueue;
- mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ mMediaOutputDialogManager = mediaOutputDialogManager;
}
@Override
@@ -54,7 +54,7 @@
@MainThread
public void showMediaOutputSwitcher(String packageName) {
if (!TextUtils.isEmpty(packageName)) {
- mMediaOutputDialogFactory.create(packageName, false, null);
+ mMediaOutputDialogManager.createAndShow(packageName, false, null);
} else {
Log.e(TAG, "Unable to launch media output dialog. Package name is empty.");
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileDataInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileDataInteractor.kt
new file mode 100644
index 0000000..22bbbbb
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileDataInteractor.kt
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.domain.interactor
+
+import android.os.UserHandle
+import com.android.systemui.dagger.qualifiers.Background
+import com.android.systemui.qs.tiles.base.interactor.DataUpdateTrigger
+import com.android.systemui.qs.tiles.base.interactor.QSTileDataInteractor
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.statusbar.policy.BatteryController
+import com.android.systemui.util.kotlin.combine
+import com.android.systemui.util.kotlin.getBatteryLevel
+import com.android.systemui.util.kotlin.isBatteryPowerSaveEnabled
+import com.android.systemui.util.kotlin.isDevicePluggedIn
+import javax.inject.Inject
+import kotlin.coroutines.CoroutineContext
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.flowOn
+
+/** Observes BatterySaver mode state changes providing the [BatterySaverTileModel.Standard]. */
+open class BatterySaverTileDataInteractor
+@Inject
+constructor(
+ @Background private val bgCoroutineContext: CoroutineContext,
+ private val batteryController: BatteryController,
+) : QSTileDataInteractor<BatterySaverTileModel> {
+
+ override fun tileData(
+ user: UserHandle,
+ triggers: Flow<DataUpdateTrigger>
+ ): Flow<BatterySaverTileModel> =
+ combine(
+ batteryController.isDevicePluggedIn().distinctUntilChanged().flowOn(bgCoroutineContext),
+ batteryController
+ .isBatteryPowerSaveEnabled()
+ .distinctUntilChanged()
+ .flowOn(bgCoroutineContext),
+ batteryController.getBatteryLevel().distinctUntilChanged().flowOn(bgCoroutineContext),
+ ) {
+ isPluggedIn: Boolean,
+ isPowerSaverEnabled: Boolean,
+ _, // we are only interested in battery level change, not the actual level
+ ->
+ BatterySaverTileModel.Standard(isPluggedIn, isPowerSaverEnabled)
+ }
+
+ override fun availability(user: UserHandle): Flow<Boolean> = flowOf(true)
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileUserActionInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileUserActionInteractor.kt
new file mode 100644
index 0000000..1e4eb38
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/interactor/BatterySaverTileUserActionInteractor.kt
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.domain.interactor
+
+import android.content.Intent
+import android.provider.Settings
+import com.android.systemui.qs.tiles.base.actions.QSTileIntentUserInputHandler
+import com.android.systemui.qs.tiles.base.interactor.QSTileInput
+import com.android.systemui.qs.tiles.base.interactor.QSTileUserActionInteractor
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.qs.tiles.viewmodel.QSTileUserAction
+import com.android.systemui.statusbar.policy.BatteryController
+import javax.inject.Inject
+
+/** Handles airplane mode tile clicks and long clicks. */
+class BatterySaverTileUserActionInteractor
+@Inject
+constructor(
+ private val qsTileIntentUserActionHandler: QSTileIntentUserInputHandler,
+ private val batteryController: BatteryController
+) : QSTileUserActionInteractor<BatterySaverTileModel> {
+
+ override suspend fun handleInput(input: QSTileInput<BatterySaverTileModel>) =
+ with(input) {
+ when (action) {
+ is QSTileUserAction.Click -> {
+ if (!data.isPluggedIn) {
+ batteryController.setPowerSaveMode(!data.isPowerSaving, action.view)
+ }
+ }
+ is QSTileUserAction.LongClick -> {
+ qsTileIntentUserActionHandler.handle(
+ action.view,
+ Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS)
+ )
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/model/BatterySaverTileModel.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/model/BatterySaverTileModel.kt
new file mode 100644
index 0000000..dbec50d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/domain/model/BatterySaverTileModel.kt
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.domain.model
+
+/** BatterySaver mode tile model. */
+sealed interface BatterySaverTileModel {
+
+ val isPluggedIn: Boolean
+ val isPowerSaving: Boolean
+
+ /** For when the device does not support extreme battery saver mode. */
+ data class Standard(
+ override val isPluggedIn: Boolean,
+ override val isPowerSaving: Boolean,
+ ) : BatterySaverTileModel
+
+ /**
+ * For when device supports extreme battery saver mode. Whether or not that mode is enabled is
+ * determined through [isExtremeSaving].
+ */
+ data class Extreme(
+ override val isPluggedIn: Boolean,
+ override val isPowerSaving: Boolean,
+ val isExtremeSaving: Boolean,
+ ) : BatterySaverTileModel
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapper.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapper.kt
new file mode 100644
index 0000000..0c08fba
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/battery/ui/BatterySaverTileMapper.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery.ui
+
+import android.content.res.Resources
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.qs.tiles.base.interactor.QSTileDataToStateMapper
+import com.android.systemui.qs.tiles.impl.battery.domain.model.BatterySaverTileModel
+import com.android.systemui.qs.tiles.viewmodel.QSTileConfig
+import com.android.systemui.qs.tiles.viewmodel.QSTileState
+import com.android.systemui.res.R
+import javax.inject.Inject
+
+/** Maps [BatterySaverTileModel] to [QSTileState]. */
+open class BatterySaverTileMapper
+@Inject
+constructor(
+ @Main protected val resources: Resources,
+ private val theme: Resources.Theme,
+) : QSTileDataToStateMapper<BatterySaverTileModel> {
+
+ override fun map(config: QSTileConfig, data: BatterySaverTileModel): QSTileState =
+ QSTileState.build(resources, theme, config.uiConfig) {
+ label = resources.getString(R.string.battery_detail_switch_title)
+ contentDescription = label
+
+ icon = {
+ Icon.Loaded(
+ resources.getDrawable(
+ if (data.isPowerSaving) R.drawable.qs_battery_saver_icon_on
+ else R.drawable.qs_battery_saver_icon_off,
+ theme
+ ),
+ null
+ )
+ }
+
+ sideViewIcon = QSTileState.SideViewIcon.None
+
+ if (data.isPluggedIn) {
+ activationState = QSTileState.ActivationState.UNAVAILABLE
+ supportedActions = setOf(QSTileState.UserAction.LONG_CLICK)
+ secondaryLabel = ""
+ } else if (data.isPowerSaving) {
+ activationState = QSTileState.ActivationState.ACTIVE
+ supportedActions =
+ setOf(QSTileState.UserAction.CLICK, QSTileState.UserAction.LONG_CLICK)
+
+ if (data is BatterySaverTileModel.Extreme) {
+ secondaryLabel =
+ resources.getString(
+ if (data.isExtremeSaving) R.string.extreme_battery_saver_text
+ else R.string.standard_battery_saver_text
+ )
+ stateDescription = secondaryLabel
+ } else {
+ secondaryLabel = ""
+ }
+ } else {
+ activationState = QSTileState.ActivationState.INACTIVE
+ supportedActions =
+ setOf(QSTileState.UserAction.CLICK, QSTileState.UserAction.LONG_CLICK)
+ secondaryLabel = ""
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapper.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapper.kt
new file mode 100644
index 0000000..caae4d2
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/InternetTileMapper.kt
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain
+
+import android.content.Context
+import android.content.res.Resources
+import android.widget.Switch
+import com.android.systemui.common.shared.model.ContentDescription.Companion.loadContentDescription
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.common.shared.model.Text.Companion.loadText
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.qs.tiles.base.interactor.QSTileDataToStateMapper
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.qs.tiles.viewmodel.QSTileConfig
+import com.android.systemui.qs.tiles.viewmodel.QSTileState
+import com.android.systemui.res.R
+import javax.inject.Inject
+
+/** Maps [InternetTileModel] to [QSTileState]. */
+class InternetTileMapper
+@Inject
+constructor(
+ @Main private val resources: Resources,
+ private val theme: Resources.Theme,
+ private val context: Context,
+) : QSTileDataToStateMapper<InternetTileModel> {
+
+ override fun map(config: QSTileConfig, data: InternetTileModel): QSTileState =
+ QSTileState.build(resources, theme, config.uiConfig) {
+ label = resources.getString(R.string.quick_settings_internet_label)
+ expandedAccessibilityClass = Switch::class
+
+ if (data.secondaryLabel != null) {
+ secondaryLabel = data.secondaryLabel.loadText(context)
+ } else {
+ secondaryLabel = data.secondaryTitle
+ }
+
+ stateDescription = data.stateDescription.loadContentDescription(context)
+ contentDescription = data.contentDescription.loadContentDescription(context)
+
+ if (data.icon != null) {
+ this.icon = { data.icon }
+ } else if (data.iconId != null) {
+ val loadedIcon =
+ Icon.Loaded(
+ resources.getDrawable(data.iconId!!, theme),
+ contentDescription = null
+ )
+ this.icon = { loadedIcon }
+ }
+
+ sideViewIcon = QSTileState.SideViewIcon.Chevron
+
+ activationState =
+ if (data is InternetTileModel.Active) QSTileState.ActivationState.ACTIVE
+ else QSTileState.ActivationState.INACTIVE
+
+ supportedActions =
+ setOf(QSTileState.UserAction.CLICK, QSTileState.UserAction.LONG_CLICK)
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractor.kt
new file mode 100644
index 0000000..fdc596b
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileDataInteractor.kt
@@ -0,0 +1,275 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain.interactor
+
+import android.annotation.StringRes
+import android.content.Context
+import android.os.UserHandle
+import android.text.Html
+import com.android.settingslib.graph.SignalDrawable
+import com.android.systemui.common.shared.model.ContentDescription
+import com.android.systemui.common.shared.model.ContentDescription.Companion.loadContentDescription
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.common.shared.model.Text
+import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.qs.tiles.base.interactor.DataUpdateTrigger
+import com.android.systemui.qs.tiles.base.interactor.QSTileDataInteractor
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.res.R
+import com.android.systemui.statusbar.pipeline.airplane.data.repository.AirplaneModeRepository
+import com.android.systemui.statusbar.pipeline.ethernet.domain.EthernetInteractor
+import com.android.systemui.statusbar.pipeline.mobile.domain.interactor.MobileIconsInteractor
+import com.android.systemui.statusbar.pipeline.mobile.domain.model.SignalIconModel
+import com.android.systemui.statusbar.pipeline.shared.data.repository.ConnectivityRepository
+import com.android.systemui.statusbar.pipeline.wifi.domain.interactor.WifiInteractor
+import com.android.systemui.statusbar.pipeline.wifi.shared.model.WifiNetworkModel
+import com.android.systemui.statusbar.pipeline.wifi.ui.model.WifiIcon
+import javax.inject.Inject
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.stateIn
+
+@OptIn(ExperimentalCoroutinesApi::class)
+/** Observes internet state changes providing the [InternetTileModel]. */
+class InternetTileDataInteractor
+@Inject
+constructor(
+ private val context: Context,
+ @Application private val scope: CoroutineScope,
+ airplaneModeRepository: AirplaneModeRepository,
+ private val connectivityRepository: ConnectivityRepository,
+ ethernetInteractor: EthernetInteractor,
+ mobileIconsInteractor: MobileIconsInteractor,
+ wifiInteractor: WifiInteractor,
+) : QSTileDataInteractor<InternetTileModel> {
+ private val internetLabel: String = context.getString(R.string.quick_settings_internet_label)
+
+ // Three symmetrical Flows that can be switched upon based on the value of
+ // [DefaultConnectionModel]
+ private val wifiIconFlow: Flow<InternetTileModel> =
+ wifiInteractor.wifiNetwork.flatMapLatest {
+ val wifiIcon = WifiIcon.fromModel(it, context, showHotspotInfo = true)
+ if (it is WifiNetworkModel.Active && wifiIcon is WifiIcon.Visible) {
+ val secondary = removeDoubleQuotes(it.ssid)
+ flowOf(
+ InternetTileModel.Active(
+ secondaryTitle = secondary,
+ icon = Icon.Loaded(context.getDrawable(wifiIcon.icon.res)!!, null),
+ stateDescription = wifiIcon.contentDescription,
+ contentDescription = ContentDescription.Loaded("$internetLabel,$secondary"),
+ )
+ )
+ } else {
+ notConnectedFlow
+ }
+ }
+
+ private val mobileDataContentName: Flow<CharSequence?> =
+ mobileIconsInteractor.activeDataIconInteractor.flatMapLatest {
+ if (it == null) {
+ flowOf(null)
+ } else {
+ combine(it.isRoaming, it.networkTypeIconGroup) { isRoaming, networkTypeIconGroup ->
+ val cd = loadString(networkTypeIconGroup.contentDescription)
+ if (isRoaming) {
+ val roaming = context.getString(R.string.data_connection_roaming)
+ if (cd != null) {
+ context.getString(R.string.mobile_data_text_format, roaming, cd)
+ } else {
+ roaming
+ }
+ } else {
+ cd
+ }
+ }
+ }
+ }
+
+ private val mobileIconFlow: Flow<InternetTileModel> =
+ mobileIconsInteractor.activeDataIconInteractor.flatMapLatest {
+ if (it == null) {
+ notConnectedFlow
+ } else {
+ combine(
+ it.networkName,
+ it.signalLevelIcon,
+ mobileDataContentName,
+ ) { networkNameModel, signalIcon, dataContentDescription ->
+ when (signalIcon) {
+ is SignalIconModel.Cellular -> {
+ val secondary =
+ mobileDataContentConcat(
+ networkNameModel.name,
+ dataContentDescription
+ )
+
+ val stateLevel = signalIcon.level
+ val drawable = SignalDrawable(context)
+ drawable.setLevel(stateLevel)
+ val loadedIcon = Icon.Loaded(drawable, null)
+
+ InternetTileModel.Active(
+ secondaryTitle = secondary,
+ icon = loadedIcon,
+ stateDescription = ContentDescription.Loaded(secondary.toString()),
+ contentDescription = ContentDescription.Loaded(internetLabel),
+ )
+ }
+ is SignalIconModel.Satellite -> {
+ val secondary =
+ signalIcon.icon.contentDescription.loadContentDescription(context)
+ InternetTileModel.Active(
+ secondaryTitle = secondary,
+ iconId = signalIcon.icon.res,
+ stateDescription = ContentDescription.Loaded(secondary),
+ contentDescription = ContentDescription.Loaded(internetLabel),
+ )
+ }
+ }
+ }
+ }
+ }
+
+ private fun mobileDataContentConcat(
+ networkName: String?,
+ dataContentDescription: CharSequence?
+ ): CharSequence {
+ if (dataContentDescription == null) {
+ return networkName ?: ""
+ }
+ if (networkName == null) {
+ return Html.fromHtml(dataContentDescription.toString(), 0)
+ }
+
+ return Html.fromHtml(
+ context.getString(
+ R.string.mobile_carrier_text_format,
+ networkName,
+ dataContentDescription
+ ),
+ 0
+ )
+ }
+
+ private fun loadString(@StringRes resId: Int): CharSequence? =
+ if (resId != 0) {
+ context.getString(resId)
+ } else {
+ null
+ }
+
+ private val ethernetIconFlow: Flow<InternetTileModel> =
+ ethernetInteractor.icon.flatMapLatest {
+ if (it == null) {
+ notConnectedFlow
+ } else {
+ val secondary = it.contentDescription
+ flowOf(
+ InternetTileModel.Active(
+ secondaryLabel = secondary?.toText(),
+ iconId = it.res,
+ stateDescription = null,
+ contentDescription = secondary,
+ )
+ )
+ }
+ }
+
+ private val notConnectedFlow: StateFlow<InternetTileModel> =
+ combine(
+ wifiInteractor.areNetworksAvailable,
+ airplaneModeRepository.isAirplaneMode,
+ ) { networksAvailable, isAirplaneMode ->
+ when {
+ isAirplaneMode -> {
+ val secondary = context.getString(R.string.status_bar_airplane)
+ InternetTileModel.Inactive(
+ secondaryTitle = secondary,
+ iconId = R.drawable.ic_qs_no_internet_unavailable,
+ stateDescription = null,
+ contentDescription = ContentDescription.Loaded(secondary),
+ )
+ }
+ networksAvailable -> {
+ val secondary =
+ context.getString(R.string.quick_settings_networks_available)
+ InternetTileModel.Inactive(
+ secondaryTitle = secondary,
+ iconId = R.drawable.ic_qs_no_internet_available,
+ stateDescription = null,
+ contentDescription =
+ ContentDescription.Loaded("$internetLabel,$secondary")
+ )
+ }
+ else -> {
+ NOT_CONNECTED_NETWORKS_UNAVAILABLE
+ }
+ }
+ }
+ .stateIn(scope, SharingStarted.WhileSubscribed(), NOT_CONNECTED_NETWORKS_UNAVAILABLE)
+
+ /**
+ * Consumable flow describing the correct state for the InternetTile.
+ *
+ * Strict ordering of which repo is sending its data to the internet tile. Swaps between each of
+ * the interim providers (wifi, mobile, ethernet, or not-connected).
+ */
+ override fun tileData(
+ user: UserHandle,
+ triggers: Flow<DataUpdateTrigger>
+ ): Flow<InternetTileModel> =
+ connectivityRepository.defaultConnections.flatMapLatest {
+ when {
+ it.ethernet.isDefault -> ethernetIconFlow
+ it.mobile.isDefault || it.carrierMerged.isDefault -> mobileIconFlow
+ it.wifi.isDefault -> wifiIconFlow
+ else -> notConnectedFlow
+ }
+ }
+
+ override fun availability(user: UserHandle): Flow<Boolean> = flowOf(true)
+
+ private companion object {
+ val NOT_CONNECTED_NETWORKS_UNAVAILABLE =
+ InternetTileModel.Inactive(
+ secondaryLabel = Text.Resource(R.string.quick_settings_networks_unavailable),
+ iconId = R.drawable.ic_qs_no_internet_unavailable,
+ stateDescription = null,
+ contentDescription =
+ ContentDescription.Resource(R.string.quick_settings_networks_unavailable),
+ )
+
+ fun removeDoubleQuotes(string: String?): String? {
+ if (string == null) return null
+ return if (string.firstOrNull() == '"' && string.lastOrNull() == '"') {
+ string.substring(1, string.length - 1)
+ } else string
+ }
+
+ fun ContentDescription.toText(): Text =
+ when (this) {
+ is ContentDescription.Loaded -> Text.Loaded(this.description)
+ is ContentDescription.Resource -> Text.Resource(this.res)
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractor.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractor.kt
new file mode 100644
index 0000000..2620cd5
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/interactor/InternetTileUserActionInteractor.kt
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain.interactor
+
+import android.content.Intent
+import android.provider.Settings
+import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.qs.tiles.base.actions.QSTileIntentUserInputHandler
+import com.android.systemui.qs.tiles.base.interactor.QSTileInput
+import com.android.systemui.qs.tiles.base.interactor.QSTileUserActionInteractor
+import com.android.systemui.qs.tiles.dialog.InternetDialogManager
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
+import com.android.systemui.qs.tiles.viewmodel.QSTileUserAction
+import com.android.systemui.statusbar.connectivity.AccessPointController
+import javax.inject.Inject
+import kotlin.coroutines.CoroutineContext
+import kotlinx.coroutines.withContext
+
+/** Handles internet tile clicks. */
+class InternetTileUserActionInteractor
+@Inject
+constructor(
+ @Main private val mainContext: CoroutineContext,
+ private val internetDialogManager: InternetDialogManager,
+ private val accessPointController: AccessPointController,
+ private val qsTileIntentUserActionHandler: QSTileIntentUserInputHandler,
+) : QSTileUserActionInteractor<InternetTileModel> {
+
+ override suspend fun handleInput(input: QSTileInput<InternetTileModel>): Unit =
+ with(input) {
+ when (action) {
+ is QSTileUserAction.Click -> {
+ withContext(mainContext) {
+ internetDialogManager.create(
+ aboveStatusBar = true,
+ accessPointController.canConfigMobileData(),
+ accessPointController.canConfigWifi(),
+ action.view,
+ )
+ }
+ }
+ is QSTileUserAction.LongClick -> {
+ qsTileIntentUserActionHandler.handle(
+ action.view,
+ Intent(Settings.ACTION_WIFI_SETTINGS)
+ )
+ }
+ }
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/model/InternetTileModel.kt b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/model/InternetTileModel.kt
new file mode 100644
index 0000000..ece90461
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/impl/internet/domain/model/InternetTileModel.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet.domain.model
+
+import com.android.systemui.common.shared.model.ContentDescription
+import com.android.systemui.common.shared.model.Icon
+import com.android.systemui.common.shared.model.Text
+
+/** Model describing the state that the QS Internet tile should be in. */
+sealed interface InternetTileModel {
+ val secondaryTitle: CharSequence?
+ val secondaryLabel: Text?
+ val iconId: Int?
+ val icon: Icon?
+ val stateDescription: ContentDescription?
+ val contentDescription: ContentDescription?
+
+ data class Active(
+ override val secondaryTitle: CharSequence? = null,
+ override val secondaryLabel: Text? = null,
+ override val iconId: Int? = null,
+ override val icon: Icon? = null,
+ override val stateDescription: ContentDescription? = null,
+ override val contentDescription: ContentDescription? = null,
+ ) : InternetTileModel
+
+ data class Inactive(
+ override val secondaryTitle: CharSequence? = null,
+ override val secondaryLabel: Text? = null,
+ override val iconId: Int? = null,
+ override val icon: Icon? = null,
+ override val stateDescription: ContentDescription? = null,
+ override val contentDescription: ContentDescription? = null,
+ ) : InternetTileModel
+}
diff --git a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
index d0585d3..20bd7c6 100644
--- a/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
+++ b/packages/SystemUI/src/com/android/systemui/scrim/ScrimView.java
@@ -64,8 +64,6 @@
private String mScrimName;
private int mTintColor;
private boolean mBlendWithMainColor = true;
- private Runnable mChangeRunnable;
- private Executor mChangeRunnableExecutor;
private Executor mExecutor;
private Looper mExecutorLooper;
@Nullable
@@ -270,9 +268,6 @@
mDrawable.invalidateSelf();
}
- if (mChangeRunnable != null) {
- mChangeRunnableExecutor.execute(mChangeRunnable);
- }
}
public int getTint() {
@@ -300,9 +295,6 @@
mViewAlpha = alpha;
mDrawable.setAlpha((int) (255 * alpha));
- if (mChangeRunnable != null) {
- mChangeRunnableExecutor.execute(mChangeRunnable);
- }
}
});
}
@@ -311,14 +303,6 @@
return mViewAlpha;
}
- /**
- * Sets a callback that is invoked whenever the alpha, color, or tint change.
- */
- public void setChangeRunnable(Runnable changeRunnable, Executor changeRunnableExecutor) {
- mChangeRunnable = changeRunnable;
- mChangeRunnableExecutor = changeRunnableExecutor;
- }
-
@Override
protected boolean canReceivePointerEvents() {
return false;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
index 4ee8349..81f644f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt
@@ -352,10 +352,6 @@
/** Called by the touch helper when the drag down was aborted and should be reset. */
internal fun onDragDownReset() {
logger.logDragDownAborted()
- nsslController.setDimmed(
- /* dimmed= */ true,
- /* animate= */ true,
- )
nsslController.resetScrollPosition()
nsslController.resetCheckSnoozeLeavebehind()
setDragDownAmountAnimated(0f)
@@ -366,12 +362,7 @@
*
* @param above whether they dragged above it
*/
- internal fun onCrossedThreshold(above: Boolean) {
- nsslController.setDimmed(
- /* dimmed= */ !above,
- /* animate= */ true,
- )
- }
+ internal fun onCrossedThreshold(above: Boolean) {}
/** Called by the touch helper when the drag down was started */
internal fun onDragDownStarted(startingChild: ExpandableView?) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/ConnectivityModule.kt b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/ConnectivityModule.kt
index 642eacc..c4d9cbf 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/ConnectivityModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/connectivity/ConnectivityModule.kt
@@ -35,6 +35,10 @@
import com.android.systemui.qs.tiles.impl.airplane.domain.interactor.AirplaneModeTileDataInteractor
import com.android.systemui.qs.tiles.impl.airplane.domain.interactor.AirplaneModeTileUserActionInteractor
import com.android.systemui.qs.tiles.impl.airplane.domain.model.AirplaneModeTileModel
+import com.android.systemui.qs.tiles.impl.internet.domain.InternetTileMapper
+import com.android.systemui.qs.tiles.impl.internet.domain.interactor.InternetTileDataInteractor
+import com.android.systemui.qs.tiles.impl.internet.domain.interactor.InternetTileUserActionInteractor
+import com.android.systemui.qs.tiles.impl.internet.domain.model.InternetTileModel
import com.android.systemui.qs.tiles.impl.saver.domain.DataSaverTileMapper
import com.android.systemui.qs.tiles.impl.saver.domain.interactor.DataSaverTileDataInteractor
import com.android.systemui.qs.tiles.impl.saver.domain.interactor.DataSaverTileUserActionInteractor
@@ -90,6 +94,7 @@
const val AIRPLANE_MODE_TILE_SPEC = "airplane"
const val DATA_SAVER_TILE_SPEC = "saver"
+ const val INTERNET_TILE_SPEC = "internet"
/** Inject InternetTile or InternetTileNewImpl into tileMap in QSModule */
@Provides
@@ -168,5 +173,36 @@
stateInteractor,
mapper,
)
+
+ @Provides
+ @IntoMap
+ @StringKey(INTERNET_TILE_SPEC)
+ fun provideInternetTileConfig(uiEventLogger: QsEventLogger): QSTileConfig =
+ QSTileConfig(
+ tileSpec = TileSpec.create(INTERNET_TILE_SPEC),
+ uiConfig =
+ QSTileUIConfig.Resource(
+ iconRes = R.drawable.ic_qs_no_internet_available,
+ labelRes = R.string.quick_settings_internet_label,
+ ),
+ instanceId = uiEventLogger.getNewInstanceId(),
+ )
+
+ /** Inject InternetTile into tileViewModelMap in QSModule */
+ @Provides
+ @IntoMap
+ @StringKey(INTERNET_TILE_SPEC)
+ fun provideInternetTileViewModel(
+ factory: QSTileViewModelFactory.Static<InternetTileModel>,
+ mapper: InternetTileMapper,
+ stateInteractor: InternetTileDataInteractor,
+ userActionInteractor: InternetTileUserActionInteractor
+ ): QSTileViewModel =
+ factory.create(
+ TileSpec.create(INTERNET_TILE_SPEC),
+ userActionInteractor,
+ stateInteractor,
+ mapper,
+ )
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
index ea9df9a..05e8717 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableView.java
@@ -275,15 +275,6 @@
return getHeight();
}
- /**
- * Sets the notification as dimmed. The default implementation does nothing.
- *
- * @param dimmed Whether the notification should be dimmed.
- * @param fade Whether an animation should be played to change the state.
- */
- public void setDimmed(boolean dimmed, boolean fade) {
- }
-
public boolean isRemoved() {
return false;
}
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 c17ee39..f835cca 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
@@ -42,6 +42,7 @@
import android.view.ViewGroup;
import android.widget.RemoteViews;
+import com.android.app.tracing.TraceUtils;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.widget.ImageMessageConsumer;
import com.android.systemui.dagger.SysUISingleton;
@@ -369,49 +370,55 @@
ExpandableNotificationRow row,
NotifLayoutInflaterFactory.Provider notifLayoutInflaterFactoryProvider,
NotificationContentInflaterLogger logger) {
- InflationProgress result = new InflationProgress();
- final NotificationEntry entryForLogging = row.getEntry();
+ return TraceUtils.trace("NotificationContentInflater.createRemoteViews", () -> {
+ InflationProgress result = new InflationProgress();
+ final NotificationEntry entryForLogging = row.getEntry();
- if ((reInflateFlags & FLAG_CONTENT_VIEW_CONTRACTED) != 0) {
- logger.logAsyncTaskProgress(entryForLogging, "creating contracted remote view");
- result.newContentView = createContentView(builder, isLowPriority, usesIncreasedHeight);
- }
-
- if ((reInflateFlags & FLAG_CONTENT_VIEW_EXPANDED) != 0) {
- logger.logAsyncTaskProgress(entryForLogging, "creating expanded remote view");
- result.newExpandedView = createExpandedView(builder, isLowPriority);
- }
-
- if ((reInflateFlags & FLAG_CONTENT_VIEW_HEADS_UP) != 0) {
- logger.logAsyncTaskProgress(entryForLogging, "creating heads up remote view");
- result.newHeadsUpView = builder.createHeadsUpContentView(usesIncreasedHeadsUpHeight);
- }
-
- if ((reInflateFlags & FLAG_CONTENT_VIEW_PUBLIC) != 0) {
- logger.logAsyncTaskProgress(entryForLogging, "creating public remote view");
- result.newPublicView = builder.makePublicContentView(isLowPriority);
- }
-
- if (AsyncGroupHeaderViewInflation.isEnabled()) {
- if ((reInflateFlags & FLAG_GROUP_SUMMARY_HEADER) != 0) {
- logger.logAsyncTaskProgress(entryForLogging,
- "creating group summary remote view");
- result.mNewGroupHeaderView = builder.makeNotificationGroupHeader();
+ if ((reInflateFlags & FLAG_CONTENT_VIEW_CONTRACTED) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging, "creating contracted remote view");
+ result.newContentView = createContentView(builder, isLowPriority,
+ usesIncreasedHeight);
}
- if ((reInflateFlags & FLAG_LOW_PRIORITY_GROUP_SUMMARY_HEADER) != 0) {
- logger.logAsyncTaskProgress(entryForLogging,
- "creating low-priority group summary remote view");
- result.mNewLowPriorityGroupHeaderView =
- builder.makeLowPriorityContentView(true /* useRegularSubtext */);
+ if ((reInflateFlags & FLAG_CONTENT_VIEW_EXPANDED) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging, "creating expanded remote view");
+ result.newExpandedView = createExpandedView(builder, isLowPriority);
}
- }
- setNotifsViewsInflaterFactory(result, row, notifLayoutInflaterFactoryProvider);
- result.packageContext = packageContext;
- result.headsUpStatusBarText = builder.getHeadsUpStatusBarText(false /* showingPublic */);
- result.headsUpStatusBarTextPublic = builder.getHeadsUpStatusBarText(
- true /* showingPublic */);
- return result;
+
+ if ((reInflateFlags & FLAG_CONTENT_VIEW_HEADS_UP) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging, "creating heads up remote view");
+ result.newHeadsUpView = builder.createHeadsUpContentView(
+ usesIncreasedHeadsUpHeight);
+ }
+
+ if ((reInflateFlags & FLAG_CONTENT_VIEW_PUBLIC) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging, "creating public remote view");
+ result.newPublicView = builder.makePublicContentView(isLowPriority);
+ }
+
+ if (AsyncGroupHeaderViewInflation.isEnabled()) {
+ if ((reInflateFlags & FLAG_GROUP_SUMMARY_HEADER) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging,
+ "creating group summary remote view");
+ result.mNewGroupHeaderView = builder.makeNotificationGroupHeader();
+ }
+
+ if ((reInflateFlags & FLAG_LOW_PRIORITY_GROUP_SUMMARY_HEADER) != 0) {
+ logger.logAsyncTaskProgress(entryForLogging,
+ "creating low-priority group summary remote view");
+ result.mNewLowPriorityGroupHeaderView =
+ builder.makeLowPriorityContentView(true /* useRegularSubtext */);
+ }
+ }
+ setNotifsViewsInflaterFactory(result, row, notifLayoutInflaterFactoryProvider);
+ result.packageContext = packageContext;
+ result.headsUpStatusBarText = builder.getHeadsUpStatusBarText(
+ false /* showingPublic */);
+ result.headsUpStatusBarTextPublic = builder.getHeadsUpStatusBarText(
+ true /* showingPublic */);
+
+ return result;
+ });
}
private static void setNotifsViewsInflaterFactory(InflationProgress result,
@@ -445,6 +452,8 @@
RemoteViews.InteractionHandler remoteViewClickHandler,
@Nullable InflationCallback callback,
NotificationContentInflaterLogger logger) {
+ Trace.beginAsyncSection(APPLY_TRACE_METHOD, System.identityHashCode(row));
+
NotificationContentView privateLayout = row.getPrivateLayout();
NotificationContentView publicLayout = row.getPublicLayout();
final HashMap<Integer, CancellationSignal> runningInflations = new HashMap<>();
@@ -621,6 +630,7 @@
cancellationSignal.setOnCancelListener(
() -> {
logger.logAsyncTaskProgress(entry, "apply cancelled");
+ Trace.endAsyncSection(APPLY_TRACE_METHOD, System.identityHashCode(row));
runningInflations.values().forEach(CancellationSignal::cancel);
});
@@ -769,17 +779,17 @@
if (!requiresHeightCheck(entry)) {
return true;
}
- Trace.beginSection("NotificationContentInflater#satisfiesMinHeightRequirement");
- int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
- int referenceWidth = resources.getDimensionPixelSize(
- R.dimen.notification_validation_reference_width);
- int widthSpec = View.MeasureSpec.makeMeasureSpec(referenceWidth, View.MeasureSpec.EXACTLY);
- view.measure(widthSpec, heightSpec);
- int minHeight = resources.getDimensionPixelSize(
- R.dimen.notification_validation_minimum_allowed_height);
- boolean result = view.getMeasuredHeight() >= minHeight;
- Trace.endSection();
- return result;
+ return TraceUtils.trace("NotificationContentInflater#satisfiesMinHeightRequirement", () -> {
+ int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
+ int referenceWidth = resources.getDimensionPixelSize(
+ R.dimen.notification_validation_reference_width);
+ int widthSpec = View.MeasureSpec.makeMeasureSpec(referenceWidth,
+ View.MeasureSpec.EXACTLY);
+ view.measure(widthSpec, heightSpec);
+ int minHeight = resources.getDimensionPixelSize(
+ R.dimen.notification_validation_minimum_allowed_height);
+ return view.getMeasuredHeight() >= minHeight;
+ });
}
/**
@@ -966,6 +976,7 @@
entry.headsUpStatusBarText = result.headsUpStatusBarText;
entry.headsUpStatusBarTextPublic = result.headsUpStatusBarTextPublic;
+ Trace.endAsyncSection(APPLY_TRACE_METHOD, System.identityHashCode(row));
if (endListener != null) {
endListener.onAsyncInflationFinished(entry);
}
@@ -1102,83 +1113,97 @@
}
@Override
+ protected void onPreExecute() {
+ Trace.beginAsyncSection(ASYNC_TASK_TRACE_METHOD, System.identityHashCode(this));
+ }
+
+ @Override
protected InflationProgress doInBackground(Void... params) {
- try {
- final StatusBarNotification sbn = mEntry.getSbn();
- // Ensure the ApplicationInfo is updated before a builder is recovered.
- updateApplicationInfo(sbn);
- final Notification.Builder recoveredBuilder
- = Notification.Builder.recoverBuilder(mContext,
- sbn.getNotification());
+ return TraceUtils.trace("NotificationContentInflater.AsyncInflationTask#doInBackground",
+ () -> {
+ try {
+ return doInBackgroundInternal();
+ } catch (Exception e) {
+ mError = e;
+ mLogger.logAsyncTaskException(mEntry, "inflating", e);
+ return null;
+ }
+ });
+ }
- Context packageContext = sbn.getPackageContext(mContext);
- if (recoveredBuilder.usesTemplate()) {
- // For all of our templates, we want it to be RTL
- packageContext = new RtlEnabledContext(packageContext);
- }
- boolean isConversation = mEntry.getRanking().isConversation();
- Notification.MessagingStyle messagingStyle = null;
- if (isConversation) {
- messagingStyle = mConversationProcessor.processNotification(
- mEntry, recoveredBuilder, mLogger);
- }
- InflationProgress inflationProgress = createRemoteViews(mReInflateFlags,
- recoveredBuilder, mIsLowPriority, mUsesIncreasedHeight,
- mUsesIncreasedHeadsUpHeight, packageContext, mRow,
- mNotifLayoutInflaterFactoryProvider, mLogger);
+ private InflationProgress doInBackgroundInternal() {
+ final StatusBarNotification sbn = mEntry.getSbn();
+ // Ensure the ApplicationInfo is updated before a builder is recovered.
+ updateApplicationInfo(sbn);
+ final Notification.Builder recoveredBuilder = Notification.Builder.recoverBuilder(
+ mContext, sbn.getNotification());
- mLogger.logAsyncTaskProgress(mEntry,
- "getting existing smart reply state (on wrong thread!)");
- InflatedSmartReplyState previousSmartReplyState = mRow.getExistingSmartReplyState();
- mLogger.logAsyncTaskProgress(mEntry, "inflating smart reply views");
- InflationProgress result = inflateSmartReplyViews(
- /* result = */ inflationProgress,
- mReInflateFlags,
- mEntry,
- mContext,
- packageContext,
- previousSmartReplyState,
- mSmartRepliesInflater,
- mLogger);
-
- if (AsyncHybridViewInflation.isEnabled()) {
- // Inflate the single-line content view's ViewModel and ViewHolder from the
- // background thread, the ViewHolder needs to be bind with ViewModel later from
- // the main thread.
- result.mInflatedSingleLineViewModel = SingleLineViewInflater
- .inflateSingleLineViewModel(
- mEntry.getSbn().getNotification(),
- messagingStyle,
- recoveredBuilder,
- mContext
- );
- result.mInflatedSingleLineViewHolder =
- SingleLineViewInflater.inflateSingleLineViewHolder(
- isConversation,
- mReInflateFlags,
- mEntry,
- mContext,
- mLogger
- );
- }
-
- mLogger.logAsyncTaskProgress(mEntry,
- "getting row image resolver (on wrong thread!)");
- final NotificationInlineImageResolver imageResolver = mRow.getImageResolver();
- // wait for image resolver to finish preloading
- mLogger.logAsyncTaskProgress(mEntry, "waiting for preloaded images");
- imageResolver.waitForPreloadedImages(IMG_PRELOAD_TIMEOUT_MS);
-
- return result;
- } catch (Exception e) {
- mError = e;
- mLogger.logAsyncTaskException(mEntry, "inflating", e);
- return null;
+ Context packageContext = sbn.getPackageContext(mContext);
+ if (recoveredBuilder.usesTemplate()) {
+ // For all of our templates, we want it to be RTL
+ packageContext = new RtlEnabledContext(packageContext);
}
+ boolean isConversation = mEntry.getRanking().isConversation();
+ Notification.MessagingStyle messagingStyle = null;
+ if (isConversation) {
+ messagingStyle = mConversationProcessor.processNotification(
+ mEntry, recoveredBuilder, mLogger);
+ }
+ InflationProgress inflationProgress = createRemoteViews(mReInflateFlags,
+ recoveredBuilder, mIsLowPriority, mUsesIncreasedHeight,
+ mUsesIncreasedHeadsUpHeight, packageContext, mRow,
+ mNotifLayoutInflaterFactoryProvider, mLogger);
+
+ mLogger.logAsyncTaskProgress(mEntry,
+ "getting existing smart reply state (on wrong thread!)");
+ InflatedSmartReplyState previousSmartReplyState =
+ mRow.getExistingSmartReplyState();
+ mLogger.logAsyncTaskProgress(mEntry, "inflating smart reply views");
+ InflationProgress result = inflateSmartReplyViews(
+ /* result = */ inflationProgress,
+ mReInflateFlags,
+ mEntry,
+ mContext,
+ packageContext,
+ previousSmartReplyState,
+ mSmartRepliesInflater,
+ mLogger);
+
+ if (AsyncHybridViewInflation.isEnabled()) {
+ // Inflate the single-line content view's ViewModel and ViewHolder from the
+ // background thread, the ViewHolder needs to be bind with ViewModel later from
+ // the main thread.
+ result.mInflatedSingleLineViewModel = SingleLineViewInflater
+ .inflateSingleLineViewModel(
+ mEntry.getSbn().getNotification(),
+ messagingStyle,
+ recoveredBuilder,
+ mContext
+ );
+ result.mInflatedSingleLineViewHolder =
+ SingleLineViewInflater.inflateSingleLineViewHolder(
+ isConversation,
+ mReInflateFlags,
+ mEntry,
+ mContext,
+ mLogger
+ );
+ }
+
+ mLogger.logAsyncTaskProgress(mEntry,
+ "getting row image resolver (on wrong thread!)");
+ final NotificationInlineImageResolver imageResolver = mRow.getImageResolver();
+ // wait for image resolver to finish preloading
+ mLogger.logAsyncTaskProgress(mEntry, "waiting for preloaded images");
+ imageResolver.waitForPreloadedImages(IMG_PRELOAD_TIMEOUT_MS);
+
+ return result;
}
@Override
protected void onPostExecute(InflationProgress result) {
+ Trace.endAsyncSection(ASYNC_TASK_TRACE_METHOD, System.identityHashCode(this));
+
if (mError == null) {
// Logged in detail in apply.
mCancellationSignal = apply(
@@ -1197,6 +1222,11 @@
}
}
+ @Override
+ protected void onCancelled(InflationProgress result) {
+ Trace.endAsyncSection(ASYNC_TASK_TRACE_METHOD, System.identityHashCode(this));
+ }
+
private void handleError(Exception e) {
mEntry.onInflationTaskFinished();
StatusBarNotification sbn = mEntry.getSbn();
@@ -1294,4 +1324,8 @@
public abstract void setResultView(View v);
public abstract RemoteViews getRemoteView();
}
+
+ private static final String ASYNC_TASK_TRACE_METHOD =
+ "NotificationContentInflater.AsyncInflationTask";
+ private static final String APPLY_TRACE_METHOD = "NotificationContentInflater#apply";
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AmbientState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AmbientState.java
index c90acee..ab2f664 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AmbientState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AmbientState.java
@@ -61,7 +61,6 @@
*/
private StatusBarKeyguardViewManager mStatusBarKeyguardViewManager;
private int mScrollY;
- private boolean mDimmed;
private float mOverScrollTopAmount;
private float mOverScrollBottomAmount;
private boolean mDozing;
@@ -344,14 +343,6 @@
this.mScrollY = Math.max(scrollY, 0);
}
- /**
- * @param dimmed Whether we are in a dimmed state (on the lockscreen), where the backgrounds are
- * translucent and everything is scaled back a bit.
- */
- public void setDimmed(boolean dimmed) {
- mDimmed = dimmed;
- }
-
/** While dozing, we draw as little as possible, assuming a black background */
public void setDozing(boolean dozing) {
mDozing = dozing;
@@ -375,12 +366,6 @@
mHideSensitive = hideSensitive;
}
- public boolean isDimmed() {
- // While we are expanding from pulse, we want the notifications not to be dimmed, otherwise
- // you'd see the difference to the pulsing notification
- return mDimmed && !(isPulseExpanding() && mDozeAmount == 1.0f);
- }
-
public boolean isDozing() {
return mDozing;
}
@@ -768,7 +753,6 @@
pw.println("mHideSensitive=" + mHideSensitive);
pw.println("mShadeExpanded=" + mShadeExpanded);
pw.println("mClearAllInProgress=" + mClearAllInProgress);
- pw.println("mDimmed=" + mDimmed);
pw.println("mStatusBarState=" + mStatusBarState);
pw.println("mExpansionChanging=" + mExpansionChanging);
pw.println("mPanelFullWidth=" + mIsSmallScreen);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AnimationFilter.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AnimationFilter.java
index 5343cbf..03a1082 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AnimationFilter.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/AnimationFilter.java
@@ -35,7 +35,6 @@
boolean animateZ;
boolean animateHeight;
boolean animateTopInset;
- boolean animateDimmed;
boolean animateHideSensitive;
boolean hasDelays;
boolean hasGoToFullShadeEvent;
@@ -83,11 +82,6 @@
return this;
}
- public AnimationFilter animateDimmed() {
- animateDimmed = true;
- return this;
- }
-
public AnimationFilter animateHideSensitive() {
animateHideSensitive = true;
return this;
@@ -128,7 +122,6 @@
animateZ |= filter.animateZ;
animateHeight |= filter.animateHeight;
animateTopInset |= filter.animateTopInset;
- animateDimmed |= filter.animateDimmed;
animateHideSensitive |= filter.animateHideSensitive;
hasDelays |= filter.hasDelays;
mAnimatedProperties.addAll(filter.mAnimatedProperties);
@@ -142,7 +135,6 @@
animateZ = false;
animateHeight = false;
animateTopInset = false;
- animateDimmed = false;
animateHideSensitive = false;
hasDelays = false;
hasGoToFullShadeEvent = false;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
index d0c5c82..d1e5ab0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/ExpandableViewState.java
@@ -88,7 +88,6 @@
| ExpandableViewState.LOCATION_MAIN_AREA;
public int height;
- public boolean dimmed;
public boolean hideSensitive;
public boolean belowSpeedBump;
public boolean inShelf;
@@ -128,7 +127,6 @@
if (viewState instanceof ExpandableViewState) {
ExpandableViewState svs = (ExpandableViewState) viewState;
height = svs.height;
- dimmed = svs.dimmed;
hideSensitive = svs.hideSensitive;
belowSpeedBump = svs.belowSpeedBump;
clipTopAmount = svs.clipTopAmount;
@@ -155,9 +153,6 @@
expandableView.setActualHeight(newHeight, false /* notifyListeners */);
}
- // apply dimming
- expandableView.setDimmed(this.dimmed, false /* animate */);
-
// apply hiding sensitive
expandableView.setHideSensitive(
this.hideSensitive, false /* animated */, 0 /* delay */, 0 /* duration */);
@@ -216,9 +211,6 @@
abortAnimation(child, TAG_ANIMATOR_BOTTOM_INSET);
}
- // start dimmed animation
- expandableView.setDimmed(this.dimmed, animationFilter.animateDimmed);
-
// apply below the speed bump
if (!NotificationIconContainerRefactor.isEnabled()) {
expandableView.setBelowSpeedBump(this.belowSpeedBump);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainer.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainer.java
index fa97300..28f874d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainer.java
@@ -795,7 +795,6 @@
} else {
childState.setZTranslation(0);
}
- childState.dimmed = parentState.dimmed;
childState.hideSensitive = parentState.hideSensitive;
childState.belowSpeedBump = parentState.belowSpeedBump;
childState.clipTopAmount = 0;
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 27db84f..bfda6d5 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
@@ -29,10 +29,6 @@
import static java.lang.annotation.RetentionPolicy.SOURCE;
-import android.animation.Animator;
-import android.animation.AnimatorListenerAdapter;
-import android.animation.TimeAnimator;
-import android.animation.ValueAnimator;
import android.annotation.ColorInt;
import android.annotation.DrawableRes;
import android.annotation.FloatRange;
@@ -79,7 +75,6 @@
import com.android.app.animation.Interpolators;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.graphics.ColorUtils;
import com.android.internal.jank.InteractionJankMonitor;
import com.android.internal.policy.SystemBarUtils;
import com.android.keyguard.BouncerPanelExpansionCalculator;
@@ -163,18 +158,11 @@
* Sentinel value for no current active pointer. Used by {@link #mActivePointerId}.
*/
private static final int INVALID_POINTER = -1;
- /**
- * The distance in pixels between sections when the sections are directly adjacent (no visible
- * gap is drawn between them). In this case we don't want to round their corners.
- */
- private static final int DISTANCE_BETWEEN_ADJACENT_SECTIONS_PX = 1;
private boolean mKeyguardBypassEnabled;
private final ExpandHelper mExpandHelper;
private NotificationSwipeHelper mSwipeHelper;
private int mCurrentStackHeight = Integer.MAX_VALUE;
- private final Paint mBackgroundPaint = new Paint();
- private final boolean mShouldDrawNotificationBackground;
private boolean mHighPriorityBeforeSpeedBump;
private float mExpandedHeight;
@@ -263,7 +251,6 @@
private OnEmptySpaceClickListener mOnEmptySpaceClickListener;
private boolean mNeedsAnimation;
private boolean mTopPaddingNeedsAnimation;
- private boolean mDimmedNeedsAnimation;
private boolean mHideSensitiveNeedsAnimation;
private boolean mActivateNeedsAnimation;
private boolean mGoToFullShadeNeedsAnimation;
@@ -350,40 +337,15 @@
}
};
private final NotificationSection[] mSections;
- private boolean mAnimateNextBackgroundTop;
- private boolean mAnimateNextBackgroundBottom;
- private boolean mAnimateNextSectionBoundsChange;
- private @ColorInt int mBgColor;
- private float mDimAmount;
- private ValueAnimator mDimAnimator;
private final ArrayList<ExpandableView> mTmpSortedChildren = new ArrayList<>();
- private final Animator.AnimatorListener mDimEndListener = new AnimatorListenerAdapter() {
- @Override
- public void onAnimationEnd(Animator animation) {
- mDimAnimator = null;
- }
- };
- private final ValueAnimator.AnimatorUpdateListener mDimUpdateListener
- = new ValueAnimator.AnimatorUpdateListener() {
-
- @Override
- public void onAnimationUpdate(ValueAnimator animation) {
- setDimAmount((Float) animation.getAnimatedValue());
- }
- };
protected ViewGroup mQsHeader;
// Rect of QsHeader. Kept as a field just to avoid creating a new one each time.
private final Rect mQsHeaderBound = new Rect();
private boolean mContinuousShadowUpdate;
- private boolean mContinuousBackgroundUpdate;
private final ViewTreeObserver.OnPreDrawListener mShadowUpdater = () -> {
updateViewShadows();
return true;
};
- private final ViewTreeObserver.OnPreDrawListener mBackgroundUpdater = () -> {
- updateBackground();
- return true;
- };
private final Comparator<ExpandableView> mViewPositionComparator = (view, otherView) -> {
float endY = view.getTranslationY() + view.getActualHeight();
float otherEndY = otherView.getTranslationY() + otherView.getActualHeight();
@@ -481,7 +443,6 @@
private boolean mHeadsUpAnimatingAway;
private int mStatusBarState;
private int mUpcomingStatusBarState;
- private int mCachedBackgroundColor;
private boolean mHeadsUpGoingAwayAnimationsAllowed = true;
private final Runnable mReflingAndAnimateScroll = this::animateScroll;
private int mCornerRadius;
@@ -581,7 +542,6 @@
*/
private boolean mDismissUsingRowTranslationX = true;
private ExpandableNotificationRow mTopHeadsUpRow;
- private long mNumHeadsUp;
private NotificationStackScrollLayoutController.TouchHandler mTouchHandler;
private final ScreenOffAnimationController mScreenOffAnimationController;
private boolean mShouldUseSplitNotificationShade;
@@ -595,7 +555,7 @@
mSplitShadeStateController = splitShadeStateController;
updateSplitNotificationShade();
}
- private FeatureFlags mFeatureFlags;
+ private final FeatureFlags mFeatureFlags;
private final ExpandableView.OnHeightChangedListener mOnChildHeightChangedListener =
new ExpandableView.OnHeightChangedListener() {
@@ -667,8 +627,6 @@
mSections = mSectionsManager.createSectionsForBuckets();
mAmbientState = Dependency.get(AmbientState.class);
- mBgColor = Utils.getColorAttr(mContext,
- com.android.internal.R.attr.materialColorSurfaceContainerHigh).getDefaultColor();
int minHeight = res.getDimensionPixelSize(R.dimen.notification_min_height);
int maxHeight = res.getDimensionPixelSize(R.dimen.notification_max_height);
mSplitShadeMinContentHeight = res.getDimensionPixelSize(
@@ -680,16 +638,12 @@
mStackScrollAlgorithm = createStackScrollAlgorithm(context);
mStateAnimator = new StackStateAnimator(context, this);
- mShouldDrawNotificationBackground =
- res.getBoolean(R.bool.config_drawNotificationBackground);
setOutlineProvider(mOutlineProvider);
// We could set this whenever we 'requestChildUpdate' much like the viewTreeObserver, but
// that adds a bunch of complexity, and drawing nothing isn't *that* expensive.
- boolean willDraw = SceneContainerFlag.isEnabled()
- || mShouldDrawNotificationBackground || mDebugLines;
+ boolean willDraw = SceneContainerFlag.isEnabled() || mDebugLines;
setWillNotDraw(!willDraw);
- mBackgroundPaint.setAntiAlias(true);
if (mDebugLines) {
mDebugPaint = new Paint();
mDebugPaint.setColor(0xffff0000);
@@ -812,9 +766,6 @@
}
void updateBgColor() {
- mBgColor = Utils.getColorAttr(mContext,
- com.android.internal.R.attr.materialColorSurfaceContainerHigh).getDefaultColor();
- updateBackgroundDimming();
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child instanceof ActivatableNotificationView activatableView) {
@@ -835,14 +786,6 @@
protected void onDraw(Canvas canvas) {
onJustBeforeDraw();
- if (mShouldDrawNotificationBackground
- && (mSections[0].getCurrentBounds().top
- < mSections[mSections.length - 1].getCurrentBounds().bottom
- || mAmbientState.isDozing())) {
- drawBackground(canvas);
- } else if (mInHeadsUpPinnedMode || mHeadsUpAnimatingAway) {
- drawHeadsUpBackground(canvas);
- }
if (mDebugLines) {
onDrawDebug(canvas);
@@ -930,150 +873,6 @@
return textY;
}
- private void drawBackground(Canvas canvas) {
- int lockScreenLeft = mSidePaddings;
- int lockScreenRight = getWidth() - mSidePaddings;
- int lockScreenTop = mSections[0].getCurrentBounds().top;
- int lockScreenBottom = mSections[mSections.length - 1].getCurrentBounds().bottom;
- int hiddenLeft = getWidth() / 2;
- int hiddenTop = mTopPadding;
-
- float yProgress = 1 - mInterpolatedHideAmount;
- float xProgress = mHideXInterpolator.getInterpolation(
- (1 - mLinearHideAmount) * mBackgroundXFactor);
-
- int left = (int) MathUtils.lerp(hiddenLeft, lockScreenLeft, xProgress);
- int right = (int) MathUtils.lerp(hiddenLeft, lockScreenRight, xProgress);
- int top = (int) MathUtils.lerp(hiddenTop, lockScreenTop, yProgress);
- int bottom = (int) MathUtils.lerp(hiddenTop, lockScreenBottom, yProgress);
- mBackgroundAnimationRect.set(
- left,
- top,
- right,
- bottom);
-
- int backgroundTopAnimationOffset = top - lockScreenTop;
- // TODO(kprevas): this may not be necessary any more since we don't display the shelf in AOD
- boolean anySectionHasVisibleChild = false;
- for (NotificationSection section : mSections) {
- if (section.needsBackground()) {
- anySectionHasVisibleChild = true;
- break;
- }
- }
- boolean shouldDrawBackground;
- if (mKeyguardBypassEnabled && onKeyguard()) {
- shouldDrawBackground = isPulseExpanding();
- } else {
- shouldDrawBackground = !mAmbientState.isDozing() || anySectionHasVisibleChild;
- }
- if (shouldDrawBackground) {
- drawBackgroundRects(canvas, left, right, top, backgroundTopAnimationOffset);
- }
-
- updateClipping();
- }
-
- /**
- * Draws round rects for each background section.
- * <p>
- * We want to draw a round rect for each background section as defined by {@link #mSections}.
- * However, if two sections are directly adjacent with no gap between them (e.g. on the
- * lockscreen where the shelf can appear directly below the high priority section, or while
- * scrolling the shade so that the top of the shelf is right at the bottom of the high priority
- * section), we don't want to round the adjacent corners.
- * <p>
- * Since {@link Canvas} doesn't provide a way to draw a half-rounded rect, this means that we
- * need to coalesce the backgrounds for adjacent sections and draw them as a single round rect.
- * This method tracks the top of each rect we need to draw, then iterates through the visible
- * sections. If a section is not adjacent to the previous section, we draw the previous rect
- * behind the sections we've accumulated up to that point, then start a new rect at the top of
- * the current section. When we're done iterating we will always have one rect left to draw.
- */
- private void drawBackgroundRects(Canvas canvas, int left, int right, int top,
- int animationYOffset) {
- int backgroundRectTop = top;
- int lastSectionBottom =
- mSections[0].getCurrentBounds().bottom + animationYOffset;
- int currentLeft = left;
- int currentRight = right;
- boolean first = true;
- for (NotificationSection section : mSections) {
- if (!section.needsBackground()) {
- continue;
- }
- int sectionTop = section.getCurrentBounds().top + animationYOffset;
- int ownLeft = Math.min(Math.max(left, section.getCurrentBounds().left), right);
- int ownRight = Math.max(Math.min(right, section.getCurrentBounds().right), ownLeft);
- // If sections are directly adjacent to each other, we don't want to draw them
- // as separate roundrects, as the rounded corners right next to each other look
- // bad.
- if (sectionTop - lastSectionBottom > DISTANCE_BETWEEN_ADJACENT_SECTIONS_PX
- || ((currentLeft != ownLeft || currentRight != ownRight) && !first)) {
- canvas.drawRoundRect(currentLeft,
- backgroundRectTop,
- currentRight,
- lastSectionBottom,
- mCornerRadius, mCornerRadius, mBackgroundPaint);
- backgroundRectTop = sectionTop;
- }
- currentLeft = ownLeft;
- currentRight = ownRight;
- lastSectionBottom =
- section.getCurrentBounds().bottom + animationYOffset;
- first = false;
- }
- canvas.drawRoundRect(currentLeft,
- backgroundRectTop,
- currentRight,
- lastSectionBottom,
- mCornerRadius, mCornerRadius, mBackgroundPaint);
- }
-
- private void drawHeadsUpBackground(Canvas canvas) {
- int left = mSidePaddings;
- int right = getWidth() - mSidePaddings;
-
- float top = getHeight();
- float bottom = 0;
- int childCount = getChildCount();
- for (int i = 0; i < childCount; i++) {
- View child = getChildAt(i);
- if (child.getVisibility() != View.GONE
- && child instanceof ExpandableNotificationRow row) {
- if ((row.isPinned() || row.isHeadsUpAnimatingAway()) && row.getTranslation() < 0
- && row.getProvider().shouldShowGutsOnSnapOpen()) {
- top = Math.min(top, row.getTranslationY());
- bottom = Math.max(bottom, row.getTranslationY() + row.getActualHeight());
- }
- }
- }
-
- if (top < bottom) {
- canvas.drawRoundRect(
- left, top, right, bottom,
- mCornerRadius, mCornerRadius, mBackgroundPaint);
- }
- }
-
- void updateBackgroundDimming() {
- // No need to update the background color if it's not being drawn.
- if (!mShouldDrawNotificationBackground) {
- return;
- }
- // Interpolate between semi-transparent notification panel background color
- // and white AOD separator.
- float colorInterpolation = MathUtils.smoothStep(0.4f /* start */, 1f /* end */,
- mLinearHideAmount);
- int color = ColorUtils.blendARGB(mBgColor, Color.WHITE, colorInterpolation);
-
- if (mCachedBackgroundColor != color) {
- mCachedBackgroundColor = color;
- mBackgroundPaint.setColor(color);
- invalidate();
- }
- }
-
private void reinitView() {
initView(getContext(), mSwipeHelper, mNotificationStackSizeCalculator);
}
@@ -1359,9 +1158,6 @@
private void onPreDrawDuringAnimation() {
mShelf.updateAppearance();
- if (!mNeedsAnimation && !mChildrenUpdateRequested) {
- updateBackground();
- }
}
private void updateScrollStateForAddedChildren() {
@@ -2565,125 +2361,6 @@
}
}
- private void updateBackground() {
- // No need to update the background color if it's not being drawn.
- if (!mShouldDrawNotificationBackground) {
- return;
- }
-
- updateBackgroundBounds();
- if (didSectionBoundsChange()) {
- boolean animate = mAnimateNextSectionBoundsChange || mAnimateNextBackgroundTop
- || mAnimateNextBackgroundBottom || areSectionBoundsAnimating();
- if (!isExpanded()) {
- abortBackgroundAnimators();
- animate = false;
- }
- if (animate) {
- startBackgroundAnimation();
- } else {
- for (NotificationSection section : mSections) {
- section.resetCurrentBounds();
- }
- invalidate();
- }
- } else {
- abortBackgroundAnimators();
- }
- mAnimateNextBackgroundTop = false;
- mAnimateNextBackgroundBottom = false;
- mAnimateNextSectionBoundsChange = false;
- }
-
- private void abortBackgroundAnimators() {
- for (NotificationSection section : mSections) {
- section.cancelAnimators();
- }
- }
-
- private boolean didSectionBoundsChange() {
- for (NotificationSection section : mSections) {
- if (section.didBoundsChange()) {
- return true;
- }
- }
- return false;
- }
-
- private boolean areSectionBoundsAnimating() {
- for (NotificationSection section : mSections) {
- if (section.areBoundsAnimating()) {
- return true;
- }
- }
- return false;
- }
-
- private void startBackgroundAnimation() {
- // TODO(kprevas): do we still need separate fields for top/bottom?
- // or can each section manage its own animation state?
- NotificationSection firstVisibleSection = getFirstVisibleSection();
- NotificationSection lastVisibleSection = getLastVisibleSection();
- for (NotificationSection section : mSections) {
- section.startBackgroundAnimation(
- section == firstVisibleSection
- ? mAnimateNextBackgroundTop
- : mAnimateNextSectionBoundsChange,
- section == lastVisibleSection
- ? mAnimateNextBackgroundBottom
- : mAnimateNextSectionBoundsChange);
- }
- }
-
- /**
- * Update the background bounds to the new desired bounds
- */
- private void updateBackgroundBounds() {
- int left = mSidePaddings;
- int right = getWidth() - mSidePaddings;
- for (NotificationSection section : mSections) {
- section.getBounds().left = left;
- section.getBounds().right = right;
- }
-
- if (!mIsExpanded) {
- for (NotificationSection section : mSections) {
- section.getBounds().top = 0;
- section.getBounds().bottom = 0;
- }
- return;
- }
- int minTopPosition;
- NotificationSection lastSection = getLastVisibleSection();
- boolean onKeyguard = mStatusBarState == StatusBarState.KEYGUARD;
- if (!onKeyguard) {
- minTopPosition = (int) (mTopPadding + mStackTranslation);
- } else if (lastSection == null) {
- minTopPosition = mTopPadding;
- } else {
- // The first sections could be empty while there could still be elements in later
- // sections. The position of these first few sections is determined by the position of
- // the first visible section.
- NotificationSection firstVisibleSection = getFirstVisibleSection();
- firstVisibleSection.updateBounds(0 /* minTopPosition*/, 0 /* minBottomPosition */,
- false /* shiftPulsingWithFirst */);
- minTopPosition = firstVisibleSection.getBounds().top;
- }
- boolean shiftPulsingWithFirst = mNumHeadsUp <= 1
- && (mAmbientState.isDozing() || (mKeyguardBypassEnabled && onKeyguard));
- for (NotificationSection section : mSections) {
- int minBottomPosition = minTopPosition;
- if (section == lastSection) {
- // We need to make sure the section goes all the way to the shelf
- minBottomPosition = (int) (ViewState.getFinalTranslationY(mShelf)
- + mShelf.getIntrinsicHeight());
- }
- minTopPosition = section.updateBounds(minTopPosition, minBottomPosition,
- shiftPulsingWithFirst);
- shiftPulsingWithFirst = false;
- }
- }
-
private NotificationSection getFirstVisibleSection() {
for (NotificationSection section : mSections) {
if (section.getFirstVisibleChild() != null) {
@@ -3184,13 +2861,7 @@
mSections, getChildrenWithBackground());
if (mAnimationsEnabled && mIsExpanded) {
- mAnimateNextBackgroundTop = firstChild != previousFirstChild;
- mAnimateNextBackgroundBottom = lastChild != previousLastChild || mAnimateBottomOnLayout;
- mAnimateNextSectionBoundsChange = sectionViewsChanged;
} else {
- mAnimateNextBackgroundTop = false;
- mAnimateNextBackgroundBottom = false;
- mAnimateNextSectionBoundsChange = false;
}
mAmbientState.setLastVisibleBackgroundChild(lastChild);
mAnimateBottomOnLayout = false;
@@ -3344,7 +3015,6 @@
setAnimationRunning(true);
mStateAnimator.startAnimationForEvents(mAnimationEvents, mGoToFullShadeDelay);
mAnimationEvents.clear();
- updateBackground();
updateViewShadows();
} else {
applyCurrentState();
@@ -3359,7 +3029,6 @@
generatePositionChangeEvents();
generateTopPaddingEvent();
generateActivateEvent();
- generateDimmedEvent();
generateHideSensitiveEvent();
generateGoToFullShadeEvent();
generateViewResizeEvent();
@@ -3577,14 +3246,6 @@
mEverythingNeedsAnimation = false;
}
- private void generateDimmedEvent() {
- if (mDimmedNeedsAnimation) {
- mAnimationEvents.add(
- new AnimationEvent(null, AnimationEvent.ANIMATION_TYPE_DIMMED));
- }
- mDimmedNeedsAnimation = false;
- }
-
private void generateHideSensitiveEvent() {
if (mHideSensitiveNeedsAnimation) {
mAnimationEvents.add(
@@ -4486,48 +4147,6 @@
mAnimationFinishedRunnables.clear();
}
- /**
- * See {@link AmbientState#setDimmed}.
- */
- void setDimmed(boolean dimmed, boolean animate) {
- dimmed &= onKeyguard();
- mAmbientState.setDimmed(dimmed);
- if (animate && mAnimationsEnabled) {
- mDimmedNeedsAnimation = true;
- mNeedsAnimation = true;
- animateDimmed(dimmed);
- } else {
- setDimAmount(dimmed ? 1.0f : 0.0f);
- }
- requestChildrenUpdate();
- }
-
- @VisibleForTesting
- boolean isDimmed() {
- return mAmbientState.isDimmed();
- }
-
- private void setDimAmount(float dimAmount) {
- mDimAmount = dimAmount;
- updateBackgroundDimming();
- }
-
- private void animateDimmed(boolean dimmed) {
- if (mDimAnimator != null) {
- mDimAnimator.cancel();
- }
- float target = dimmed ? 1.0f : 0.0f;
- if (target == mDimAmount) {
- return;
- }
- mDimAnimator = TimeAnimator.ofFloat(mDimAmount, target);
- mDimAnimator.setDuration(StackStateAnimator.ANIMATION_DURATION_DIMMED_ACTIVATED);
- mDimAnimator.setInterpolator(Interpolators.FAST_OUT_SLOW_IN);
- mDimAnimator.addListener(mDimEndListener);
- mDimAnimator.addUpdateListener(mDimUpdateListener);
- mDimAnimator.start();
- }
-
void updateSensitiveness(boolean animate, boolean hideSensitive) {
if (hideSensitive != mAmbientState.isHideSensitive()) {
int childCount = getChildCount();
@@ -4564,7 +4183,6 @@
runAnimationFinishedRunnables();
setAnimationRunning(false);
- updateBackground();
updateViewShadows();
}
@@ -4714,7 +4332,6 @@
invalidateOutline();
}
updateAlgorithmHeightAndPadding();
- updateBackgroundDimming();
requestChildrenUpdate();
updateOwnTranslationZ();
}
@@ -4747,21 +4364,6 @@
}
}
- private int getNotGoneIndex(View child) {
- int count = getChildCount();
- int notGoneIndex = 0;
- for (int i = 0; i < count; i++) {
- View v = getChildAt(i);
- if (child == v) {
- return notGoneIndex;
- }
- if (v.getVisibility() != View.GONE) {
- notGoneIndex++;
- }
- }
- return -1;
- }
-
/**
* Returns whether or not a History button is shown in the footer. If there is no footer, then
* this will return false.
@@ -5266,13 +4868,10 @@
void onStatePostChange(boolean fromShadeLocked) {
boolean onKeyguard = onKeyguard();
- mAmbientState.setDimmed(onKeyguard);
-
if (mHeadsUpAppearanceController != null) {
mHeadsUpAppearanceController.onStateChanged();
}
- setDimmed(onKeyguard, fromShadeLocked);
setExpandingEnabled(!onKeyguard);
if (!FooterViewRefactor.isEnabled()) {
updateFooter();
@@ -5676,7 +5275,6 @@
*/
public void setDozeAmount(float dozeAmount) {
mAmbientState.setDozeAmount(dozeAmount);
- updateContinuousBackgroundDrawing();
updateStackPosition();
requestChildrenUpdate();
}
@@ -5711,7 +5309,6 @@
view.setTranslationY(wakeUplocation);
}
}
- mDimmedNeedsAnimation = true;
}
void setAnimateBottomOnLayout(boolean animateBottomOnLayout) {
@@ -5763,7 +5360,6 @@
updateFirstAndLastBackgroundViews();
requestDisallowInterceptTouchEvent(true);
updateContinuousShadowDrawing();
- updateContinuousBackgroundDrawing();
requestChildrenUpdate();
}
@@ -5786,7 +5382,6 @@
* @param numHeadsUp the number of active alerting notifications.
*/
public void setNumHeadsUp(long numHeadsUp) {
- mNumHeadsUp = numHeadsUp;
mAmbientState.setHasHeadsUpEntries(numHeadsUp > 0);
}
@@ -6160,19 +5755,6 @@
mSpeedBumpIndexDirty = true;
}
- void updateContinuousBackgroundDrawing() {
- boolean continuousBackground = !mAmbientState.isFullyAwake()
- && mSwipeHelper.isSwiping();
- if (continuousBackground != mContinuousBackgroundUpdate) {
- mContinuousBackgroundUpdate = continuousBackground;
- if (continuousBackground) {
- getViewTreeObserver().addOnPreDrawListener(mBackgroundUpdater);
- } else {
- getViewTreeObserver().removeOnPreDrawListener(mBackgroundUpdater);
- }
- }
- }
-
private void resetAllSwipeState() {
Trace.beginSection("NSSL.resetAllSwipeState()");
mSwipeHelper.resetTouchState();
@@ -6259,7 +5841,6 @@
.animateHeight()
.animateTopInset()
.animateY()
- .animateDimmed()
.animateZ(),
// ANIMATION_TYPE_ACTIVATED_CHILD
@@ -6267,8 +5848,7 @@
.animateZ(),
// ANIMATION_TYPE_DIMMED
- new AnimationFilter()
- .animateDimmed(),
+ new AnimationFilter(),
// ANIMATION_TYPE_CHANGE_POSITION
new AnimationFilter()
@@ -6283,7 +5863,6 @@
.animateHeight()
.animateTopInset()
.animateY()
- .animateDimmed()
.animateZ()
.hasDelays(),
@@ -6339,7 +5918,6 @@
// ANIMATION_TYPE_EVERYTHING
new AnimationFilter()
.animateAlpha()
- .animateDimmed()
.animateHideSensitive()
.animateHeight()
.animateTopInset()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
index 7c13877..3bdd0e9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayoutController.java
@@ -875,8 +875,6 @@
mHeadsUpManager.setAnimationStateHandler(mView::setHeadsUpGoingAwayAnimationsAllowed);
mDynamicPrivacyController.addListener(mDynamicPrivacyControllerListener);
- mScrimController.setScrimBehindChangeRunnable(mView::updateBackgroundDimming);
-
mLockscreenShadeTransitionController.setStackScroller(this);
mLockscreenUserManager.addUserChangedListener(mLockscreenUserChangeListener);
@@ -1743,13 +1741,6 @@
}
/**
- * Set the dimmed state for all of the notification views.
- */
- public void setDimmed(boolean dimmed, boolean animate) {
- mView.setDimmed(dimmed, animate);
- }
-
- /**
* @return the inset during the full shade transition, that needs to be added to the position
* of the quick settings edge. This is relevant for media, that is transitioning
* from the keyguard host to the quick settings one.
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
index 1ef9a8f..9b1952b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java
@@ -369,13 +369,11 @@
/** Updates the dimmed and hiding sensitive states of the children. */
private void updateDimmedAndHideSensitive(AmbientState ambientState,
StackScrollAlgorithmState algorithmState) {
- boolean dimmed = ambientState.isDimmed();
boolean hideSensitive = ambientState.isHideSensitive();
int childCount = algorithmState.visibleChildren.size();
for (int i = 0; i < childCount; i++) {
ExpandableView child = algorithmState.visibleChildren.get(i);
ExpandableViewState childViewState = child.getViewState();
- childViewState.dimmed = dimmed;
childViewState.hideSensitive = hideSensitive;
}
}
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 d2e36b8..088f894 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java
@@ -207,8 +207,6 @@
private ScrimView mNotificationsScrim;
private ScrimView mScrimBehind;
- private Runnable mScrimBehindChangeRunnable;
-
private final KeyguardStateController mKeyguardStateController;
private final KeyguardUpdateMonitor mKeyguardUpdateMonitor;
private final DozeParameters mDozeParameters;
@@ -415,11 +413,6 @@
behindScrim.enableBottomEdgeConcave(mClipsQsScrim);
mNotificationsScrim.enableRoundedCorners(true);
- if (mScrimBehindChangeRunnable != null) {
- mScrimBehind.setChangeRunnable(mScrimBehindChangeRunnable, mMainExecutor);
- mScrimBehindChangeRunnable = null;
- }
-
final ScrimState[] states = ScrimState.values();
for (int i = 0; i < states.length; i++) {
states[i].init(mScrimInFront, mScrimBehind, mDozeParameters, mDockManager);
@@ -1542,16 +1535,6 @@
mScrimBehind.postOnAnimationDelayed(callback, 32 /* delayMillis */);
}
- public void setScrimBehindChangeRunnable(Runnable changeRunnable) {
- // TODO: remove this. This is necessary because of an order-of-operations limitation.
- // The fix is to move more of these class into @SysUISingleton.
- if (mScrimBehind == null) {
- mScrimBehindChangeRunnable = changeRunnable;
- } else {
- mScrimBehind.setChangeRunnable(changeRunnable, mMainExecutor);
- }
- }
-
private void updateThemeColors() {
if (mScrimBehind == null) return;
int background = Utils.getColorAttr(mScrimBehind.getContext(),
diff --git a/packages/SystemUI/src/com/android/systemui/util/kotlin/BatteryControllerExt.kt b/packages/SystemUI/src/com/android/systemui/util/kotlin/BatteryControllerExt.kt
index 0128eb7..80ccd64 100644
--- a/packages/SystemUI/src/com/android/systemui/util/kotlin/BatteryControllerExt.kt
+++ b/packages/SystemUI/src/com/android/systemui/util/kotlin/BatteryControllerExt.kt
@@ -22,6 +22,24 @@
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onStart
+fun BatteryController.isDevicePluggedIn(): Flow<Boolean> {
+ return conflatedCallbackFlow {
+ val batteryCallback =
+ object : BatteryController.BatteryStateChangeCallback {
+ override fun onBatteryLevelChanged(
+ level: Int,
+ pluggedIn: Boolean,
+ charging: Boolean
+ ) {
+ trySend(pluggedIn)
+ }
+ }
+ addCallback(batteryCallback)
+ awaitClose { removeCallback(batteryCallback) }
+ }
+ .onStart { emit(isPluggedIn) }
+}
+
fun BatteryController.isBatteryPowerSaveEnabled(): Flow<Boolean> {
return conflatedCallbackFlow {
val batteryCallback =
@@ -35,3 +53,35 @@
}
.onStart { emit(isPowerSave) }
}
+
+fun BatteryController.getBatteryLevel(): Flow<Int> {
+ return conflatedCallbackFlow {
+ val batteryCallback =
+ object : BatteryController.BatteryStateChangeCallback {
+ override fun onBatteryLevelChanged(
+ level: Int,
+ pluggedIn: Boolean,
+ charging: Boolean
+ ) {
+ trySend(level)
+ }
+ }
+ addCallback(batteryCallback)
+ awaitClose { removeCallback(batteryCallback) }
+ }
+ .onStart { emit(0) }
+}
+
+fun BatteryController.isExtremePowerSaverEnabled(): Flow<Boolean> {
+ return conflatedCallbackFlow {
+ val batteryCallback =
+ object : BatteryController.BatteryStateChangeCallback {
+ override fun onExtremeBatterySaverChanged(isExtreme: Boolean) {
+ trySend(isExtreme)
+ }
+ }
+ addCallback(batteryCallback)
+ awaitClose { removeCallback(batteryCallback) }
+ }
+ .onStart { emit(isExtremeSaverOn) }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 4045630..deec215 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -120,7 +120,7 @@
import com.android.systemui.haptics.slider.HapticSliderViewBinder;
import com.android.systemui.haptics.slider.SeekableSliderHapticPlugin;
import com.android.systemui.haptics.slider.SliderHapticFeedbackConfig;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.plugins.VolumeDialog;
import com.android.systemui.plugins.VolumeDialogController;
import com.android.systemui.plugins.VolumeDialogController.State;
@@ -265,7 +265,7 @@
private final Object mSafetyWarningLock = new Object();
private final Accessibility mAccessibility = new Accessibility();
private final ConfigurationController mConfigurationController;
- private final MediaOutputDialogFactory mMediaOutputDialogFactory;
+ private final MediaOutputDialogManager mMediaOutputDialogManager;
private final CsdWarningDialog.Factory mCsdWarningDialogFactory;
private final VolumePanelNavigationInteractor mVolumePanelNavigationInteractor;
private final VolumeNavigator mVolumeNavigator;
@@ -316,7 +316,7 @@
AccessibilityManagerWrapper accessibilityManagerWrapper,
DeviceProvisionedController deviceProvisionedController,
ConfigurationController configurationController,
- MediaOutputDialogFactory mediaOutputDialogFactory,
+ MediaOutputDialogManager mediaOutputDialogManager,
InteractionJankMonitor interactionJankMonitor,
VolumePanelNavigationInteractor volumePanelNavigationInteractor,
VolumeNavigator volumeNavigator,
@@ -340,7 +340,7 @@
mAccessibilityMgr = accessibilityManagerWrapper;
mDeviceProvisionedController = deviceProvisionedController;
mConfigurationController = configurationController;
- mMediaOutputDialogFactory = mediaOutputDialogFactory;
+ mMediaOutputDialogManager = mediaOutputDialogManager;
mCsdWarningDialogFactory = csdWarningDialogFactory;
mShowActiveStreamOnly = showActiveStreamOnly();
mHasSeenODICaptionsTooltip =
@@ -1199,7 +1199,7 @@
mSettingsIcon.setOnClickListener(v -> {
Events.writeEvent(Events.EVENT_SETTINGS_CLICK);
dismissH(DISMISS_REASON_SETTINGS_CLICKED);
- mMediaOutputDialogFactory.dismiss();
+ mMediaOutputDialogManager.dismiss();
mVolumeNavigator.openVolumePanel(
mVolumePanelNavigationInteractor.getVolumePanelRoute());
});
@@ -2082,6 +2082,9 @@
} else {
row.anim.cancel();
row.anim.setIntValues(progress, newProgress);
+ // The animator can't keep up with the volume changes so haptics need to be
+ // triggered here. This happens when the volume keys are continuously pressed.
+ row.deliverOnProgressChangedHaptics(false, newProgress);
}
row.animTargetProgress = newProgress;
row.anim.setDuration(UPDATE_ANIMATION_DURATION);
@@ -2486,10 +2489,10 @@
if (getActiveRow().equals(mRow)
&& mRow.slider.getVisibility() == VISIBLE
&& mRow.mHapticPlugin != null) {
- mRow.mHapticPlugin.onProgressChanged(seekBar, progress, fromUser);
- if (!fromUser) {
- // Consider a change from program as the volume key being continuously pressed
- mRow.mHapticPlugin.onKeyDown();
+ if (fromUser || mRow.animTargetProgress == progress) {
+ // Deliver user-generated slider changes immediately, or when the animation
+ // completes
+ mRow.deliverOnProgressChangedHaptics(fromUser, progress);
}
}
if (D.BUG) Log.d(TAG, AudioSystem.streamToString(mRow.stream)
@@ -2571,11 +2574,11 @@
/* progressInterpolatorFactor= */ 1f,
/* progressBasedDragMinScale= */ 0f,
/* progressBasedDragMaxScale= */ 0.2f,
- /* additionalVelocityMaxBump= */ 0.15f,
+ /* additionalVelocityMaxBump= */ 0.25f,
/* deltaMillisForDragInterval= */ 0f,
- /* deltaProgressForDragThreshold= */ 0.015f,
- /* numberOfLowTicks= */ 5,
- /* maxVelocityToScale= */ 300f,
+ /* deltaProgressForDragThreshold= */ 0.05f,
+ /* numberOfLowTicks= */ 4,
+ /* maxVelocityToScale= */ 200,
/* velocityAxis= */ MotionEvent.AXIS_Y,
/* upperBookendScale= */ 1f,
/* lowerBookendScale= */ 0.05f,
@@ -2642,6 +2645,14 @@
void removeHaptics() {
slider.setOnTouchListener(null);
}
+
+ void deliverOnProgressChangedHaptics(boolean fromUser, int progress) {
+ mHapticPlugin.onProgressChanged(slider, progress, fromUser);
+ if (!fromUser) {
+ // Consider a change from program as the volume key being continuously pressed
+ mHapticPlugin.onKeyDown();
+ }
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java b/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
index 64a5644..1f87ec8 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/dagger/VolumeModule.java
@@ -24,7 +24,7 @@
import com.android.internal.jank.InteractionJankMonitor;
import com.android.systemui.CoreStartable;
import com.android.systemui.dump.DumpManager;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.plugins.VolumeDialog;
import com.android.systemui.plugins.VolumeDialogController;
import com.android.systemui.statusbar.VibratorHelper;
@@ -100,7 +100,7 @@
AccessibilityManagerWrapper accessibilityManagerWrapper,
DeviceProvisionedController deviceProvisionedController,
ConfigurationController configurationController,
- MediaOutputDialogFactory mediaOutputDialogFactory,
+ MediaOutputDialogManager mediaOutputDialogManager,
InteractionJankMonitor interactionJankMonitor,
VolumePanelNavigationInteractor volumePanelNavigationInteractor,
VolumeNavigator volumeNavigator,
@@ -116,7 +116,7 @@
accessibilityManagerWrapper,
deviceProvisionedController,
configurationController,
- mediaOutputDialogFactory,
+ mediaOutputDialogManager,
interactionJankMonitor,
volumePanelNavigationInteractor,
volumeNavigator,
diff --git a/packages/SystemUI/src/com/android/systemui/volume/panel/component/mediaoutput/domain/interactor/MediaOutputActionsInteractor.kt b/packages/SystemUI/src/com/android/systemui/volume/panel/component/mediaoutput/domain/interactor/MediaOutputActionsInteractor.kt
index 2ab5998..cb16abe 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/panel/component/mediaoutput/domain/interactor/MediaOutputActionsInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/volume/panel/component/mediaoutput/domain/interactor/MediaOutputActionsInteractor.kt
@@ -20,7 +20,7 @@
import com.android.systemui.animation.DialogCuj
import com.android.systemui.animation.DialogTransitionAnimator
import com.android.systemui.animation.Expandable
-import com.android.systemui.media.dialog.MediaOutputDialogFactory
+import com.android.systemui.media.dialog.MediaOutputDialogManager
import com.android.systemui.volume.panel.component.mediaoutput.domain.model.MediaDeviceSession
import com.android.systemui.volume.panel.dagger.scope.VolumePanelScope
import javax.inject.Inject
@@ -30,20 +30,22 @@
class MediaOutputActionsInteractor
@Inject
constructor(
- private val mediaOutputDialogFactory: MediaOutputDialogFactory,
+ private val mediaOutputDialogManager: MediaOutputDialogManager,
) {
fun onBarClick(session: MediaDeviceSession, expandable: Expandable) {
when (session) {
is MediaDeviceSession.Active -> {
- mediaOutputDialogFactory.createWithController(
+ mediaOutputDialogManager.createAndShowWithController(
session.packageName,
false,
expandable.dialogController()
)
}
is MediaDeviceSession.Inactive -> {
- mediaOutputDialogFactory.createDialogForSystemRouting(expandable.dialogController())
+ mediaOutputDialogManager.createAndShowForSystemRouting(
+ expandable.dialogController()
+ )
}
else -> {
/* do nothing */
@@ -56,7 +58,7 @@
cuj =
DialogCuj(
InteractionJankMonitor.CUJ_SHADE_DIALOG_OPEN,
- MediaOutputDialogFactory.INTERACTION_JANK_TAG
+ MediaOutputDialogManager.INTERACTION_JANK_TAG
)
)
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
index f07932c..e3be3822 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/animation/AnimatorTestRuleOrderTest.kt
@@ -19,6 +19,7 @@
import android.testing.AndroidTestingRunner
import android.testing.TestableLooper.RunWithLooper
import androidx.core.animation.doOnEnd
+import androidx.test.filters.FlakyTest
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.util.doOnEnd
@@ -30,6 +31,7 @@
@RunWith(AndroidTestingRunner::class)
@SmallTest
@RunWithLooper
+@FlakyTest(bugId = 302149604)
class AnimatorTestRuleOrderTest : SysuiTestCase() {
@get:Rule val animatorTestRule = AnimatorTestRule(this)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
index 043dcaa..3c073d5 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/battery/BatteryMeterViewTest.kt
@@ -193,6 +193,34 @@
}
@Test
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun modeEstimate_batteryPercentView_isNotNull_flagOn() {
+ mBatteryMeterView.onBatteryLevelChanged(15, false)
+ mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ESTIMATE)
+ mBatteryMeterView.setBatteryEstimateFetcher(Fetcher())
+
+ mBatteryMeterView.updatePercentText()
+
+ // New battery icon only uses the percent view for the estimate text
+ assertThat(mBatteryMeterView.batteryPercentView).isNotNull()
+ // Make sure that it was added to the view hierarchy
+ assertThat(mBatteryMeterView.batteryPercentView.parent).isNotNull()
+ }
+
+ @Test
+ @EnableFlags(FLAG_NEW_STATUS_BAR_ICONS)
+ fun modePercent_batteryPercentView_isNull_flagOn() {
+ mBatteryMeterView.onBatteryLevelChanged(15, false)
+ mBatteryMeterView.setPercentShowMode(BatteryMeterView.MODE_ON)
+ mBatteryMeterView.setBatteryEstimateFetcher(Fetcher())
+
+ mBatteryMeterView.updatePercentText()
+
+ // New battery icon only uses the percent view for the estimate text
+ assertThat(mBatteryMeterView.batteryPercentView).isNull()
+ }
+
+ @Test
fun contentDescription_manyUpdates_alwaysUpdated() {
// BatteryDefender
mBatteryMeterView.onBatteryLevelChanged(90, false)
diff --git a/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogDelegateTest.java b/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogDelegateTest.java
index 7a18477..a569cee 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogDelegateTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/bluetooth/BroadcastDialogDelegateTest.java
@@ -42,7 +42,7 @@
import com.android.systemui.SysuiTestCase;
import com.android.systemui.animation.DialogTransitionAnimator;
import com.android.systemui.broadcast.BroadcastSender;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.model.SysUiState;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.phone.SystemUIDialog;
@@ -77,7 +77,8 @@
@Mock SysUiState mSysUiState;
@Mock
DialogTransitionAnimator mDialogTransitionAnimator;
- @Mock MediaOutputDialogFactory mMediaOutputDialogFactory;
+ @Mock
+ MediaOutputDialogManager mMediaOutputDialogManager;
private SystemUIDialog mDialog;
private TextView mTitle;
private TextView mSubTitle;
@@ -96,7 +97,7 @@
mBroadcastDialogDelegate = new BroadcastDialogDelegate(
mContext,
- mMediaOutputDialogFactory,
+ mMediaOutputDialogManager,
mLocalBluetoothManager,
new UiEventLoggerFake(),
mFakeExecutor,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/controller/MediaControlPanelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/controller/MediaControlPanelTest.kt
index 2f92afa..83e4d31 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/controller/MediaControlPanelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/controls/ui/controller/MediaControlPanelTest.kt
@@ -84,7 +84,7 @@
import com.android.systemui.media.controls.ui.viewmodel.SeekBarViewModel
import com.android.systemui.media.controls.util.MediaFlags
import com.android.systemui.media.controls.util.MediaUiEventLogger
-import com.android.systemui.media.dialog.MediaOutputDialogFactory
+import com.android.systemui.media.dialog.MediaOutputDialogManager
import com.android.systemui.monet.ColorScheme
import com.android.systemui.monet.Style
import com.android.systemui.plugins.ActivityStarter
@@ -160,7 +160,7 @@
@Mock private lateinit var mediaDataManager: MediaDataManager
@Mock private lateinit var expandedSet: ConstraintSet
@Mock private lateinit var collapsedSet: ConstraintSet
- @Mock private lateinit var mediaOutputDialogFactory: MediaOutputDialogFactory
+ @Mock private lateinit var mediaOutputDialogManager: MediaOutputDialogManager
@Mock private lateinit var mediaCarouselController: MediaCarouselController
@Mock private lateinit var falsingManager: FalsingManager
@Mock private lateinit var transitionParent: ViewGroup
@@ -266,7 +266,7 @@
mediaViewController,
seekBarViewModel,
Lazy { mediaDataManager },
- mediaOutputDialogFactory,
+ mediaOutputDialogManager,
mediaCarouselController,
falsingManager,
clock,
diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogReceiverTest.java b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogReceiverTest.java
index 0879884..83def8e4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogReceiverTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/media/dialog/MediaOutputDialogReceiverTest.java
@@ -42,16 +42,16 @@
private MediaOutputDialogReceiver mMediaOutputDialogReceiver;
- private final MediaOutputDialogFactory mMockMediaOutputDialogFactory =
- mock(MediaOutputDialogFactory.class);
+ private final MediaOutputDialogManager mMockMediaOutputDialogManager =
+ mock(MediaOutputDialogManager.class);
- private final MediaOutputBroadcastDialogFactory mMockMediaOutputBroadcastDialogFactory =
- mock(MediaOutputBroadcastDialogFactory.class);
+ private final MediaOutputBroadcastDialogManager mMockMediaOutputBroadcastDialogManager =
+ mock(MediaOutputBroadcastDialogManager.class);
@Before
public void setup() {
- mMediaOutputDialogReceiver = new MediaOutputDialogReceiver(mMockMediaOutputDialogFactory,
- mMockMediaOutputBroadcastDialogFactory);
+ mMediaOutputDialogReceiver = new MediaOutputDialogReceiver(mMockMediaOutputDialogManager,
+ mMockMediaOutputBroadcastDialogManager);
}
@Test
@@ -60,9 +60,10 @@
intent.putExtra(MediaOutputConstants.EXTRA_PACKAGE_NAME, getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, times(1))
- .create(getContext().getPackageName(), false, null);
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, times(1))
+ .createAndShow(getContext().getPackageName(), false, null);
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -71,8 +72,9 @@
intent.putExtra("Wrong Package Name Key", getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -80,8 +82,9 @@
Intent intent = new Intent(MediaOutputConstants.ACTION_LAUNCH_MEDIA_OUTPUT_DIALOG);
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -92,8 +95,9 @@
intent.putExtra(MediaOutputConstants.EXTRA_PACKAGE_NAME, getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -104,9 +108,9 @@
intent.putExtra(MediaOutputConstants.EXTRA_PACKAGE_NAME, getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, times(1))
- .create(getContext().getPackageName(), true, null);
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, times(1))
+ .createAndShow(getContext().getPackageName(), true, null);
}
@Test
@@ -117,8 +121,9 @@
intent.putExtra("Wrong Package Name Key", getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -128,8 +133,9 @@
MediaOutputConstants.ACTION_LAUNCH_MEDIA_OUTPUT_BROADCAST_DIALOG);
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -139,8 +145,9 @@
intent.putExtra(MediaOutputConstants.EXTRA_PACKAGE_NAME, getContext().getPackageName());
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
@Test
@@ -148,7 +155,8 @@
Intent intent = new Intent("UnKnown Action");
mMediaOutputDialogReceiver.onReceive(getContext(), intent);
- verify(mMockMediaOutputDialogFactory, never()).create(any(), anyBoolean(), any());
- verify(mMockMediaOutputBroadcastDialogFactory, never()).create(any(), anyBoolean(), any());
+ verify(mMockMediaOutputDialogManager, never()).createAndShow(any(), anyBoolean(), any());
+ verify(mMockMediaOutputBroadcastDialogManager, never())
+ .createAndShow(any(), anyBoolean(), any());
}
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicChildBindControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicChildBindControllerTest.java
index a59ba07..eb692eb 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicChildBindControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/DynamicChildBindControllerTest.java
@@ -32,9 +32,9 @@
import android.view.LayoutInflater;
import android.view.View;
-import com.android.systemui.res.R;
import com.android.systemui.SysuiTestCase;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
+import com.android.systemui.res.R;
import com.android.systemui.statusbar.notification.collection.NotificationEntry;
import com.android.systemui.statusbar.notification.collection.NotificationEntryBuilder;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
@@ -51,6 +51,7 @@
import java.util.List;
import java.util.Map;
+
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -65,7 +66,7 @@
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- mDependency.injectMockDependency(MediaOutputDialogFactory.class);
+ mDependency.injectMockDependency(MediaOutputDialogManager.class);
allowTestableLooperAsMainThread();
when(mBindStage.getStageParams(any())).thenReturn(new RowContentBindParams());
mDynamicChildBindController =
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 fb49499f..718f998 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
@@ -58,7 +58,7 @@
import com.android.systemui.flags.FakeFeatureFlags;
import com.android.systemui.flags.FeatureFlags;
import com.android.systemui.media.controls.util.MediaFeatureFlag;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.NotificationMediaManager;
@@ -159,7 +159,7 @@
dependency.injectTestDependency(FeatureFlags.class, mFeatureFlags);
dependency.injectMockDependency(NotificationMediaManager.class);
dependency.injectMockDependency(NotificationShadeWindowController.class);
- dependency.injectMockDependency(MediaOutputDialogFactory.class);
+ dependency.injectMockDependency(MediaOutputDialogManager.class);
mMockLogger = mock(ExpandableNotificationRowLogger.class);
mStatusBarStateController = mock(StatusBarStateController.class);
mKeyguardBypassController = mock(KeyguardBypassController.class);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
index 3d75288..4715b33 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/stack/AmbientStateTest.kt
@@ -57,39 +57,6 @@
)
}
- // region isDimmed
- @Test
- fun isDimmed_whenTrue_shouldReturnTrue() {
- sut.arrangeDimmed(true)
-
- assertThat(sut.isDimmed).isTrue()
- }
-
- @Test
- fun isDimmed_whenFalse_shouldReturnFalse() {
- sut.arrangeDimmed(false)
-
- assertThat(sut.isDimmed).isFalse()
- }
-
- @Test
- fun isDimmed_whenDozeAmountIsEmpty_shouldReturnTrue() {
- sut.arrangeDimmed(true)
- sut.dozeAmount = 0f
-
- assertThat(sut.isDimmed).isTrue()
- }
-
- @Test
- fun isDimmed_whenPulseExpandingIsFalse_shouldReturnTrue() {
- sut.arrangeDimmed(true)
- sut.arrangePulseExpanding(false)
- sut.dozeAmount = 1f // arrangePulseExpanding changes dozeAmount
-
- assertThat(sut.isDimmed).isTrue()
- }
- // endregion
-
// region pulseHeight
@Test
fun pulseHeight_whenValueChanged_shouldCallListener() {
@@ -383,12 +350,6 @@
}
// region Arrange helper methods.
-private fun AmbientState.arrangeDimmed(value: Boolean) {
- isDimmed = value
- dozeAmount = if (value) 0f else 1f
- arrangePulseExpanding(!value)
-}
-
private fun AmbientState.arrangePulseExpanding(value: Boolean) {
if (value) {
dozeAmount = 1f
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 f326cea..28dfbbb 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
@@ -307,14 +307,6 @@
}
@Test
- public void testNotDimmedOnKeyguard() {
- when(mBarState.getState()).thenReturn(StatusBarState.SHADE);
- mStackScroller.setDimmed(true /* dimmed */, false /* animate */);
- mStackScroller.setDimmed(true /* dimmed */, true /* animate */);
- assertFalse(mStackScroller.isDimmed());
- }
-
- @Test
public void updateEmptyView_dndSuppressing() {
when(mEmptyShadeView.willBeGone()).thenReturn(true);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 3a6324d..d0261ae 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -69,7 +69,7 @@
import com.android.systemui.SysuiTestCase;
import com.android.systemui.animation.AnimatorTestRule;
import com.android.systemui.dump.DumpManager;
-import com.android.systemui.media.dialog.MediaOutputDialogFactory;
+import com.android.systemui.media.dialog.MediaOutputDialogManager;
import com.android.systemui.plugins.VolumeDialogController;
import com.android.systemui.plugins.VolumeDialogController.State;
import com.android.systemui.res.R;
@@ -130,7 +130,7 @@
@Mock
DeviceProvisionedController mDeviceProvisionedController;
@Mock
- MediaOutputDialogFactory mMediaOutputDialogFactory;
+ MediaOutputDialogManager mMediaOutputDialogManager;
@Mock
InteractionJankMonitor mInteractionJankMonitor;
@Mock
@@ -196,7 +196,7 @@
mAccessibilityMgr,
mDeviceProvisionedController,
mConfigurationController,
- mMediaOutputDialogFactory,
+ mMediaOutputDialogManager,
mInteractionJankMonitor,
mVolumePanelNavigationInteractor,
mVolumeNavigator,
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/media/MediaKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/media/MediaKosmos.kt
index e1b1966..e788669 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/media/MediaKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/media/MediaKosmos.kt
@@ -17,7 +17,7 @@
package com.android.systemui.media
import com.android.systemui.kosmos.Kosmos
-import com.android.systemui.media.dialog.MediaOutputDialogFactory
+import com.android.systemui.media.dialog.MediaOutputDialogManager
import com.android.systemui.util.mockito.mock
-var Kosmos.mediaOutputDialogFactory: MediaOutputDialogFactory by Kosmos.Fixture { mock {} }
+var Kosmos.mediaOutputDialogManager: MediaOutputDialogManager by Kosmos.Fixture { mock {} }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/battery/BatterySaverTileKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/battery/BatterySaverTileKosmos.kt
new file mode 100644
index 0000000..a2d1d93
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/battery/BatterySaverTileKosmos.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.battery
+
+import com.android.systemui.battery.BatterySaverModule
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.qs.qsEventLogger
+
+val Kosmos.qsBatterySaverTileConfig by
+ Kosmos.Fixture { BatterySaverModule.provideBatterySaverTileConfig(qsEventLogger) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/internet/InternetTileKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/internet/InternetTileKosmos.kt
new file mode 100644
index 0000000..6772ba3
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/qs/tiles/impl/internet/InternetTileKosmos.kt
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles.impl.internet
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.qs.qsEventLogger
+import com.android.systemui.statusbar.connectivity.ConnectivityModule
+
+val Kosmos.qsInternetTileConfig by
+ Kosmos.Fixture { ConnectivityModule.provideInternetTileConfig(qsEventLogger) }
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/utils/leaks/FakeBatteryController.java b/packages/SystemUI/tests/utils/src/com/android/systemui/utils/leaks/FakeBatteryController.java
index 5ae033c..d798b3b 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/utils/leaks/FakeBatteryController.java
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/utils/leaks/FakeBatteryController.java
@@ -30,6 +30,8 @@
private boolean mIsAodPowerSave = false;
private boolean mWirelessCharging;
private boolean mPowerSaveMode = false;
+ private boolean mIsPluggedIn = false;
+ private boolean mIsExtremePowerSave = false;
private final List<BatteryStateChangeCallback> mCallbacks = new ArrayList<>();
@@ -64,8 +66,35 @@
}
@Override
+ public boolean isExtremeSaverOn() {
+ return mIsExtremePowerSave;
+ }
+
+ /**
+ * Note: this does not affect the regular power saver. Triggers all callbacks, only on change.
+ */
+ public void setExtremeSaverOn(Boolean extremePowerSave) {
+ if (extremePowerSave == mIsExtremePowerSave) return;
+
+ mIsExtremePowerSave = extremePowerSave;
+ for (BatteryStateChangeCallback callback: mCallbacks) {
+ callback.onExtremeBatterySaverChanged(extremePowerSave);
+ }
+ }
+
+ @Override
public boolean isPluggedIn() {
- return false;
+ return mIsPluggedIn;
+ }
+
+ /**
+ * Notifies all registered callbacks
+ */
+ public void setPluggedIn(boolean pluggedIn) {
+ mIsPluggedIn = pluggedIn;
+ for (BatteryStateChangeCallback cb : mCallbacks) {
+ cb.onBatteryLevelChanged(0, pluggedIn, false);
+ }
}
@Override
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/volume/MediaOutputKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/volume/MediaOutputKosmos.kt
index a3b1a0e..3938f77 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/volume/MediaOutputKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/volume/MediaOutputKosmos.kt
@@ -24,7 +24,7 @@
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.testCase
import com.android.systemui.kosmos.testScope
-import com.android.systemui.media.mediaOutputDialogFactory
+import com.android.systemui.media.mediaOutputDialogManager
import com.android.systemui.util.mockito.any
import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.whenever
@@ -42,7 +42,7 @@
Kosmos.Fixture { FakeLocalMediaRepositoryFactory { localMediaRepository } }
val Kosmos.mediaOutputActionsInteractor by
- Kosmos.Fixture { MediaOutputActionsInteractor(mediaOutputDialogFactory) }
+ Kosmos.Fixture { MediaOutputActionsInteractor(mediaOutputDialogManager) }
val Kosmos.mediaControllerRepository by Kosmos.Fixture { FakeMediaControllerRepository() }
val Kosmos.mediaOutputInteractor by
Kosmos.Fixture {
diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
index 6d731b2..b1672ed 100644
--- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
+++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceImpl.java
@@ -210,7 +210,7 @@
mActivityListener.onTopActivityChanged(displayId, topActivity,
UserHandle.USER_NULL);
} catch (RemoteException e) {
- Slog.w(TAG, "Unable to call mActivityListener", e);
+ Slog.w(TAG, "Unable to call mActivityListener for display: " + displayId, e);
}
}
@@ -220,7 +220,7 @@
try {
mActivityListener.onTopActivityChanged(displayId, topActivity, userId);
} catch (RemoteException e) {
- Slog.w(TAG, "Unable to call mActivityListener", e);
+ Slog.w(TAG, "Unable to call mActivityListener for display: " + displayId, e);
}
}
@@ -229,7 +229,7 @@
try {
mActivityListener.onDisplayEmpty(displayId);
} catch (RemoteException e) {
- Slog.w(TAG, "Unable to call mActivityListener", e);
+ Slog.w(TAG, "Unable to call mActivityListener for display: " + displayId, e);
}
}
};
@@ -1213,7 +1213,7 @@
mContext.startActivityAsUser(
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK),
ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle(),
- mContext.getUser());
+ UserHandle.SYSTEM);
}
private void onSecureWindowShown(int displayId, int uid) {
diff --git a/services/core/java/com/android/server/clipboard/ArcClipboardMonitor.java b/services/core/java/com/android/server/clipboard/ArcClipboardMonitor.java
new file mode 100644
index 0000000..413020e
--- /dev/null
+++ b/services/core/java/com/android/server/clipboard/ArcClipboardMonitor.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.clipboard;
+
+import android.annotation.Nullable;
+import android.content.ClipData;
+
+import com.android.server.LocalServices;
+
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+
+public class ArcClipboardMonitor implements Consumer<ClipData> {
+ private static final String TAG = "ArcClipboardMonitor";
+
+ public interface ArcClipboardBridge {
+ /**
+ * Called when a clipboard content is updated.
+ */
+ void onPrimaryClipChanged(ClipData data);
+
+ /**
+ * Passes the callback to set a new clipboard content with a uid.
+ */
+ void setHandler(BiConsumer<ClipData, Integer> setAndroidClipboard);
+ }
+
+ private ArcClipboardBridge mBridge;
+ private BiConsumer<ClipData, Integer> mAndroidClipboardSetter;
+
+ ArcClipboardMonitor(final BiConsumer<ClipData, Integer> setAndroidClipboard) {
+ mAndroidClipboardSetter = setAndroidClipboard;
+ LocalServices.addService(ArcClipboardMonitor.class, this);
+ }
+
+ @Override
+ public void accept(final @Nullable ClipData clip) {
+ if (mBridge != null) {
+ mBridge.onPrimaryClipChanged(clip);
+ }
+ }
+
+ /**
+ * Sets the other end of the clipboard bridge.
+ */
+ public void setClipboardBridge(ArcClipboardBridge bridge) {
+ mBridge = bridge;
+ mBridge.setHandler(mAndroidClipboardSetter);
+ }
+}
diff --git a/services/core/java/com/android/server/clipboard/ClipboardService.java b/services/core/java/com/android/server/clipboard/ClipboardService.java
index 49f6070..4c3020f 100644
--- a/services/core/java/com/android/server/clipboard/ClipboardService.java
+++ b/services/core/java/com/android/server/clipboard/ClipboardService.java
@@ -151,7 +151,7 @@
private final ContentCaptureManagerInternal mContentCaptureInternal;
private final AutofillManagerInternal mAutofillInternal;
private final IBinder mPermissionOwner;
- private final Consumer<ClipData> mEmulatorClipboardMonitor;
+ private final Consumer<ClipData> mClipboardMonitor;
private final Handler mWorkerHandler;
@GuardedBy("mLock")
@@ -192,7 +192,7 @@
final IBinder permOwner = mUgmInternal.newUriPermissionOwner("clipboard");
mPermissionOwner = permOwner;
if (Build.IS_EMULATOR) {
- mEmulatorClipboardMonitor = new EmulatorClipboardMonitor((clip) -> {
+ mClipboardMonitor = new EmulatorClipboardMonitor((clip) -> {
synchronized (mLock) {
Clipboard clipboard = getClipboardLocked(0, DEVICE_ID_DEFAULT);
if (clipboard != null) {
@@ -201,8 +201,12 @@
}
}
});
+ } else if (Build.IS_ARC) {
+ mClipboardMonitor = new ArcClipboardMonitor((clip, uid) -> {
+ setPrimaryClipInternal(clip, uid);
+ });
} else {
- mEmulatorClipboardMonitor = (clip) -> {};
+ mClipboardMonitor = (clip) -> {};
}
updateConfig();
@@ -937,7 +941,7 @@
private void setPrimaryClipInternalLocked(
@Nullable ClipData clip, int uid, int deviceId, @Nullable String sourcePackage) {
if (deviceId == DEVICE_ID_DEFAULT) {
- mEmulatorClipboardMonitor.accept(clip);
+ mClipboardMonitor.accept(clip);
}
final int userId = UserHandle.getUserId(uid);
diff --git a/services/core/java/com/android/server/display/DisplayOffloadSessionImpl.java b/services/core/java/com/android/server/display/DisplayOffloadSessionImpl.java
index a43f93a..91e560e 100644
--- a/services/core/java/com/android/server/display/DisplayOffloadSessionImpl.java
+++ b/services/core/java/com/android/server/display/DisplayOffloadSessionImpl.java
@@ -20,7 +20,6 @@
import android.annotation.Nullable;
import android.hardware.display.DisplayManagerInternal;
-import android.os.PowerManager;
import android.os.Trace;
/**
@@ -110,7 +109,6 @@
try {
mDisplayOffloader.stopOffload();
mIsActive = false;
- mDisplayPowerController.setBrightnessFromOffload(PowerManager.BRIGHTNESS_INVALID_FLOAT);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_POWER);
}
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index 2010aca..7f014f6 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -375,7 +375,8 @@
// information.
// At the time of this writing, this value is changed within updatePowerState() only, which is
// limited to the thread used by DisplayControllerHandler.
- private final BrightnessReason mBrightnessReason = new BrightnessReason();
+ @VisibleForTesting
+ final BrightnessReason mBrightnessReason = new BrightnessReason();
private final BrightnessReason mBrightnessReasonTemp = new BrightnessReason();
// Brightness animation ramp rates in brightness units per second
@@ -1379,7 +1380,7 @@
// Switch to doze auto-brightness mode if needed
if (mFlags.areAutoBrightnessModesEnabled() && mAutomaticBrightnessController != null
&& !mAutomaticBrightnessController.isInIdleMode()) {
- mAutomaticBrightnessController.switchMode(mPowerRequest.policy == POLICY_DOZE
+ mAutomaticBrightnessController.switchMode(Display.isDozeState(state)
? AUTO_BRIGHTNESS_MODE_DOZE : AUTO_BRIGHTNESS_MODE_DEFAULT);
}
@@ -1434,7 +1435,9 @@
float currentBrightnessSetting = mDisplayBrightnessController.getCurrentBrightness();
// Apply auto-brightness.
int brightnessAdjustmentFlags = 0;
- if (Float.isNaN(brightnessState)) {
+ // AutomaticBrightnessStrategy has higher priority than OffloadBrightnessStrategy
+ if (Float.isNaN(brightnessState)
+ || mBrightnessReasonTemp.getReason() == BrightnessReason.REASON_OFFLOAD) {
if (mAutomaticBrightnessStrategy.isAutoBrightnessEnabled()) {
brightnessState = mAutomaticBrightnessStrategy.getAutomaticScreenBrightness(
mTempBrightnessEvent);
@@ -1455,8 +1458,11 @@
if (mScreenOffBrightnessSensorController != null) {
mScreenOffBrightnessSensorController.setLightSensorEnabled(false);
}
+ setBrightnessFromOffload(PowerManager.BRIGHTNESS_INVALID_FLOAT);
} else {
mAutomaticBrightnessStrategy.setAutoBrightnessApplied(false);
+ // Restore the lower-priority brightness strategy
+ brightnessState = displayBrightnessState.getBrightness();
}
}
} else {
@@ -3020,9 +3026,10 @@
setDwbcLoggingEnabled(msg.arg1);
break;
case MSG_SET_BRIGHTNESS_FROM_OFFLOAD:
- mDisplayBrightnessController.setBrightnessFromOffload(
- Float.intBitsToFloat(msg.arg1));
- updatePowerState();
+ if (mDisplayBrightnessController.setBrightnessFromOffload(
+ Float.intBitsToFloat(msg.arg1))) {
+ updatePowerState();
+ }
break;
}
}
diff --git a/services/core/java/com/android/server/display/brightness/DisplayBrightnessController.java b/services/core/java/com/android/server/display/brightness/DisplayBrightnessController.java
index f6d02db..34d53be 100644
--- a/services/core/java/com/android/server/display/brightness/DisplayBrightnessController.java
+++ b/services/core/java/com/android/server/display/brightness/DisplayBrightnessController.java
@@ -26,6 +26,7 @@
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.display.BrightnessSynchronizer;
import com.android.server.display.AutomaticBrightnessController;
import com.android.server.display.BrightnessMappingStrategy;
import com.android.server.display.BrightnessSetting;
@@ -175,14 +176,19 @@
/**
* Sets the brightness from the offload session.
+ * @return Whether the offload brightness has changed
*/
- public void setBrightnessFromOffload(float brightness) {
+ public boolean setBrightnessFromOffload(float brightness) {
synchronized (mLock) {
- if (mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy() != null) {
+ if (mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy() != null
+ && !BrightnessSynchronizer.floatEquals(mDisplayBrightnessStrategySelector
+ .getOffloadBrightnessStrategy().getOffloadScreenBrightness(), brightness)) {
mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy()
.setOffloadScreenBrightness(brightness);
+ return true;
}
}
+ return false;
}
/**
diff --git a/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java b/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
index 8e84450..71cc872 100644
--- a/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
+++ b/services/core/java/com/android/server/display/brightness/DisplayBrightnessStrategySelector.java
@@ -133,7 +133,8 @@
} else if (BrightnessUtils.isValidBrightnessValue(
mTemporaryBrightnessStrategy.getTemporaryScreenBrightness())) {
displayBrightnessStrategy = mTemporaryBrightnessStrategy;
- } else if (mOffloadBrightnessStrategy != null && BrightnessUtils.isValidBrightnessValue(
+ } else if (mAutomaticBrightnessStrategy.shouldUseAutoBrightness()
+ && mOffloadBrightnessStrategy != null && BrightnessUtils.isValidBrightnessValue(
mOffloadBrightnessStrategy.getOffloadScreenBrightness())) {
displayBrightnessStrategy = mOffloadBrightnessStrategy;
}
diff --git a/services/core/java/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategy.java b/services/core/java/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategy.java
index d1ca49b..8b54b22 100644
--- a/services/core/java/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategy.java
+++ b/services/core/java/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategy.java
@@ -108,7 +108,6 @@
mIsAutoBrightnessEnabled = shouldUseAutoBrightness()
&& (targetDisplayState == Display.STATE_ON || autoBrightnessEnabledInDoze)
&& brightnessReason != BrightnessReason.REASON_OVERRIDE
- && brightnessReason != BrightnessReason.REASON_OFFLOAD
&& mAutomaticBrightnessController != null;
mAutoBrightnessDisabledDueToDisplayOff = shouldUseAutoBrightness()
&& !(targetDisplayState == Display.STATE_ON || autoBrightnessEnabledInDoze);
diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubClientBroker.java b/services/core/java/com/android/server/location/contexthub/ContextHubClientBroker.java
index fc99471..0ca4808 100644
--- a/services/core/java/com/android/server/location/contexthub/ContextHubClientBroker.java
+++ b/services/core/java/com/android/server/location/contexthub/ContextHubClientBroker.java
@@ -449,7 +449,7 @@
}
/**
- * Sends a reliable message rom this client to a nanoapp.
+ * Sends a reliable message from this client to a nanoapp.
*
* @param message the message to send
* @param transactionCallback The callback to use to confirm the delivery of the message for
@@ -473,6 +473,12 @@
@Nullable IContextHubTransactionCallback transactionCallback) {
ContextHubServiceUtil.checkPermissions(mContext);
+ // Clear the isReliable and messageSequenceNumber fields.
+ // These will be set to true and a real value if the message
+ // is reliable.
+ message.setIsReliable(false);
+ message.setMessageSequenceNumber(0);
+
@ContextHubTransaction.Result int result;
if (isRegistered()) {
int authState = mMessageChannelNanoappIdMap.getOrDefault(
@@ -485,7 +491,9 @@
// Return a bland error code for apps targeting old SDKs since they wouldn't be able
// to use an error code added in S.
return ContextHubTransaction.RESULT_FAILED_UNKNOWN;
- } else if (authState == AUTHORIZATION_UNKNOWN) {
+ }
+
+ if (authState == AUTHORIZATION_UNKNOWN) {
// Only check permissions the first time a nanoapp is queried since nanoapp
// permissions don't currently change at runtime. If the host permission changes
// later, that'll be checked by onOpChanged.
diff --git a/services/core/java/com/android/server/notification/ManagedServices.java b/services/core/java/com/android/server/notification/ManagedServices.java
index f645eaa..3ecc58e 100644
--- a/services/core/java/com/android/server/notification/ManagedServices.java
+++ b/services/core/java/com/android/server/notification/ManagedServices.java
@@ -942,6 +942,23 @@
return false;
}
+ protected boolean isPackageOrComponentAllowedWithPermission(ComponentName component,
+ int userId) {
+ if (!(isPackageOrComponentAllowed(component.flattenToString(), userId)
+ || isPackageOrComponentAllowed(component.getPackageName(), userId))) {
+ return false;
+ }
+ return componentHasBindPermission(component, userId);
+ }
+
+ private boolean componentHasBindPermission(ComponentName component, int userId) {
+ ServiceInfo info = getServiceInfo(component, userId);
+ if (info == null) {
+ return false;
+ }
+ return mConfig.bindPermission.equals(info.permission);
+ }
+
boolean isPackageOrComponentUserSet(String pkgOrComponent, int userId) {
synchronized (mApproved) {
ArraySet<String> services = mUserSetServices.get(userId);
@@ -1003,6 +1020,7 @@
for (int uid : uidList) {
if (isPackageAllowed(pkgName, UserHandle.getUserId(uid))) {
anyServicesInvolved = true;
+ trimApprovedListsForInvalidServices(pkgName, UserHandle.getUserId(uid));
}
}
}
@@ -1135,8 +1153,7 @@
synchronized (mMutex) {
if (enabled) {
- if (isPackageOrComponentAllowed(component.flattenToString(), userId)
- || isPackageOrComponentAllowed(component.getPackageName(), userId)) {
+ if (isPackageOrComponentAllowedWithPermission(component, userId)) {
registerServiceLocked(component, userId);
} else {
Slog.d(TAG, component + " no longer has permission to be bound");
@@ -1270,6 +1287,33 @@
return removed;
}
+ private void trimApprovedListsForInvalidServices(String packageName, int userId) {
+ synchronized (mApproved) {
+ final ArrayMap<Boolean, ArraySet<String>> approvedByType = mApproved.get(userId);
+ if (approvedByType == null) {
+ return;
+ }
+ for (int i = 0; i < approvedByType.size(); i++) {
+ final ArraySet<String> approved = approvedByType.valueAt(i);
+ for (int j = approved.size() - 1; j >= 0; j--) {
+ final String approvedPackageOrComponent = approved.valueAt(j);
+ if (TextUtils.equals(getPackageName(approvedPackageOrComponent), packageName)) {
+ final ComponentName component = ComponentName.unflattenFromString(
+ approvedPackageOrComponent);
+ if (component != null && !componentHasBindPermission(component, userId)) {
+ approved.removeAt(j);
+ if (DEBUG) {
+ Slog.v(TAG, "Removing " + approvedPackageOrComponent
+ + " from approved list; no bind permission found "
+ + mConfig.bindPermission);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
protected String getPackageName(String packageOrComponent) {
final ComponentName component = ComponentName.unflattenFromString(packageOrComponent);
if (component != null) {
@@ -1519,8 +1563,7 @@
void reregisterService(final ComponentName cn, final int userId) {
// If rebinding a package that died, ensure it still has permission
// after the rebind delay
- if (isPackageOrComponentAllowed(cn.getPackageName(), userId)
- || isPackageOrComponentAllowed(cn.flattenToString(), userId)) {
+ if (isPackageOrComponentAllowedWithPermission(cn, userId)) {
registerService(cn, userId);
}
}
diff --git a/services/core/java/com/android/server/ondeviceintelligence/OnDeviceIntelligenceManagerService.java b/services/core/java/com/android/server/ondeviceintelligence/OnDeviceIntelligenceManagerService.java
index 0abe50f..71800ef 100644
--- a/services/core/java/com/android/server/ondeviceintelligence/OnDeviceIntelligenceManagerService.java
+++ b/services/core/java/com/android/server/ondeviceintelligence/OnDeviceIntelligenceManagerService.java
@@ -32,12 +32,13 @@
import android.app.ondeviceintelligence.IProcessingSignal;
import android.app.ondeviceintelligence.IResponseCallback;
import android.app.ondeviceintelligence.IStreamingResponseCallback;
-import android.app.ondeviceintelligence.ITokenCountCallback;
+import android.app.ondeviceintelligence.ITokenInfoCallback;
import android.app.ondeviceintelligence.OnDeviceIntelligenceManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
+import android.os.Binder;
import android.os.Bundle;
import android.os.ICancellationSignal;
import android.os.ParcelFileDescriptor;
@@ -47,11 +48,12 @@
import android.os.UserHandle;
import android.provider.DeviceConfig;
import android.service.ondeviceintelligence.IOnDeviceIntelligenceService;
-import android.service.ondeviceintelligence.IOnDeviceTrustedInferenceService;
+import android.service.ondeviceintelligence.IOnDeviceSandboxedInferenceService;
import android.service.ondeviceintelligence.IRemoteProcessingService;
import android.service.ondeviceintelligence.IRemoteStorageService;
import android.service.ondeviceintelligence.IProcessingUpdateStatusCallback;
import android.service.ondeviceintelligence.OnDeviceIntelligenceService;
+import android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService;
import android.text.TextUtils;
import android.util.Slog;
@@ -69,7 +71,7 @@
* This is the system service for handling calls on the
* {@link android.app.ondeviceintelligence.OnDeviceIntelligenceManager}. This
* service holds connection references to the underlying remote services i.e. the isolated service
- * {@link OnDeviceTrustedInferenceService} and a regular
+ * {@link OnDeviceSandboxedInferenceService} and a regular
* service counter part {@link OnDeviceIntelligenceService}.
*
* Note: Both the remote services run under the SYSTEM user, as we cannot have separate instance of
@@ -90,7 +92,7 @@
protected final Object mLock = new Object();
- private RemoteOnDeviceTrustedInferenceService mRemoteInferenceService;
+ private RemoteOnDeviceSandboxedInferenceService mRemoteInferenceService;
private RemoteOnDeviceIntelligenceService mRemoteOnDeviceIntelligenceService;
volatile boolean mIsServiceEnabled;
@@ -165,7 +167,7 @@
}
ensureRemoteIntelligenceServiceInitialized();
mRemoteOnDeviceIntelligenceService.post(
- service -> service.getFeature(id, featureCallback));
+ service -> service.getFeature(Binder.getCallingUid(), id, featureCallback));
}
@Override
@@ -185,7 +187,7 @@
}
ensureRemoteIntelligenceServiceInitialized();
mRemoteOnDeviceIntelligenceService.post(
- service -> service.listFeatures(listFeaturesCallback));
+ service -> service.listFeatures(Binder.getCallingUid(), listFeaturesCallback));
}
@Override
@@ -207,7 +209,8 @@
}
ensureRemoteIntelligenceServiceInitialized();
mRemoteOnDeviceIntelligenceService.post(
- service -> service.getFeatureDetails(feature, featureDetailsCallback));
+ service -> service.getFeatureDetails(Binder.getCallingUid(), feature,
+ featureDetailsCallback));
}
@Override
@@ -227,33 +230,35 @@
}
ensureRemoteIntelligenceServiceInitialized();
mRemoteOnDeviceIntelligenceService.post(
- service -> service.requestFeatureDownload(feature, cancellationSignal,
+ service -> service.requestFeatureDownload(Binder.getCallingUid(), feature,
+ cancellationSignal,
downloadCallback));
}
@Override
- public void requestTokenCount(Feature feature,
+ public void requestTokenInfo(Feature feature,
Content request, ICancellationSignal cancellationSignal,
- ITokenCountCallback tokenCountcallback) throws RemoteException {
+ ITokenInfoCallback tokenInfoCallback) throws RemoteException {
Slog.i(TAG, "OnDeviceIntelligenceManagerInternal prepareFeatureProcessing");
Objects.requireNonNull(feature);
Objects.requireNonNull(request);
- Objects.requireNonNull(tokenCountcallback);
+ Objects.requireNonNull(tokenInfoCallback);
mContext.enforceCallingOrSelfPermission(
Manifest.permission.USE_ON_DEVICE_INTELLIGENCE, TAG);
if (!mIsServiceEnabled) {
Slog.w(TAG, "Service not available");
- tokenCountcallback.onFailure(
+ tokenInfoCallback.onFailure(
OnDeviceIntelligenceManager.OnDeviceIntelligenceManagerException.ON_DEVICE_INTELLIGENCE_SERVICE_UNAVAILABLE,
"OnDeviceIntelligenceManagerService is unavailable",
new PersistableBundle());
}
- ensureRemoteTrustedInferenceServiceInitialized();
+ ensureRemoteInferenceServiceInitialized();
mRemoteInferenceService.post(
- service -> service.requestTokenCount(feature, request, cancellationSignal,
- tokenCountcallback));
+ service -> service.requestTokenInfo(Binder.getCallingUid(), feature, request,
+ cancellationSignal,
+ tokenInfoCallback));
}
@Override
@@ -267,7 +272,6 @@
Slog.i(TAG, "OnDeviceIntelligenceManagerInternal processRequest");
Objects.requireNonNull(feature);
Objects.requireNonNull(responseCallback);
- Objects.requireNonNull(request);
mContext.enforceCallingOrSelfPermission(
Manifest.permission.USE_ON_DEVICE_INTELLIGENCE, TAG);
if (!mIsServiceEnabled) {
@@ -277,9 +281,10 @@
"OnDeviceIntelligenceManagerService is unavailable",
new PersistableBundle());
}
- ensureRemoteTrustedInferenceServiceInitialized();
+ ensureRemoteInferenceServiceInitialized();
mRemoteInferenceService.post(
- service -> service.processRequest(feature, request, requestType,
+ service -> service.processRequest(Binder.getCallingUid(), feature, request,
+ requestType,
cancellationSignal, processingSignal,
responseCallback));
}
@@ -293,7 +298,6 @@
IStreamingResponseCallback streamingCallback) throws RemoteException {
Slog.i(TAG, "OnDeviceIntelligenceManagerInternal processRequestStreaming");
Objects.requireNonNull(feature);
- Objects.requireNonNull(request);
Objects.requireNonNull(streamingCallback);
mContext.enforceCallingOrSelfPermission(
Manifest.permission.USE_ON_DEVICE_INTELLIGENCE, TAG);
@@ -304,9 +308,10 @@
"OnDeviceIntelligenceManagerService is unavailable",
new PersistableBundle());
}
- ensureRemoteTrustedInferenceServiceInitialized();
+ ensureRemoteInferenceServiceInitialized();
mRemoteInferenceService.post(
- service -> service.processRequestStreaming(feature, request, requestType,
+ service -> service.processRequestStreaming(Binder.getCallingUid(), feature,
+ request, requestType,
cancellationSignal, processingSignal,
streamingCallback));
}
@@ -346,7 +351,7 @@
Bundle processingState,
IProcessingUpdateStatusCallback callback) {
try {
- ensureRemoteTrustedInferenceServiceInitialized();
+ ensureRemoteInferenceServiceInitialized();
mRemoteInferenceService.post(
service -> service.updateProcessingState(
processingState, callback));
@@ -363,22 +368,24 @@
};
}
- private void ensureRemoteTrustedInferenceServiceInitialized() throws RemoteException {
+ private void ensureRemoteInferenceServiceInitialized() throws RemoteException {
synchronized (mLock) {
if (mRemoteInferenceService == null) {
String serviceName = mContext.getResources().getString(
- R.string.config_defaultOnDeviceTrustedInferenceService);
+ R.string.config_defaultOnDeviceSandboxedInferenceService);
validateService(serviceName, true);
- mRemoteInferenceService = new RemoteOnDeviceTrustedInferenceService(mContext,
+ mRemoteInferenceService = new RemoteOnDeviceSandboxedInferenceService(mContext,
ComponentName.unflattenFromString(serviceName),
UserHandle.SYSTEM.getIdentifier());
mRemoteInferenceService.setServiceLifecycleCallbacks(
new ServiceConnector.ServiceLifecycleCallbacks<>() {
@Override
public void onConnected(
- @NonNull IOnDeviceTrustedInferenceService service) {
+ @NonNull IOnDeviceSandboxedInferenceService service) {
try {
ensureRemoteIntelligenceServiceInitialized();
+ mRemoteOnDeviceIntelligenceService.post(
+ intelligenceService -> intelligenceService.notifyInferenceServiceConnected());
service.registerRemoteStorageService(
getIRemoteStorageService());
} catch (RemoteException ex) {
@@ -433,7 +440,7 @@
}
checkServiceRequiresPermission(serviceInfo,
- Manifest.permission.BIND_ON_DEVICE_TRUSTED_SERVICE);
+ Manifest.permission.BIND_ON_DEVICE_SANDBOXED_INFERENCE_SERVICE);
if (!isIsolatedService(serviceInfo)) {
throw new SecurityException(
"Call required an isolated service, but the configured service: "
diff --git a/services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceTrustedInferenceService.java b/services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceSandboxedInferenceService.java
similarity index 73%
rename from services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceTrustedInferenceService.java
rename to services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceSandboxedInferenceService.java
index cc8e788..69ba1d2 100644
--- a/services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceTrustedInferenceService.java
+++ b/services/core/java/com/android/server/ondeviceintelligence/RemoteOnDeviceSandboxedInferenceService.java
@@ -22,18 +22,18 @@
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
-import android.service.ondeviceintelligence.IOnDeviceTrustedInferenceService;
-import android.service.ondeviceintelligence.OnDeviceTrustedInferenceService;
+import android.service.ondeviceintelligence.IOnDeviceSandboxedInferenceService;
+import android.service.ondeviceintelligence.OnDeviceSandboxedInferenceService;
import com.android.internal.infra.ServiceConnector;
/**
- * Manages the connection to the remote on-device trusted inference service. Also, handles unbinding
+ * Manages the connection to the remote on-device sand boxed inference service. Also, handles unbinding
* logic set by the service implementation via a SecureSettings flag.
*/
-public class RemoteOnDeviceTrustedInferenceService extends
- ServiceConnector.Impl<IOnDeviceTrustedInferenceService> {
+public class RemoteOnDeviceSandboxedInferenceService extends
+ ServiceConnector.Impl<IOnDeviceSandboxedInferenceService> {
/**
* Creates an instance of {@link ServiceConnector}
*
@@ -43,12 +43,12 @@
* {@link Context#unbindService unbinding}
* @param userId to be used for {@link Context#bindServiceAsUser binding}
*/
- RemoteOnDeviceTrustedInferenceService(Context context, ComponentName serviceName,
+ RemoteOnDeviceSandboxedInferenceService(Context context, ComponentName serviceName,
int userId) {
super(context, new Intent(
- OnDeviceTrustedInferenceService.SERVICE_INTERFACE).setComponent(serviceName),
+ OnDeviceSandboxedInferenceService.SERVICE_INTERFACE).setComponent(serviceName),
BIND_FOREGROUND_SERVICE | BIND_INCLUDE_CAPABILITIES, userId,
- IOnDeviceTrustedInferenceService.Stub::asInterface);
+ IOnDeviceSandboxedInferenceService.Stub::asInterface);
// Bind right away
connect();
diff --git a/services/core/java/com/android/server/pm/PackageArchiver.java b/services/core/java/com/android/server/pm/PackageArchiver.java
index ef8453d..29de26e 100644
--- a/services/core/java/com/android/server/pm/PackageArchiver.java
+++ b/services/core/java/com/android/server/pm/PackageArchiver.java
@@ -31,6 +31,7 @@
import static android.content.pm.PackageManager.DELETE_ALL_USERS;
import static android.content.pm.PackageManager.DELETE_ARCHIVE;
import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
+import static android.content.pm.PackageManager.INSTALL_UNARCHIVE;
import static android.content.pm.PackageManager.INSTALL_UNARCHIVE_DRAFT;
import static android.graphics.drawable.AdaptiveIconDrawable.getExtraInsetFraction;
import static android.os.PowerExemptionManager.REASON_PACKAGE_UNARCHIVE;
@@ -754,8 +755,9 @@
int draftSessionId;
try {
- draftSessionId = Binder.withCleanCallingIdentity(() ->
- createDraftSession(packageName, installerPackage, statusReceiver, userId));
+ draftSessionId = Binder.withCleanCallingIdentity(
+ () -> createDraftSession(packageName, installerPackage, callerPackageName,
+ statusReceiver, userId));
} catch (RuntimeException e) {
if (e.getCause() instanceof IOException) {
throw ExceptionUtils.wrap((IOException) e.getCause());
@@ -795,11 +797,18 @@
}
private int createDraftSession(String packageName, String installerPackage,
+ String callerPackageName,
IntentSender statusReceiver, int userId) throws IOException {
PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
sessionParams.setAppPackageName(packageName);
- sessionParams.installFlags = INSTALL_UNARCHIVE_DRAFT;
+ sessionParams.setAppLabel(
+ mContext.getString(com.android.internal.R.string.unarchival_session_app_label));
+ sessionParams.setAppIcon(
+ getArchivedAppIcon(packageName, UserHandle.of(userId), callerPackageName));
+ // To make sure SessionInfo::isUnarchival returns true for draft sessions,
+ // INSTALL_UNARCHIVE is also set.
+ sessionParams.installFlags = (INSTALL_UNARCHIVE_DRAFT | INSTALL_UNARCHIVE);
int installerUid = mPm.snapshotComputer().getPackageUid(installerPackage, 0, userId);
// Handles case of repeated unarchival calls for the same package.
diff --git a/services/core/java/com/android/server/power/ThermalManagerService.java b/services/core/java/com/android/server/power/ThermalManagerService.java
index 24d7acd..5360788 100644
--- a/services/core/java/com/android/server/power/ThermalManagerService.java
+++ b/services/core/java/com/android/server/power/ThermalManagerService.java
@@ -700,6 +700,8 @@
return runOverrideStatus();
case "reset":
return runReset();
+ case "headroom":
+ return runHeadroom();
default:
return handleDefaultCommands(cmd);
}
@@ -862,6 +864,36 @@
}
}
+ private int runHeadroom() {
+ final long token = Binder.clearCallingIdentity();
+ try {
+ final PrintWriter pw = getOutPrintWriter();
+ int forecastSecs;
+ try {
+ forecastSecs = Integer.parseInt(getNextArgRequired());
+ } catch (RuntimeException ex) {
+ pw.println("Error: " + ex);
+ return -1;
+ }
+ if (!mHalReady.get()) {
+ pw.println("Error: thermal HAL is not ready");
+ return -1;
+ }
+
+ if (forecastSecs < MIN_FORECAST_SEC || forecastSecs > MAX_FORECAST_SEC) {
+ pw.println(
+ "Error: forecast second input should be in range [" + MIN_FORECAST_SEC
+ + "," + MAX_FORECAST_SEC + "]");
+ return -1;
+ }
+ float headroom = mTemperatureWatcher.getForecast(forecastSecs);
+ pw.println("Headroom in " + forecastSecs + " seconds: " + headroom);
+ return 0;
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
@Override
public void onHelp() {
final PrintWriter pw = getOutPrintWriter();
@@ -877,6 +909,9 @@
pw.println(" status code is defined in android.os.Temperature.");
pw.println(" reset");
pw.println(" unlocks the thermal status of the device.");
+ pw.println(" headroom FORECAST_SECONDS");
+ pw.println(" gets the thermal headroom forecast in specified seconds, from ["
+ + MIN_FORECAST_SEC + "," + MAX_FORECAST_SEC + "].");
pw.println();
}
}
diff --git a/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java b/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java
index ffce50e..79adcb4 100644
--- a/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java
+++ b/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java
@@ -349,7 +349,6 @@
}
}
- userState.mIAppMap.clear();
userState.mAdServiceMap = adServiceMap;
}
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayOffloadSessionImplTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayOffloadSessionImplTest.java
index fbb14c3..4409051 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/DisplayOffloadSessionImplTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayOffloadSessionImplTest.java
@@ -26,7 +26,6 @@
import static org.mockito.Mockito.when;
import android.hardware.display.DisplayManagerInternal;
-import android.os.PowerManager;
import org.junit.Before;
import org.junit.Test;
@@ -66,8 +65,6 @@
mSession.stopOffload();
assertFalse(mSession.isActive());
- verify(mDisplayPowerController).setBrightnessFromOffload(
- PowerManager.BRIGHTNESS_INVALID_FLOAT);
// An inactive session shouldn't be stopped again
mSession.stopOffload();
diff --git a/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java b/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
index e9315c8..14d8a9c 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/DisplayPowerControllerTest.java
@@ -22,6 +22,7 @@
import static com.android.server.display.AutomaticBrightnessController.AUTO_BRIGHTNESS_MODE_DOZE;
import static com.android.server.display.AutomaticBrightnessController.AUTO_BRIGHTNESS_MODE_IDLE;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
@@ -77,6 +78,7 @@
import com.android.server.am.BatteryStatsService;
import com.android.server.display.RampAnimator.DualRampAnimator;
import com.android.server.display.brightness.BrightnessEvent;
+import com.android.server.display.brightness.BrightnessReason;
import com.android.server.display.brightness.clamper.BrightnessClamperController;
import com.android.server.display.brightness.clamper.HdrClamper;
import com.android.server.display.color.ColorDisplayService;
@@ -1559,6 +1561,43 @@
verify(mHolder.animator).animateTo(eq(brightness), anyFloat(),
eq(BRIGHTNESS_RAMP_RATE_FAST_INCREASE), eq(false));
+ assertEquals(BrightnessReason.REASON_OFFLOAD, mHolder.dpc.mBrightnessReason.getReason());
+ }
+
+ @Test
+ public void testBrightness_AutomaticHigherPriorityThanOffload() {
+ when(mDisplayManagerFlagsMock.isDisplayOffloadEnabled()).thenReturn(true);
+ mHolder = createDisplayPowerController(DISPLAY_ID, UNIQUE_ID);
+ Settings.System.putInt(mContext.getContentResolver(),
+ Settings.System.SCREEN_BRIGHTNESS_MODE,
+ Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
+ float brightness = 0.34f;
+ when(mHolder.displayPowerState.getColorFadeLevel()).thenReturn(1.0f);
+ when(mHolder.displayPowerState.getScreenState()).thenReturn(Display.STATE_ON);
+ when(mHolder.automaticBrightnessController.getAutomaticScreenBrightness(
+ any(BrightnessEvent.class))).thenReturn(PowerManager.BRIGHTNESS_INVALID_FLOAT);
+ mHolder.dpc.setDisplayOffloadSession(mDisplayOffloadSession);
+
+ mHolder.dpc.setBrightnessFromOffload(brightness);
+ DisplayPowerRequest dpr = new DisplayPowerRequest();
+ mHolder.dpc.requestPowerState(dpr, /* waitForNegativeProximity= */ false);
+ advanceTime(1); // Run updatePowerState
+
+ verify(mHolder.animator).animateTo(eq(brightness), anyFloat(),
+ eq(BRIGHTNESS_RAMP_RATE_FAST_INCREASE), eq(false));
+ assertEquals(BrightnessReason.REASON_OFFLOAD, mHolder.dpc.mBrightnessReason.getReason());
+
+ // Now automatic brightness becomes available
+ brightness = 0.22f;
+ when(mHolder.automaticBrightnessController.getAutomaticScreenBrightness(
+ any(BrightnessEvent.class))).thenReturn(brightness);
+
+ mHolder.dpc.updateBrightness();
+ advanceTime(1); // Run updatePowerState
+
+ verify(mHolder.animator).animateTo(eq(brightness), anyFloat(),
+ eq(BRIGHTNESS_RAMP_RATE_FAST_INCREASE), eq(false));
+ assertEquals(BrightnessReason.REASON_AUTOMATIC, mHolder.dpc.mBrightnessReason.getReason());
}
@Test
diff --git a/services/tests/displayservicetests/src/com/android/server/display/LocalDisplayAdapterTest.java b/services/tests/displayservicetests/src/com/android/server/display/LocalDisplayAdapterTest.java
index b99ecf3..14de527 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/LocalDisplayAdapterTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/LocalDisplayAdapterTest.java
@@ -46,7 +46,6 @@
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
-import android.os.PowerManager;
import android.view.Display;
import android.view.DisplayAddress;
import android.view.SurfaceControl;
@@ -1229,8 +1228,6 @@
verify(mDisplayOffloader).stopOffload();
assertFalse(mDisplayOffloadSession.isActive());
- verify(mMockedDisplayPowerController).setBrightnessFromOffload(
- PowerManager.BRIGHTNESS_INVALID_FLOAT);
}
private void initDisplayOffloadSession() {
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessControllerTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessControllerTest.java
index 289d54b..9b6cc0a 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessControllerTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessControllerTest.java
@@ -393,7 +393,31 @@
OffloadBrightnessStrategy offloadBrightnessStrategy = mock(OffloadBrightnessStrategy.class);
when(mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy()).thenReturn(
offloadBrightnessStrategy);
- mDisplayBrightnessController.setBrightnessFromOffload(brightness);
+ boolean brightnessUpdated =
+ mDisplayBrightnessController.setBrightnessFromOffload(brightness);
verify(offloadBrightnessStrategy).setOffloadScreenBrightness(brightness);
+ assertTrue(brightnessUpdated);
+ }
+
+ @Test
+ public void setBrightnessFromOffload_OffloadStrategyNull() {
+ float brightness = 0.4f;
+ when(mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy()).thenReturn(null);
+ boolean brightnessUpdated =
+ mDisplayBrightnessController.setBrightnessFromOffload(brightness);
+ assertFalse(brightnessUpdated);
+ }
+
+ @Test
+ public void setBrightnessFromOffload_BrightnessUnchanged() {
+ float brightness = 0.4f;
+ OffloadBrightnessStrategy offloadBrightnessStrategy = mock(OffloadBrightnessStrategy.class);
+ when(offloadBrightnessStrategy.getOffloadScreenBrightness()).thenReturn(brightness);
+ when(mDisplayBrightnessStrategySelector.getOffloadBrightnessStrategy()).thenReturn(
+ offloadBrightnessStrategy);
+ boolean brightnessUpdated =
+ mDisplayBrightnessController.setBrightnessFromOffload(brightness);
+ verify(offloadBrightnessStrategy, never()).setOffloadScreenBrightness(brightness);
+ assertFalse(brightnessUpdated);
}
}
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessStrategySelectorTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessStrategySelectorTest.java
index 1c681ce..0e89d83 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessStrategySelectorTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/DisplayBrightnessStrategySelectorTest.java
@@ -247,6 +247,7 @@
displayPowerRequest.screenBrightnessOverride = Float.NaN;
when(mFollowerBrightnessStrategy.getBrightnessToFollow()).thenReturn(Float.NaN);
when(mTemporaryBrightnessStrategy.getTemporaryScreenBrightness()).thenReturn(Float.NaN);
+ when(mAutomaticBrightnessStrategy.shouldUseAutoBrightness()).thenReturn(true);
when(mOffloadBrightnessStrategy.getOffloadScreenBrightness()).thenReturn(0.3f);
assertEquals(mOffloadBrightnessStrategy, mDisplayBrightnessStrategySelector.selectStrategy(
displayPowerRequest, Display.STATE_ON));
diff --git a/services/tests/displayservicetests/src/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategyTest.java b/services/tests/displayservicetests/src/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategyTest.java
index ba462e3..a5dc668 100644
--- a/services/tests/displayservicetests/src/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategyTest.java
+++ b/services/tests/displayservicetests/src/com/android/server/display/brightness/strategy/AutomaticBrightnessStrategyTest.java
@@ -188,29 +188,6 @@
}
@Test
- public void testAutoBrightnessState_BrightnessReasonIsOffload() {
- mAutomaticBrightnessStrategy.setUseAutoBrightness(true);
- int targetDisplayState = Display.STATE_ON;
- boolean allowAutoBrightnessWhileDozing = false;
- int brightnessReason = BrightnessReason.REASON_OFFLOAD;
- int policy = DisplayManagerInternal.DisplayPowerRequest.POLICY_BRIGHT;
- float lastUserSetBrightness = 0.2f;
- boolean userSetBrightnessChanged = true;
- mAutomaticBrightnessStrategy.updatePendingAutoBrightnessAdjustments();
- mAutomaticBrightnessStrategy.setAutoBrightnessState(targetDisplayState,
- allowAutoBrightnessWhileDozing, brightnessReason, policy, lastUserSetBrightness,
- userSetBrightnessChanged);
- verify(mAutomaticBrightnessController)
- .configure(AutomaticBrightnessController.AUTO_BRIGHTNESS_DISABLED,
- mBrightnessConfiguration,
- lastUserSetBrightness,
- userSetBrightnessChanged, 0.5f,
- false, policy, true);
- assertFalse(mAutomaticBrightnessStrategy.isAutoBrightnessEnabled());
- assertFalse(mAutomaticBrightnessStrategy.isAutoBrightnessDisabledDueToDisplayOff());
- }
-
- @Test
public void testAutoBrightnessState_DisplayIsInDoze_ConfigDoesAllow() {
mAutomaticBrightnessStrategy.setUseAutoBrightness(true);
int targetDisplayState = Display.STATE_DOZE;
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
index 4dded1d..05b6c90 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ManagedServicesTest.java
@@ -37,6 +37,7 @@
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -885,6 +886,7 @@
return true;
});
+ mockServiceInfoWithMetaData(List.of(cn), service, new ArrayMap<>());
service.addApprovedList("a", 0, true);
service.reregisterService(cn, 0);
@@ -915,6 +917,7 @@
return true;
});
+ mockServiceInfoWithMetaData(List.of(cn), service, new ArrayMap<>());
service.addApprovedList("a", 0, false);
service.reregisterService(cn, 0);
@@ -945,6 +948,7 @@
return true;
});
+ mockServiceInfoWithMetaData(List.of(cn), service, new ArrayMap<>());
service.addApprovedList("a/a", 0, true);
service.reregisterService(cn, 0);
@@ -975,6 +979,7 @@
return true;
});
+ mockServiceInfoWithMetaData(List.of(cn), service, new ArrayMap<>());
service.addApprovedList("a/a", 0, false);
service.reregisterService(cn, 0);
@@ -1152,6 +1157,58 @@
}
@Test
+ public void testUpgradeAppNoPermissionNoRebind() throws Exception {
+ Context context = spy(getContext());
+ doReturn(true).when(context).bindServiceAsUser(any(), any(), anyInt(), any());
+
+ ManagedServices service = new TestManagedServices(context, mLock, mUserProfiles,
+ mIpm,
+ APPROVAL_BY_COMPONENT);
+
+ List<String> packages = new ArrayList<>();
+ packages.add("package");
+ addExpectedServices(service, packages, 0);
+
+ final ComponentName unapprovedComponent = ComponentName.unflattenFromString("package/C1");
+ final ComponentName approvedComponent = ComponentName.unflattenFromString("package/C2");
+
+ // Both components are approved initially
+ mExpectedPrimaryComponentNames.clear();
+ mExpectedPrimaryPackages.clear();
+ mExpectedPrimaryComponentNames.put(0, "package/C1:package/C2");
+ mExpectedSecondaryComponentNames.clear();
+ mExpectedSecondaryPackages.clear();
+
+ loadXml(service);
+
+ //Component package/C1 loses bind permission
+ when(mIpm.getServiceInfo(any(), anyLong(), anyInt())).thenAnswer(
+ (Answer<ServiceInfo>) invocation -> {
+ ComponentName invocationCn = invocation.getArgument(0);
+ if (invocationCn != null) {
+ ServiceInfo serviceInfo = new ServiceInfo();
+ serviceInfo.packageName = invocationCn.getPackageName();
+ serviceInfo.name = invocationCn.getClassName();
+ if (invocationCn.equals(unapprovedComponent)) {
+ serviceInfo.permission = "none";
+ } else {
+ serviceInfo.permission = service.getConfig().bindPermission;
+ }
+ serviceInfo.metaData = null;
+ return serviceInfo;
+ }
+ return null;
+ }
+ );
+
+ // Trigger package update
+ service.onPackagesChanged(false, new String[]{"package"}, new int[]{0});
+
+ assertFalse(service.isComponentEnabledForCurrentProfiles(unapprovedComponent));
+ assertTrue(service.isComponentEnabledForCurrentProfiles(approvedComponent));
+ }
+
+ @Test
public void testSetPackageOrComponentEnabled() throws Exception {
for (int approvalLevel : new int[] {APPROVAL_BY_COMPONENT, APPROVAL_BY_PACKAGE}) {
ManagedServices service = new TestManagedServices(getContext(), mLock, mUserProfiles,
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index 78fb570..bfc47fd 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -324,7 +324,11 @@
when(mPermissionHelper.getNotificationPermissionValues(USER_SYSTEM))
.thenReturn(appPermissions);
- when(mUserProfiles.getCurrentProfileIds()).thenReturn(IntArray.wrap(new int[] {0}));
+ IntArray currentProfileIds = IntArray.wrap(new int[]{0});
+ if (UserManager.isHeadlessSystemUserMode()) {
+ currentProfileIds.add(UserHandle.getUserId(UID_HEADLESS));
+ }
+ when(mUserProfiles.getCurrentProfileIds()).thenReturn(currentProfileIds);
mHelper = new PreferencesHelper(getContext(), mPm, mHandler, mMockZenModeHelper,
mPermissionHelper, mPermissionManager, mLogger, mAppOpsManager, mUserProfiles,
diff --git a/services/tests/vibrator/src/com/android/server/vibrator/GroupedAggregatedLogRecordsTest.java b/services/tests/vibrator/src/com/android/server/vibrator/GroupedAggregatedLogRecordsTest.java
index 038f1db..54ab367 100644
--- a/services/tests/vibrator/src/com/android/server/vibrator/GroupedAggregatedLogRecordsTest.java
+++ b/services/tests/vibrator/src/com/android/server/vibrator/GroupedAggregatedLogRecordsTest.java
@@ -135,7 +135,7 @@
AggregatedLogRecord<TestSingleLogRecord> droppedRecord =
records.add(createRecord(GROUP_1, KEY_2, createTime++));
assertThat(droppedRecord).isNotNull();
- assertThat(droppedRecord.getLatest()).isEqualTo(mTestRecords.getFirst());
+ assertThat(droppedRecord.getLatest()).isEqualTo(mTestRecords.get(0));
dumpRecords(records);
assertGroupHeadersWrittenOnce(records, GROUP_1);
@@ -155,7 +155,7 @@
AggregatedLogRecord<TestSingleLogRecord> droppedRecord =
records.add(createRecord(GROUP_1, KEY_1, createTime + AGGREGATION_TIME_LIMIT));
assertThat(droppedRecord).isNotNull();
- assertThat(droppedRecord.getLatest()).isEqualTo(mTestRecords.getFirst());
+ assertThat(droppedRecord.getLatest()).isEqualTo(mTestRecords.get(0));
dumpRecords(records);
assertGroupHeadersWrittenOnce(records, GROUP_1);
diff --git a/telephony/java/android/telephony/ims/ImsService.java b/telephony/java/android/telephony/ims/ImsService.java
index b84ff29..12e04c2 100644
--- a/telephony/java/android/telephony/ims/ImsService.java
+++ b/telephony/java/android/telephony/ims/ImsService.java
@@ -195,7 +195,8 @@
// whether or not ImsFeature.FEATURE_EMERGENCY_MMTEL feature is set and should
// not be set by users of ImsService.
CAPABILITY_SIP_DELEGATE_CREATION,
- CAPABILITY_TERMINAL_BASED_CALL_WAITING
+ CAPABILITY_TERMINAL_BASED_CALL_WAITING,
+ CAPABILITY_SUPPORTS_SIMULTANEOUS_CALLING
})
@Retention(RetentionPolicy.SOURCE)
public @interface ImsServiceCapability {}
@@ -206,7 +207,9 @@
*/
private static final Map<Long, String> CAPABILITIES_LOG_MAP = Map.of(
CAPABILITY_EMERGENCY_OVER_MMTEL, "EMERGENCY_OVER_MMTEL",
- CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION");
+ CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION",
+ CAPABILITY_TERMINAL_BASED_CALL_WAITING, "TERMINAL_BASED_CALL_WAITING",
+ CAPABILITY_SUPPORTS_SIMULTANEOUS_CALLING, "SIMULTANEOUS_CALLING");
/**
* The intent that must be defined as an intent-filter in the AndroidManifest of the ImsService.
diff --git a/tests/FlickerTests/Android.bp b/tests/FlickerTests/Android.bp
index 1d71f95..d658d59 100644
--- a/tests/FlickerTests/Android.bp
+++ b/tests/FlickerTests/Android.bp
@@ -63,17 +63,20 @@
],
}
-android_library_import {
- name: "wm-flicker-window-extensions_nodeps",
- aars: ["libs/window-extensions-release.aar"],
- sdk_version: "current",
-}
-
java_library {
name: "wm-flicker-window-extensions",
sdk_version: "current",
static_libs: [
- "wm-flicker-window-extensions_nodeps",
+ "androidx.window.extensions_extensions-nodeps",
+ ],
+ installable: false,
+}
+
+java_library {
+ name: "wm-flicker-window-extensions-core",
+ sdk_version: "current",
+ static_libs: [
+ "androidx.window.extensions.core_core-nodeps",
],
installable: false,
}
diff --git a/tests/FlickerTests/libs/window-extensions-release.aar b/tests/FlickerTests/libs/window-extensions-release.aar
deleted file mode 100644
index 918e514..0000000
--- a/tests/FlickerTests/libs/window-extensions-release.aar
+++ /dev/null
Binary files differ
diff --git a/tests/Internal/src/com/android/internal/protolog/LegacyProtoLogImplTest.java b/tests/Internal/src/com/android/internal/protolog/LegacyProtoLogImplTest.java
index a64996c..d9a4c26 100644
--- a/tests/Internal/src/com/android/internal/protolog/LegacyProtoLogImplTest.java
+++ b/tests/Internal/src/com/android/internal/protolog/LegacyProtoLogImplTest.java
@@ -59,6 +59,7 @@
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.LinkedList;
+import java.util.TreeMap;
/**
* Test class for {@link ProtoLogImpl}.
@@ -89,7 +90,7 @@
//noinspection ResultOfMethodCallIgnored
mFile.delete();
mProtoLog = new LegacyProtoLogImpl(mFile, mViewerConfigFilename,
- 1024 * 1024, mReader, 1024);
+ 1024 * 1024, mReader, 1024, new TreeMap<>());
}
@After
diff --git a/tests/Internal/src/com/android/internal/protolog/PerfettoProtoLogImplTest.java b/tests/Internal/src/com/android/internal/protolog/PerfettoProtoLogImplTest.java
index 270f595..548adef 100644
--- a/tests/Internal/src/com/android/internal/protolog/PerfettoProtoLogImplTest.java
+++ b/tests/Internal/src/com/android/internal/protolog/PerfettoProtoLogImplTest.java
@@ -64,6 +64,7 @@
import java.io.IOException;
import java.util.List;
import java.util.Random;
+import java.util.TreeMap;
import perfetto.protos.Protolog;
import perfetto.protos.ProtologCommon;
@@ -152,7 +153,8 @@
.thenAnswer(it -> new ProtoInputStream(mViewerConfigBuilder.build().toByteArray()));
mReader = Mockito.spy(new ProtoLogViewerConfigReader(viewerConfigInputStreamProvider));
- mProtoLog = new PerfettoProtoLogImpl(viewerConfigInputStreamProvider, mReader);
+ mProtoLog =
+ new PerfettoProtoLogImpl(viewerConfigInputStreamProvider, mReader, new TreeMap<>());
}
@After
diff --git a/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt b/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt
index a359155..2690bc5 100644
--- a/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/CommandOptions.kt
@@ -25,6 +25,7 @@
const val READ_LOG_CMD = "read-log"
private val commands = setOf(TRANSFORM_CALLS_CMD, GENERATE_CONFIG_CMD, READ_LOG_CMD)
+ // TODO: This is always the same. I don't think it's required
private const val PROTOLOG_CLASS_PARAM = "--protolog-class"
private const val PROTOLOGGROUP_CLASS_PARAM = "--loggroups-class"
private const val PROTOLOGGROUP_JAR_PARAM = "--loggroups-jar"
diff --git a/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
index ea2c8da..837dae9 100644
--- a/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
+++ b/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt
@@ -24,11 +24,17 @@
import com.github.javaparser.ParserConfiguration
import com.github.javaparser.StaticJavaParser
import com.github.javaparser.ast.CompilationUnit
+import com.github.javaparser.ast.NodeList
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
+import com.github.javaparser.ast.body.InitializerDeclaration
+import com.github.javaparser.ast.expr.FieldAccessExpr
import com.github.javaparser.ast.expr.MethodCallExpr
+import com.github.javaparser.ast.expr.NameExpr
import com.github.javaparser.ast.expr.NullLiteralExpr
+import com.github.javaparser.ast.expr.ObjectCreationExpr
import com.github.javaparser.ast.expr.SimpleName
import com.github.javaparser.ast.expr.StringLiteralExpr
+import com.github.javaparser.ast.stmt.BlockStmt
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
@@ -96,7 +102,8 @@
outJar.putNextEntry(zipEntry(protologImplPath))
outJar.write(generateProtoLogImpl(protologImplName, command.viewerConfigFilePathArg,
- command.legacyViewerConfigFilePathArg, command.legacyOutputFilePath).toByteArray())
+ command.legacyViewerConfigFilePathArg, command.legacyOutputFilePath,
+ groups, command.protoLogGroupsClassNameArg).toByteArray())
val executor = newThreadPool()
@@ -140,6 +147,8 @@
viewerConfigFilePath: String,
legacyViewerConfigFilePath: String?,
legacyOutputFilePath: String?,
+ groups: Map<String, LogGroup>,
+ protoLogGroupsClassName: String,
): String {
val file = File(PROTOLOG_IMPL_SRC_PATH)
@@ -160,7 +169,8 @@
classNameNode.setId(protoLogImplGenName)
injectConstants(classDeclaration,
- viewerConfigFilePath, legacyViewerConfigFilePath, legacyOutputFilePath)
+ viewerConfigFilePath, legacyViewerConfigFilePath, legacyOutputFilePath, groups,
+ protoLogGroupsClassName)
return code.toString()
}
@@ -169,7 +179,9 @@
classDeclaration: ClassOrInterfaceDeclaration,
viewerConfigFilePath: String,
legacyViewerConfigFilePath: String?,
- legacyOutputFilePath: String?
+ legacyOutputFilePath: String?,
+ groups: Map<String, LogGroup>,
+ protoLogGroupsClassName: String
) {
classDeclaration.fields.forEach { field ->
field.getAnnotationByClass(ProtoLogToolInjected::class.java)
@@ -197,6 +209,35 @@
StringLiteralExpr(it)
} ?: NullLiteralExpr())
}
+ ProtoLogToolInjected.Value.LOG_GROUPS.name -> {
+ val initializerBlockStmt = BlockStmt()
+ for (group in groups) {
+ initializerBlockStmt.addStatement(
+ MethodCallExpr()
+ .setName("put")
+ .setArguments(
+ NodeList(StringLiteralExpr(group.key),
+ FieldAccessExpr()
+ .setScope(
+ NameExpr(
+ protoLogGroupsClassName
+ ))
+ .setName(group.value.name)))
+ )
+ group.key
+ }
+
+ val treeMapCreation = ObjectCreationExpr()
+ .setType("TreeMap<String, IProtoLogGroup>")
+ .setAnonymousClassBody(NodeList(
+ InitializerDeclaration().setBody(
+ initializerBlockStmt
+ )
+ ))
+
+ field.setFinal(true)
+ field.variables.first().setInitializer(treeMapCreation)
+ }
else -> error("Unhandled ProtoLogToolInjected value: $valueName.")
}
}