Merge "Make MediaItem2 builder be a final class"
diff --git a/api/current.txt b/api/current.txt
index 49bccc9..3ba0dd2 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -4447,7 +4447,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(String, android.content.ComponentName, android.content.ComponentName, android.net.Uri, android.service.notification.ZenPolicy, 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 public AutomaticZenRule(android.os.Parcel);
method public int describeContents();
method public android.net.Uri getConditionId();
@@ -23053,7 +23053,7 @@
ctor public AudioAttributes.Builder();
ctor public AudioAttributes.Builder(android.media.AudioAttributes);
method public android.media.AudioAttributes build();
- method public android.media.AudioAttributes.Builder setAllowCapture(boolean);
+ method @NonNull public android.media.AudioAttributes.Builder setAllowCapture(boolean);
method public android.media.AudioAttributes.Builder setContentType(int);
method public android.media.AudioAttributes.Builder setFlags(int);
method public android.media.AudioAttributes.Builder setLegacyStreamType(int);
@@ -23392,11 +23392,11 @@
public static final class AudioPlaybackCaptureConfiguration.Builder {
ctor public AudioPlaybackCaptureConfiguration.Builder(@NonNull android.media.projection.MediaProjection);
- method public android.media.AudioPlaybackCaptureConfiguration.Builder addMatchingUid(int);
- method public android.media.AudioPlaybackCaptureConfiguration.Builder addMatchingUsage(@NonNull android.media.AudioAttributes);
- method public android.media.AudioPlaybackCaptureConfiguration build();
- method public android.media.AudioPlaybackCaptureConfiguration.Builder excludeUid(int);
- method public android.media.AudioPlaybackCaptureConfiguration.Builder excludeUsage(@NonNull android.media.AudioAttributes);
+ method @NonNull public android.media.AudioPlaybackCaptureConfiguration.Builder addMatchingUid(int);
+ method @NonNull public android.media.AudioPlaybackCaptureConfiguration.Builder addMatchingUsage(@NonNull android.media.AudioAttributes);
+ method @NonNull public android.media.AudioPlaybackCaptureConfiguration build();
+ method @NonNull public android.media.AudioPlaybackCaptureConfiguration.Builder excludeUid(int);
+ method @NonNull public android.media.AudioPlaybackCaptureConfiguration.Builder excludeUsage(@NonNull android.media.AudioAttributes);
}
public final class AudioPlaybackConfiguration implements android.os.Parcelable {
@@ -23497,7 +23497,7 @@
ctor public AudioRecord.Builder();
method public android.media.AudioRecord build() throws java.lang.UnsupportedOperationException;
method public android.media.AudioRecord.Builder setAudioFormat(@NonNull android.media.AudioFormat) throws java.lang.IllegalArgumentException;
- method public android.media.AudioRecord.Builder setAudioPlaybackCaptureConfig(@NonNull android.media.AudioPlaybackCaptureConfiguration);
+ method @NonNull public android.media.AudioRecord.Builder setAudioPlaybackCaptureConfig(@NonNull android.media.AudioPlaybackCaptureConfiguration);
method public android.media.AudioRecord.Builder setAudioSource(int) throws java.lang.IllegalArgumentException;
method public android.media.AudioRecord.Builder setBufferSizeInBytes(int) throws java.lang.IllegalArgumentException;
}
@@ -41869,26 +41869,26 @@
public static class ZenPolicy.Builder {
ctor public ZenPolicy.Builder();
- method public android.service.notification.ZenPolicy.Builder allowAlarms(boolean);
- method public android.service.notification.ZenPolicy.Builder allowAllSounds();
- method public android.service.notification.ZenPolicy.Builder allowCalls(int);
- method public android.service.notification.ZenPolicy.Builder allowEvents(boolean);
- method public android.service.notification.ZenPolicy.Builder allowMedia(boolean);
- method public android.service.notification.ZenPolicy.Builder allowMessages(int);
- method public android.service.notification.ZenPolicy.Builder allowReminders(boolean);
- method public android.service.notification.ZenPolicy.Builder allowRepeatCallers(boolean);
- method public android.service.notification.ZenPolicy.Builder allowSystem(boolean);
- method public android.service.notification.ZenPolicy build();
- method public android.service.notification.ZenPolicy.Builder disallowAllSounds();
- method public android.service.notification.ZenPolicy.Builder hideAllVisualEffects();
- method public android.service.notification.ZenPolicy.Builder showAllVisualEffects();
- method public android.service.notification.ZenPolicy.Builder showBadges(boolean);
- method public android.service.notification.ZenPolicy.Builder showFullScreenIntent(boolean);
- method public android.service.notification.ZenPolicy.Builder showInAmbientDisplay(boolean);
- method public android.service.notification.ZenPolicy.Builder showInNotificationList(boolean);
- method public android.service.notification.ZenPolicy.Builder showLights(boolean);
- method public android.service.notification.ZenPolicy.Builder showPeeking(boolean);
- method public android.service.notification.ZenPolicy.Builder showStatusBarIcons(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowAlarms(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowAllSounds();
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowCalls(int);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowEvents(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowMedia(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowMessages(int);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowReminders(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowRepeatCallers(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder allowSystem(boolean);
+ method @NonNull public android.service.notification.ZenPolicy build();
+ method @NonNull public android.service.notification.ZenPolicy.Builder disallowAllSounds();
+ method @NonNull public android.service.notification.ZenPolicy.Builder hideAllVisualEffects();
+ method @NonNull public android.service.notification.ZenPolicy.Builder showAllVisualEffects();
+ method @NonNull public android.service.notification.ZenPolicy.Builder showBadges(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showFullScreenIntent(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showInAmbientDisplay(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showInNotificationList(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showLights(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showPeeking(boolean);
+ method @NonNull public android.service.notification.ZenPolicy.Builder showStatusBarIcons(boolean);
}
}
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index da72002..7298da6 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -219,6 +219,7 @@
"tests/anomaly/AnomalyTracker_test.cpp",
"tests/ConfigManager_test.cpp",
"tests/external/puller_util_test.cpp",
+ "tests/external/IncidentReportArgs_test.cpp",
"tests/external/StatsPuller_test.cpp",
"tests/indexed_priority_queue_test.cpp",
"tests/LogEntryMatcher_test.cpp",
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index a983b27..5968fa8 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -1568,7 +1568,7 @@
ROLLBACK_INITIATE = 1;
ROLLBACK_SUCCESS = 2;
ROLLBACK_FAILURE = 3;
- ROLLBACK_ROOT_TRIGGERED = 4;
+ ROLLBACK_BOOT_TRIGGERED = 4;
}
optional RollbackType rollback_type = 1;
diff --git a/cmds/statsd/src/statsd_config.proto b/cmds/statsd/src/statsd_config.proto
index 5c6d548..0e91f52 100644
--- a/cmds/statsd/src/statsd_config.proto
+++ b/cmds/statsd/src/statsd_config.proto
@@ -324,6 +324,12 @@
EXPLICIT = 1;
}
optional Destination dest = 2;
+
+ // Package name of the incident report receiver.
+ optional string receiver_pkg = 3;
+
+ // Class name of the incident report receiver.
+ optional string receiver_cls = 4;
}
message PerfettoDetails {
diff --git a/cmds/statsd/src/subscriber/IncidentdReporter.cpp b/cmds/statsd/src/subscriber/IncidentdReporter.cpp
index 0ed2d75..7c2d242 100644
--- a/cmds/statsd/src/subscriber/IncidentdReporter.cpp
+++ b/cmds/statsd/src/subscriber/IncidentdReporter.cpp
@@ -162,6 +162,10 @@
}
incidentReport.setDest(dest);
+ incidentReport.setReceiverPkg(config.receiver_pkg());
+
+ incidentReport.setReceiverCls(config.receiver_cls());
+
sp<IIncidentManager> service = interface_cast<IIncidentManager>(
defaultServiceManager()->getService(android::String16("incident")));
if (service == nullptr) {
diff --git a/cmds/statsd/tests/external/IncidentReportArgs_test.cpp b/cmds/statsd/tests/external/IncidentReportArgs_test.cpp
new file mode 100644
index 0000000..c170b12
--- /dev/null
+++ b/cmds/statsd/tests/external/IncidentReportArgs_test.cpp
@@ -0,0 +1,72 @@
+// Copyright (C) 2018 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <android/os/IncidentReportArgs.h>
+
+#include <gtest/gtest.h>
+
+namespace android {
+namespace os {
+namespace statsd {
+
+TEST(IncidentReportArgsTest, testSerialization) {
+ IncidentReportArgs args;
+ args.setAll(0);
+ args.addSection(1000);
+ args.addSection(1001);
+
+ vector<uint8_t> header1;
+ header1.push_back(0x1);
+ header1.push_back(0x2);
+ vector<uint8_t> header2;
+ header1.push_back(0x22);
+ header1.push_back(0x33);
+
+ args.addHeader(header1);
+ args.addHeader(header2);
+
+ args.setDest(1);
+
+ args.setReceiverPkg("com.android.os");
+ args.setReceiverCls("com.android.os.Receiver");
+
+ Parcel out;
+ status_t err = args.writeToParcel(&out);
+ EXPECT_EQ(NO_ERROR, err);
+
+ out.setDataPosition(0);
+
+ IncidentReportArgs args2;
+ err = args2.readFromParcel(&out);
+ EXPECT_EQ(NO_ERROR, err);
+
+ EXPECT_EQ(0, args2.all());
+ set<int> sections;
+ sections.insert(1000);
+ sections.insert(1001);
+ EXPECT_EQ(sections, args2.sections());
+ EXPECT_EQ(1, args2.dest());
+
+ EXPECT_EQ(String16("com.android.os"), args2.receiverPkg());
+ EXPECT_EQ(String16("com.android.os.Receiver"), args2.receiverCls());
+
+ vector<vector<uint8_t>> headers;
+ headers.push_back(header1);
+ headers.push_back(header2);
+ EXPECT_EQ(headers, args2.headers());
+}
+
+} // namespace statsd
+} // namespace os
+} // namespace android
\ No newline at end of file
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index 4a826d1..010a900 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -16,18 +16,15 @@
package android.app;
-import static android.app.NotificationManager.INTERRUPTION_FILTER_PRIORITY;
-
+import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.app.NotificationManager.InterruptionFilter;
import android.content.ComponentName;
-import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
-import android.service.notification.ZenPolicy;
import android.service.notification.Condition;
-
-import com.android.internal.util.Preconditions;
+import android.service.notification.ZenPolicy;
import java.util.Objects;
@@ -92,8 +89,9 @@
* action ({@link Condition#STATE_TRUE}).
* @param enabled Whether the rule is enabled.
*/
- public AutomaticZenRule(String name, ComponentName owner, ComponentName configurationActivity,
- Uri conditionId, ZenPolicy policy, int interruptionFilter, boolean enabled) {
+ public AutomaticZenRule(@NonNull String name, @Nullable ComponentName owner,
+ @Nullable ComponentName configurationActivity, @NonNull Uri conditionId,
+ @Nullable ZenPolicy policy, int interruptionFilter, boolean enabled) {
this.name = name;
this.owner = owner;
this.configurationActivity = configurationActivity;
diff --git a/core/java/android/content/pm/LauncherApps.java b/core/java/android/content/pm/LauncherApps.java
index 38ea43e..0cc5f39 100644
--- a/core/java/android/content/pm/LauncherApps.java
+++ b/core/java/android/content/pm/LauncherApps.java
@@ -792,7 +792,7 @@
*
* @return an {@link AppUsageLimit} object describing the app time limit containing
* the given package with the smallest time remaining, or {@code null} if none exist.
- * @throws SecurityException when the caller is not the active launcher.
+ * @throws SecurityException when the caller is not the recents app.
*/
@Nullable
public LauncherApps.AppUsageLimit getAppUsageLimit(@NonNull String packageName,
diff --git a/core/java/android/os/IncidentReportArgs.java b/core/java/android/os/IncidentReportArgs.java
index 1bdfd94..a1f2430 100644
--- a/core/java/android/os/IncidentReportArgs.java
+++ b/core/java/android/os/IncidentReportArgs.java
@@ -36,6 +36,8 @@
private final ArrayList<byte[]> mHeaders = new ArrayList<byte[]>();
private boolean mAll;
private int mPrivacyPolicy;
+ private String mReceiverPkg;
+ private String mReceiverCls;
/**
* Construct an incident report args with no fields.
@@ -73,6 +75,10 @@
}
out.writeInt(mPrivacyPolicy);
+
+ out.writeString(mReceiverPkg);
+
+ out.writeString(mReceiverCls);
}
public void readFromParcel(Parcel in) {
@@ -91,6 +97,10 @@
}
mPrivacyPolicy = in.readInt();
+
+ mReceiverPkg = in.readString();
+
+ mReceiverCls = in.readString();
}
public static final @android.annotation.NonNull Parcelable.Creator<IncidentReportArgs> CREATOR
@@ -126,6 +136,8 @@
sb.append(mHeaders.size());
sb.append(" headers), ");
sb.append("privacy: ").append(mPrivacyPolicy);
+ sb.append("receiver pkg: ").append(mReceiverPkg);
+ sb.append("receiver cls: ").append(mReceiverCls);
return sb.toString();
}
diff --git a/core/java/android/service/notification/ZenPolicy.java b/core/java/android/service/notification/ZenPolicy.java
index 74e6c6e..7ef40cd 100644
--- a/core/java/android/service/notification/ZenPolicy.java
+++ b/core/java/android/service/notification/ZenPolicy.java
@@ -17,6 +17,7 @@
package android.service.notification;
import android.annotation.IntDef;
+import android.annotation.NonNull;
import android.app.Notification;
import android.app.NotificationChannel;
import android.os.Parcel;
@@ -378,14 +379,14 @@
/**
* Builds the current ZenPolicy.
*/
- public ZenPolicy build() {
+ public @NonNull ZenPolicy build() {
return mZenPolicy.copy();
}
/**
* Allows all notifications to bypass DND and unmutes all streams.
*/
- public Builder allowAllSounds() {
+ public @NonNull Builder allowAllSounds() {
for (int i = 0; i < mZenPolicy.mPriorityCategories.size(); i++) {
mZenPolicy.mPriorityCategories.set(i, STATE_ALLOW);
}
@@ -401,7 +402,7 @@
* {@link NotificationChannel#canBypassDnd can bypass DND}. If no channels can bypass DND,
* the ringer stream is also muted.
*/
- public Builder disallowAllSounds() {
+ public @NonNull Builder disallowAllSounds() {
for (int i = 0; i < mZenPolicy.mPriorityCategories.size(); i++) {
mZenPolicy.mPriorityCategories.set(i, STATE_DISALLOW);
}
@@ -413,7 +414,7 @@
/**
* Allows notifications intercepted by DND to show on all surfaces when DND is active.
*/
- public Builder showAllVisualEffects() {
+ public @NonNull Builder showAllVisualEffects() {
for (int i = 0; i < mZenPolicy.mVisualEffects.size(); i++) {
mZenPolicy.mVisualEffects.set(i, STATE_ALLOW);
}
@@ -423,7 +424,7 @@
/**
* Disallows notifications intercepted by DND from showing when DND is active.
*/
- public Builder hideAllVisualEffects() {
+ public @NonNull Builder hideAllVisualEffects() {
for (int i = 0; i < mZenPolicy.mVisualEffects.size(); i++) {
mZenPolicy.mVisualEffects.set(i, STATE_DISALLOW);
}
@@ -435,7 +436,7 @@
* unset categories will default to the current applied policy.
* @hide
*/
- public Builder unsetPriorityCategory(@PriorityCategory int category) {
+ public @NonNull Builder unsetPriorityCategory(@PriorityCategory int category) {
mZenPolicy.mPriorityCategories.set(category, STATE_UNSET);
if (category == PRIORITY_CATEGORY_MESSAGES) {
@@ -452,7 +453,7 @@
* unset effects will default to the current applied policy.
* @hide
*/
- public Builder unsetVisualEffect(@VisualEffect int effect) {
+ public @NonNull Builder unsetVisualEffect(@VisualEffect int effect) {
mZenPolicy.mVisualEffects.set(effect, STATE_UNSET);
return this;
}
@@ -461,7 +462,7 @@
* Whether to allow notifications with category {@link Notification#CATEGORY_REMINDER}
* to play sounds and visually appear or to intercept them when DND is active.
*/
- public Builder allowReminders(boolean allow) {
+ public @NonNull Builder allowReminders(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_REMINDERS,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -471,7 +472,7 @@
* Whether to allow notifications with category {@link Notification#CATEGORY_EVENT}
* to play sounds and visually appear or to intercept them when DND is active.
*/
- public Builder allowEvents(boolean allow) {
+ public @NonNull Builder allowEvents(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_EVENTS,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -483,7 +484,7 @@
* them when DND is active.
* @param audienceType message senders that are allowed to bypass DND
*/
- public Builder allowMessages(@PeopleType int audienceType) {
+ public @NonNull Builder allowMessages(@PeopleType int audienceType) {
if (audienceType == STATE_UNSET) {
return unsetPriorityCategory(PRIORITY_CATEGORY_MESSAGES);
}
@@ -507,7 +508,7 @@
* them when DND is active.
* @param audienceType callers that are allowed to bypass DND
*/
- public Builder allowCalls(@PeopleType int audienceType) {
+ public @NonNull Builder allowCalls(@PeopleType int audienceType) {
if (audienceType == STATE_UNSET) {
return unsetPriorityCategory(PRIORITY_CATEGORY_CALLS);
}
@@ -530,7 +531,7 @@
* {@link Notification#CATEGORY_CALL} that have recently called
* to play sounds and visually appear.
*/
- public Builder allowRepeatCallers(boolean allow) {
+ public @NonNull Builder allowRepeatCallers(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_REPEAT_CALLERS,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -542,7 +543,7 @@
* to play sounds and visually appear or to intercept them when DND is active.
* Disallowing alarms will mute the alarm stream when DND is active.
*/
- public Builder allowAlarms(boolean allow) {
+ public @NonNull Builder allowAlarms(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_ALARMS,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -553,7 +554,7 @@
* appear or to intercept them when DND is active.
* Disallowing media will mute the media stream when DND is active.
*/
- public Builder allowMedia(boolean allow) {
+ public @NonNull Builder allowMedia(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_MEDIA,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -563,7 +564,7 @@
* Whether to allow system sounds to play when DND is active.
* Disallowing system sounds will mute the system stream when DND is active.
*/
- public Builder allowSystem(boolean allow) {
+ public @NonNull Builder allowSystem(boolean allow) {
mZenPolicy.mPriorityCategories.set(PRIORITY_CATEGORY_SYSTEM,
allow ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -573,7 +574,7 @@
* Whether to allow {@link PriorityCategory} sounds to play when DND is active.
* @hide
*/
- public Builder allowCategory(@PriorityCategory int category, boolean allow) {
+ public @NonNull Builder allowCategory(@PriorityCategory int category, boolean allow) {
switch (category) {
case PRIORITY_CATEGORY_ALARMS:
allowAlarms(allow);
@@ -601,7 +602,7 @@
* Whether {@link Notification#fullScreenIntent full screen intents} that are intercepted
* by DND are shown.
*/
- public Builder showFullScreenIntent(boolean show) {
+ public @NonNull Builder showFullScreenIntent(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_FULL_SCREEN_INTENT,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -611,7 +612,7 @@
* Whether {@link NotificationChannel#shouldShowLights() notification lights} from
* notifications intercepted by DND are blocked.
*/
- public Builder showLights(boolean show) {
+ public @NonNull Builder showLights(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_LIGHTS,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -620,7 +621,7 @@
/**
* Whether notifications intercepted by DND are prevented from peeking.
*/
- public Builder showPeeking(boolean show) {
+ public @NonNull Builder showPeeking(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_PEEK,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -630,7 +631,7 @@
* Whether notifications intercepted by DND are prevented from appearing in the status bar
* on devices that support status bars.
*/
- public Builder showStatusBarIcons(boolean show) {
+ public @NonNull Builder showStatusBarIcons(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_STATUS_BAR,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -640,7 +641,7 @@
* Whether {@link NotificationChannel#canShowBadge() badges} from
* notifications intercepted by DND are allowed on devices that support badging.
*/
- public Builder showBadges(boolean show) {
+ public @NonNull Builder showBadges(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_BADGE,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -650,7 +651,7 @@
* Whether notification intercepted by DND are prevented from appearing on ambient displays
* on devices that support ambient display.
*/
- public Builder showInAmbientDisplay(boolean show) {
+ public @NonNull Builder showInAmbientDisplay(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_AMBIENT,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -661,7 +662,7 @@
* list views like the notification shade or lockscreen on devices that support those
* views.
*/
- public Builder showInNotificationList(boolean show) {
+ public @NonNull Builder showInNotificationList(boolean show) {
mZenPolicy.mVisualEffects.set(VISUAL_EFFECT_NOTIFICATION_LIST,
show ? STATE_ALLOW : STATE_DISALLOW);
return this;
@@ -672,7 +673,7 @@
* {@link VisualEffect}
* @hide
*/
- public Builder showVisualEffect(@VisualEffect int effect, boolean show) {
+ public @NonNull Builder showVisualEffect(@VisualEffect int effect, boolean show) {
switch (effect) {
case VISUAL_EFFECT_FULL_SCREEN_INTENT:
showFullScreenIntent(show);
@@ -1001,7 +1002,7 @@
* Makes deep copy of this ZenPolicy.
* @hide
*/
- public ZenPolicy copy() {
+ public @NonNull ZenPolicy copy() {
final Parcel parcel = Parcel.obtain();
try {
writeToParcel(parcel, 0);
diff --git a/graphics/java/android/graphics/RenderNode.java b/graphics/java/android/graphics/RenderNode.java
index 42b6acd..0244942 100644
--- a/graphics/java/android/graphics/RenderNode.java
+++ b/graphics/java/android/graphics/RenderNode.java
@@ -62,7 +62,7 @@
*
* <h3>Creating a RenderNode</h3>
* <pre class="prettyprint">
- * RenderNode renderNode = RenderNode.create("myRenderNode");
+ * RenderNode renderNode = new RenderNode("myRenderNode");
* renderNode.setLeftTopRightBottom(0, 0, 50, 50); // Set the size to 50x50
* RecordingCanvas canvas = renderNode.beginRecording();
* try {
@@ -106,7 +106,7 @@
*
* <pre class="prettyprint">
* private void createDisplayList() {
- * mRenderNode = RenderNode.create("MyRenderNode");
+ * mRenderNode = new RenderNode("MyRenderNode");
* mRenderNode.setLeftTopRightBottom(0, 0, width, height);
* RecordingCanvas canvas = mRenderNode.beginRecording();
* try {
diff --git a/libs/incident/include/android/os/IncidentReportArgs.h b/libs/incident/include/android/os/IncidentReportArgs.h
index 5e8eac1..f056d3b 100644
--- a/libs/incident/include/android/os/IncidentReportArgs.h
+++ b/libs/incident/include/android/os/IncidentReportArgs.h
@@ -47,12 +47,16 @@
void setAll(bool all);
void setDest(int dest);
void addSection(int section);
+ void setReceiverPkg(const string& pkg);
+ void setReceiverCls(const string& cls);
void addHeader(const vector<uint8_t>& headerProto);
inline bool all() const { return mAll; }
bool containsSection(int section) const;
inline int dest() const { return mDest; }
inline const set<int>& sections() const { return mSections; }
+ inline const String16& receiverPkg() const { return mReceiverPkg; }
+ inline const String16& receiverCls() const { return mReceiverCls; }
inline const vector<vector<uint8_t>>& headers() const { return mHeaders; }
void merge(const IncidentReportArgs& that);
@@ -62,6 +66,8 @@
vector<vector<uint8_t>> mHeaders;
bool mAll;
int mDest;
+ String16 mReceiverPkg;
+ String16 mReceiverCls;
};
}
diff --git a/libs/incident/src/IncidentReportArgs.cpp b/libs/incident/src/IncidentReportArgs.cpp
index 06b7a5b..46c8dcf9 100644
--- a/libs/incident/src/IncidentReportArgs.cpp
+++ b/libs/incident/src/IncidentReportArgs.cpp
@@ -81,6 +81,16 @@
return err;
}
+ err = out->writeString16(mReceiverPkg);
+ if (err != NO_ERROR) {
+ return err;
+ }
+
+ err = out->writeString16(mReceiverCls);
+ if (err != NO_ERROR) {
+ return err;
+ }
+
return NO_ERROR;
}
@@ -134,6 +144,9 @@
}
mDest = dest;
+ mReceiverPkg = in->readString16();
+ mReceiverCls = in->readString16();
+
return OK;
}
@@ -161,6 +174,18 @@
}
void
+IncidentReportArgs::setReceiverPkg(const string& pkg)
+{
+ mReceiverPkg = String16(pkg.c_str());
+}
+
+void
+IncidentReportArgs::setReceiverCls(const string& cls)
+{
+ mReceiverCls = String16(cls.c_str());
+}
+
+void
IncidentReportArgs::addHeader(const vector<uint8_t>& headerProto)
{
mHeaders.push_back(headerProto);
diff --git a/media/java/android/media/AudioAttributes.java b/media/java/android/media/AudioAttributes.java
index 46d4204..aed8e4e 100644
--- a/media/java/android/media/AudioAttributes.java
+++ b/media/java/android/media/AudioAttributes.java
@@ -630,7 +630,7 @@
* true to allow apps to capture the audio
* @return the same Builder instance
*/
- public Builder setAllowCapture(boolean allowCapture) {
+ public @NonNull Builder setAllowCapture(boolean allowCapture) {
if (allowCapture) {
mFlags &= ~FLAG_NO_CAPTURE;
} else {
diff --git a/media/java/android/media/AudioPlaybackCaptureConfiguration.java b/media/java/android/media/AudioPlaybackCaptureConfiguration.java
index 9a16aea..333cd2d 100644
--- a/media/java/android/media/AudioPlaybackCaptureConfiguration.java
+++ b/media/java/android/media/AudioPlaybackCaptureConfiguration.java
@@ -72,7 +72,7 @@
*
* @param audioFormat The format in which to capture the audio.
*/
- AudioMix createAudioMix(AudioFormat audioFormat) {
+ @NonNull AudioMix createAudioMix(@NonNull AudioFormat audioFormat) {
return new AudioMix.Builder(mAudioMixingRule)
.setFormat(audioFormat)
.setRouteFlags(AudioMix.ROUTE_FLAG_LOOP_BACK | AudioMix.ROUTE_FLAG_RENDER)
@@ -123,7 +123,7 @@
* @throws IllegalStateException if called in conjunction with
* {@link #excludeUsage(AudioAttributes)}.
*/
- public Builder addMatchingUsage(@NonNull AudioAttributes audioAttributes) {
+ public @NonNull Builder addMatchingUsage(@NonNull AudioAttributes audioAttributes) {
Preconditions.checkNotNull(audioAttributes);
Preconditions.checkState(
mUsageMatchType != MATCH_TYPE_EXCLUSIVE, ERROR_MESSAGE_MISMATCHED_RULES);
@@ -141,7 +141,7 @@
*
* @throws IllegalStateException if called in conjunction with {@link #excludeUid(int)}.
*/
- public Builder addMatchingUid(int uid) {
+ public @NonNull Builder addMatchingUid(int uid) {
Preconditions.checkState(
mUidMatchType != MATCH_TYPE_EXCLUSIVE, ERROR_MESSAGE_MISMATCHED_RULES);
mAudioMixingRuleBuilder.addMixRule(AudioMixingRule.RULE_MATCH_UID, uid);
@@ -158,7 +158,7 @@
* @throws IllegalStateException if called in conjunction with
* {@link #addMatchingUsage(AudioAttributes)}.
*/
- public Builder excludeUsage(@NonNull AudioAttributes audioAttributes) {
+ public @NonNull Builder excludeUsage(@NonNull AudioAttributes audioAttributes) {
Preconditions.checkNotNull(audioAttributes);
Preconditions.checkState(
mUsageMatchType != MATCH_TYPE_INCLUSIVE, ERROR_MESSAGE_MISMATCHED_RULES);
@@ -176,7 +176,7 @@
*
* @throws IllegalStateException if called in conjunction with {@link #addMatchingUid(int)}.
*/
- public Builder excludeUid(int uid) {
+ public @NonNull Builder excludeUid(int uid) {
Preconditions.checkState(
mUidMatchType != MATCH_TYPE_INCLUSIVE, ERROR_MESSAGE_MISMATCHED_RULES);
mAudioMixingRuleBuilder.excludeMixRule(AudioMixingRule.RULE_MATCH_UID, uid);
@@ -189,7 +189,7 @@
*
* @throws UnsupportedOperationException if the parameters set are incompatible.
*/
- public AudioPlaybackCaptureConfiguration build() {
+ public @NonNull AudioPlaybackCaptureConfiguration build() {
return new AudioPlaybackCaptureConfiguration(mAudioMixingRuleBuilder.build(),
mProjection);
}
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index 3d5120f..28937a6 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -618,7 +618,7 @@
* @throws IllegalStateException if called in conjunction with {@link #setAudioSource(int)}.
* @throws NullPointerException if {@code config} is null.
*/
- public Builder setAudioPlaybackCaptureConfig(
+ public @NonNull Builder setAudioPlaybackCaptureConfig(
@NonNull AudioPlaybackCaptureConfiguration config) {
Preconditions.checkNotNull(
config, "Illegal null AudioPlaybackCaptureConfiguration argument");
@@ -647,7 +647,7 @@
return this;
}
- private AudioRecord buildAudioPlaybackCaptureRecord() {
+ private @NonNull AudioRecord buildAudioPlaybackCaptureRecord() {
AudioMix audioMix = mAudioPlaybackCaptureConfiguration.createAudioMix(mFormat);
MediaProjection projection = mAudioPlaybackCaptureConfiguration.getMediaProjection();
AudioPolicy audioPolicy = new AudioPolicy.Builder(/*context=*/ null)
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java
index 7755cbc..719417e 100644
--- a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/DynamicAndroidInstallationService.java
@@ -114,6 +114,7 @@
private NotificationManager mNM;
private long mSystemSize;
+ private long mUserdataSize;
private long mInstalledSize;
private boolean mJustCancelledByUser;
@@ -220,9 +221,11 @@
String url = intent.getStringExtra(DynamicAndroidClient.KEY_SYSTEM_URL);
mSystemSize = intent.getLongExtra(DynamicAndroidClient.KEY_SYSTEM_SIZE, 0);
- long userdata = intent.getLongExtra(DynamicAndroidClient.KEY_USERDATA_SIZE, 0);
+ mUserdataSize = intent.getLongExtra(DynamicAndroidClient.KEY_USERDATA_SIZE, 0);
- mInstallTask = new InstallationAsyncTask(url, mSystemSize, userdata, mDynAndroid, this);
+ mInstallTask = new InstallationAsyncTask(
+ url, mSystemSize, mUserdataSize, mDynAndroid, this);
+
mInstallTask.execute();
// start fore ground
@@ -332,8 +335,8 @@
case STATUS_IN_PROGRESS:
builder.setContentText(getString(R.string.notification_install_inprogress));
- int max = (int) Math.max(mSystemSize >> 20, 1);
- int progress = (int) mInstalledSize >> 20;
+ int max = (int) Math.max((mSystemSize + mUserdataSize) >> 20, 1);
+ int progress = (int) (mInstalledSize >> 20);
builder.setProgress(max, progress, false);
diff --git a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java
index 3c759e9..03fc773 100644
--- a/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java
+++ b/packages/DynamicAndroidInstallationService/src/com/android/dynandroid/InstallationAsyncTask.java
@@ -16,6 +16,7 @@
package com.android.dynandroid;
+import android.gsi.GsiProgress;
import android.os.AsyncTask;
import android.os.DynamicAndroidManager;
import android.util.Log;
@@ -63,8 +64,6 @@
private final InstallStatusListener mListener;
private DynamicAndroidManager.Session mInstallationSession;
- private long mInstalledSize;
- private long mReportedInstalledSize;
private int mResult = NO_RESULT;
private InputStream mStream;
@@ -89,8 +88,40 @@
Log.d(TAG, "Start doInBackground(), URL: " + mUrl);
try {
- // call start in background
- mInstallationSession = mDynamicAndroid.startInstallation(mSystemSize, mUserdataSize);
+ long installedSize = 0;
+ long reportedInstalledSize = 0;
+
+ long minStepToReport = (mSystemSize + mUserdataSize) / 100;
+
+ // init input stream before calling startInstallation(), which takes 90 seconds.
+ initInputStream();
+
+ Thread thread = new Thread(() -> {
+ mInstallationSession =
+ mDynamicAndroid.startInstallation(mSystemSize, mUserdataSize);
+ });
+
+
+ thread.start();
+
+ while (thread.isAlive()) {
+ if (isCancelled()) {
+ boolean aborted = mDynamicAndroid.abort();
+ Log.d(TAG, "Called DynamicAndroidManager.abort(), result = " + aborted);
+ return RESULT_OK;
+ }
+
+ GsiProgress progress = mDynamicAndroid.getInstallationProgress();
+ installedSize = progress.bytes_processed;
+
+ if (installedSize > reportedInstalledSize + minStepToReport) {
+ publishProgress(installedSize);
+ reportedInstalledSize = installedSize;
+ }
+
+ Thread.sleep(10);
+ }
+
if (mInstallationSession == null) {
Log.e(TAG, "Failed to start installation with requested size: "
@@ -99,12 +130,11 @@
return RESULT_ERROR_IO;
}
- initInputStream();
+ installedSize = mUserdataSize;
byte[] bytes = new byte[READ_BUFFER_SIZE];
int numBytesRead;
- long minStepToReport = mSystemSize / 100;
Log.d(TAG, "Start installation loop");
while ((numBytesRead = mStream.read(bytes, 0, READ_BUFFER_SIZE)) != -1) {
@@ -119,11 +149,11 @@
throw new IOException("Failed write() to DynamicAndroid");
}
- mInstalledSize += numBytesRead;
+ installedSize += numBytesRead;
- if (mInstalledSize > mReportedInstalledSize + minStepToReport) {
- publishProgress(mInstalledSize);
- mReportedInstalledSize = mInstalledSize;
+ if (installedSize > reportedInstalledSize + minStepToReport) {
+ publishProgress(installedSize);
+ reportedInstalledSize = installedSize;
}
}
diff --git a/packages/SystemUI/res/raw/image_wallpaper_fragment_shader.glsl b/packages/SystemUI/res/raw/image_wallpaper_fragment_shader.glsl
index 586cdf3..716e127 100644
--- a/packages/SystemUI/res/raw/image_wallpaper_fragment_shader.glsl
+++ b/packages/SystemUI/res/raw/image_wallpaper_fragment_shader.glsl
@@ -1,27 +1,76 @@
precision mediump float;
+// The actual wallpaper texture.
uniform sampler2D uTexture;
-uniform float uCenterReveal;
+
+// The 85th percenile for the luminance histogram of the image (a value between 0 and 1).
+// This value represents the point in histogram that includes 85% of the pixels of the image.
+uniform float uPer85;
+
+// Reveal is the animation value that goes from 1 (the image is hidden) to 0 (the image is visible).
uniform float uReveal;
+
+// The opacity of locked screen (constant value).
uniform float uAod2Opacity;
varying vec2 vTextureCoordinates;
+/*
+ * Calculates the relative luminance of the pixel.
+ */
vec3 luminosity(vec3 color) {
float lum = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
return vec3(lum);
}
vec4 transform(vec3 diffuse) {
- // TODO: Add well comments here, tracking on b/123615467.
+ // Getting the luminance for this pixel
vec3 lum = luminosity(diffuse);
- diffuse = mix(diffuse, lum, smoothstep(0., uCenterReveal, uReveal));
- float val = mix(uReveal, uCenterReveal, step(uCenterReveal, uReveal));
- diffuse = smoothstep(val, 1.0, diffuse);
- diffuse *= uAod2Opacity * (1. - smoothstep(uCenterReveal, 1., uReveal));
+
+ /*
+ * while the reveal > per85, it shows the luminance image (B&W image)
+ * then when moving passed that value, the image gets colored.
+ */
+ float trans = smoothstep(0., uPer85, uReveal);
+ diffuse = mix(diffuse, lum, trans);
+
+ // 'lower' value represents the capped 'reveal' value to the range [0, per85]
+ float selector = step(uPer85, uReveal);
+ float lower = mix(uReveal, uPer85, selector);
+
+ /*
+ * Remaps image:
+ * - from reveal=1 to reveal=per85 => lower=per85, diffuse=luminance
+ * That means that remaps black and white image pixel
+ * from a possible values of [0,1] to [per85, 1] (if the pixel is darker than per85,
+ * it's gonna be black, if it's between per85 and 1, it's gonna be gray
+ * and if it's 1 it's gonna be white).
+ * - from reveal=per85 to reveal=0 => lower=reveal, 'diffuse' changes from luminance to color
+ * That means that remaps each image pixel color (rgb)
+ * from a possible values of [0,1] to [lower, 1] (if the pixel color is darker than 'lower',
+ * it's gonna be 0, if it's between 'lower' and 1, it's gonna be remap to a value
+ * between 0 and 1 and if it's 1 it's gonna be 1).
+ * - if reveal=0 => lower=0, diffuse=color image
+ * The image is shown as it is, colored.
+ */
+ vec3 remaps = smoothstep(lower, 1., diffuse);
+
+ // Interpolate between diffuse and remaps using reveal to avoid over saturation.
+ diffuse = mix(diffuse, remaps, uReveal);
+
+ /*
+ * Fades in the pixel value:
+ * - if reveal=1 => fadeInOpacity=0
+ * - from reveal=1 to reveal=per85 => 0<=fadeInOpacity<=1
+ * - if reveal>per85 => fadeInOpacity=1
+ */
+ float fadeInOpacity = 1. - smoothstep(uPer85, 1., uReveal);
+ diffuse *= uAod2Opacity * fadeInOpacity;
+
return vec4(diffuse.r, diffuse.g, diffuse.b, 1.);
}
void main() {
+ // gets the pixel value of the wallpaper for this uv coordinates on screen.
vec4 fragColor = texture2D(uTexture, vTextureCoordinates);
gl_FragColor = transform(fragColor.rgb);
}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageGLWallpaper.java b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageGLWallpaper.java
index 19d85b1..a313336 100644
--- a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageGLWallpaper.java
+++ b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageGLWallpaper.java
@@ -50,7 +50,7 @@
static final String A_POSITION = "aPosition";
static final String A_TEXTURE_COORDINATES = "aTextureCoordinates";
- static final String U_CENTER_REVEAL = "uCenterReveal";
+ static final String U_PER85 = "uPer85";
static final String U_REVEAL = "uReveal";
static final String U_AOD2OPACITY = "uAod2Opacity";
static final String U_TEXTURE = "uTexture";
@@ -87,7 +87,7 @@
private int mAttrPosition;
private int mAttrTextureCoordinates;
private int mUniAod2Opacity;
- private int mUniCenterReveal;
+ private int mUniPer85;
private int mUniReveal;
private int mUniTexture;
private int mTextureId;
@@ -131,7 +131,7 @@
private void setupUniforms() {
mUniAod2Opacity = mProgram.getUniformHandle(U_AOD2OPACITY);
- mUniCenterReveal = mProgram.getUniformHandle(U_CENTER_REVEAL);
+ mUniPer85 = mProgram.getUniformHandle(U_PER85);
mUniReveal = mProgram.getUniformHandle(U_REVEAL);
mUniTexture = mProgram.getUniformHandle(U_TEXTURE);
}
@@ -144,8 +144,8 @@
return mAttrTextureCoordinates;
case U_AOD2OPACITY:
return mUniAod2Opacity;
- case U_CENTER_REVEAL:
- return mUniCenterReveal;
+ case U_PER85:
+ return mUniPer85;
case U_REVEAL:
return mUniReveal;
case U_TEXTURE:
diff --git a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
index 991b116..7295008 100644
--- a/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
+++ b/packages/SystemUI/src/com/android/systemui/glwallpaper/ImageWallpaperRenderer.java
@@ -93,13 +93,13 @@
@Override
public void onDrawFrame(GL10 gl) {
- float threshold = mImageProcessHelper.getPercentile85();
+ float per85 = mImageProcessHelper.getPercentile85();
float reveal = mImageRevealHelper.getReveal();
glClear(GL_COLOR_BUFFER_BIT);
glUniform1f(mWallpaper.getHandle(ImageGLWallpaper.U_AOD2OPACITY), 1);
- glUniform1f(mWallpaper.getHandle(ImageGLWallpaper.U_CENTER_REVEAL), threshold);
+ glUniform1f(mWallpaper.getHandle(ImageGLWallpaper.U_PER85), per85);
glUniform1f(mWallpaper.getHandle(ImageGLWallpaper.U_REVEAL), reveal);
mWallpaper.useTexture();
diff --git a/packages/SystemUI/src/com/android/systemui/power/BatteryStateSnapshot.kt b/packages/SystemUI/src/com/android/systemui/power/BatteryStateSnapshot.kt
new file mode 100644
index 0000000..d7a2d9a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/power/BatteryStateSnapshot.kt
@@ -0,0 +1,55 @@
+package com.android.systemui.power
+
+import com.android.systemui.power.PowerUI.NO_ESTIMATE_AVAILABLE
+
+/**
+ * A simple data class to snapshot battery state when a particular check for the
+ * low battery warning is running in the background.
+ */
+data class BatteryStateSnapshot(
+ val batteryLevel: Int,
+ val isPowerSaver: Boolean,
+ val plugged: Boolean,
+ val bucket: Int,
+ val batteryStatus: Int,
+ val severeLevelThreshold: Int,
+ val lowLevelThreshold: Int,
+ val timeRemainingMillis: Long,
+ val severeThresholdMillis: Long,
+ val lowThresholdMillis: Long,
+ val isBasedOnUsage: Boolean
+) {
+ /**
+ * Returns whether hybrid warning logic/copy should be used for this snapshot
+ */
+ var isHybrid: Boolean = false
+ private set
+
+ init {
+ this.isHybrid = true
+ }
+
+ constructor(
+ batteryLevel: Int,
+ isPowerSaver: Boolean,
+ plugged: Boolean,
+ bucket: Int,
+ batteryStatus: Int,
+ severeLevelThreshold: Int,
+ lowLevelThreshold: Int
+ ) : this(
+ batteryLevel,
+ isPowerSaver,
+ plugged,
+ bucket,
+ batteryStatus,
+ severeLevelThreshold,
+ lowLevelThreshold,
+ NO_ESTIMATE_AVAILABLE.toLong(),
+ NO_ESTIMATE_AVAILABLE.toLong(),
+ NO_ESTIMATE_AVAILABLE.toLong(),
+ false
+ ) {
+ this.isHybrid = false
+ }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/power/Estimate.java b/packages/SystemUI/src/com/android/systemui/power/Estimate.java
deleted file mode 100644
index 12a8f0a..0000000
--- a/packages/SystemUI/src/com/android/systemui/power/Estimate.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.android.systemui.power;
-
-public class Estimate {
- public final long estimateMillis;
- public final boolean isBasedOnUsage;
-
- public Estimate(long estimateMillis, boolean isBasedOnUsage) {
- this.estimateMillis = estimateMillis;
- this.isBasedOnUsage = isBasedOnUsage;
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/power/Estimate.kt b/packages/SystemUI/src/com/android/systemui/power/Estimate.kt
new file mode 100644
index 0000000..dca0d45
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/power/Estimate.kt
@@ -0,0 +1,3 @@
+package com.android.systemui.power
+
+data class Estimate(val estimateMillis: Long, val isBasedOnUsage: Boolean)
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerNotificationWarnings.java b/packages/SystemUI/src/com/android/systemui/power/PowerNotificationWarnings.java
index fdb0b36..41bcab5 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerNotificationWarnings.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerNotificationWarnings.java
@@ -134,10 +134,6 @@
private int mShowing;
private long mWarningTriggerTimeMs;
-
- private Estimate mEstimate;
- private long mLowWarningThreshold;
- private long mSevereWarningThreshold;
private boolean mWarning;
private boolean mShowAutoSaverSuggestion;
private boolean mPlaySound;
@@ -148,6 +144,7 @@
private SystemUIDialog mHighTempDialog;
private SystemUIDialog mThermalShutdownDialog;
@VisibleForTesting SystemUIDialog mUsbHighTempDialog;
+ private BatteryStateSnapshot mCurrentBatterySnapshot;
/**
*/
@@ -195,17 +192,8 @@
}
@Override
- public void updateEstimate(Estimate estimate) {
- mEstimate = estimate;
- if (estimate.estimateMillis <= mLowWarningThreshold) {
- mWarningTriggerTimeMs = System.currentTimeMillis();
- }
- }
-
- @Override
- public void updateThresholds(long lowThreshold, long severeThreshold) {
- mLowWarningThreshold = lowThreshold;
- mSevereWarningThreshold = severeThreshold;
+ public void updateSnapshot(BatteryStateSnapshot snapshot) {
+ mCurrentBatterySnapshot = snapshot;
}
private void updateNotification() {
@@ -254,15 +242,17 @@
protected void showWarningNotification() {
final String percentage = NumberFormat.getPercentInstance()
- .format((double) mBatteryLevel / 100.0);
+ .format((double) mCurrentBatterySnapshot.getBatteryLevel() / 100.0);
- // get standard notification copy
+ // get shared standard notification copy
String title = mContext.getString(R.string.battery_low_title);
- String contentText = mContext.getString(R.string.battery_low_percent_format, percentage);
+ String contentText;
- // override notification copy if hybrid notification enabled
- if (mEstimate != null) {
+ // get correct content text if notification is hybrid or not
+ if (mCurrentBatterySnapshot.isHybrid()) {
contentText = getHybridContentString(percentage);
+ } else {
+ contentText = mContext.getString(R.string.battery_low_percent_format, percentage);
}
final Notification.Builder nb =
@@ -282,8 +272,9 @@
}
// Make the notification red if the percentage goes below a certain amount or the time
// remaining estimate is disabled
- if (mEstimate == null || mBucket < 0
- || mEstimate.estimateMillis < mSevereWarningThreshold) {
+ if (!mCurrentBatterySnapshot.isHybrid() || mBucket < 0
+ || mCurrentBatterySnapshot.getTimeRemainingMillis()
+ < mCurrentBatterySnapshot.getSevereThresholdMillis()) {
nb.setColor(Utils.getColorAttrDefaultColor(mContext, android.R.attr.colorError));
}
@@ -324,10 +315,10 @@
private String getHybridContentString(String percentage) {
return PowerUtil.getBatteryRemainingStringFormatted(
- mContext,
- mEstimate.estimateMillis,
- percentage,
- mEstimate.isBasedOnUsage);
+ mContext,
+ mCurrentBatterySnapshot.getTimeRemainingMillis(),
+ percentage,
+ mCurrentBatterySnapshot.isBasedOnUsage());
}
private PendingIntent pendingBroadcast(String action) {
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
index e27c25e..1863860 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
@@ -55,6 +55,7 @@
import java.util.concurrent.Future;
public class PowerUI extends SystemUI {
+
static final String TAG = "PowerUI";
static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private static final long TEMPERATURE_INTERVAL = 30 * DateUtils.SECOND_IN_MILLIS;
@@ -63,6 +64,7 @@
static final long THREE_HOURS_IN_MILLIS = DateUtils.HOUR_IN_MILLIS * 3;
private static final int CHARGE_CYCLE_PERCENT_RESET = 45;
private static final long SIX_HOURS_MILLIS = Duration.ofHours(6).toMillis();
+ public static final int NO_ESTIMATE_AVAILABLE = -1;
private final Handler mHandler = new Handler();
@VisibleForTesting
@@ -71,13 +73,9 @@
private PowerManager mPowerManager;
private WarningsUI mWarnings;
private final Configuration mLastConfiguration = new Configuration();
- private long mTimeRemaining = Long.MAX_VALUE;
private int mPlugType = 0;
private int mInvalidCharger = 0;
private EnhancedEstimates mEnhancedEstimates;
- private Estimate mLastEstimate;
- private boolean mLowWarningShownThisChargeCycle;
- private boolean mSevereWarningShownThisChargeCycle;
private Future mLastShowWarningTask;
private boolean mEnableSkinTemperatureWarning;
private boolean mEnableUsbTemperatureAlarm;
@@ -87,6 +85,10 @@
private long mScreenOffTime = -1;
+ @VisibleForTesting boolean mLowWarningShownThisChargeCycle;
+ @VisibleForTesting boolean mSevereWarningShownThisChargeCycle;
+ @VisibleForTesting BatteryStateSnapshot mCurrentBatteryStateSnapshot;
+ @VisibleForTesting BatteryStateSnapshot mLastBatteryStateSnapshot;
@VisibleForTesting IThermalService mThermalService;
@VisibleForTesting int mBatteryLevel = 100;
@@ -205,6 +207,7 @@
mPlugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 1);
final int oldInvalidCharger = mInvalidCharger;
mInvalidCharger = intent.getIntExtra(BatteryManager.EXTRA_INVALID_CHARGER, 0);
+ mLastBatteryStateSnapshot = mCurrentBatteryStateSnapshot;
final boolean plugged = mPlugType != 0;
final boolean oldPlugged = oldPlugType != 0;
@@ -233,16 +236,22 @@
mWarnings.dismissInvalidChargerWarning();
} else if (mWarnings.isInvalidChargerWarningShowing()) {
// if invalid charger is showing, don't show low battery
+ if (DEBUG) {
+ Slog.d(TAG, "Bad Charger");
+ }
return;
}
// Show the correct version of low battery warning if needed
if (mLastShowWarningTask != null) {
mLastShowWarningTask.cancel(true);
+ if (DEBUG) {
+ Slog.d(TAG, "cancelled task");
+ }
}
mLastShowWarningTask = ThreadUtils.postOnBackgroundThread(() -> {
- maybeShowBatteryWarning(
- oldBatteryLevel, plugged, oldPlugged, oldBucket, bucket);
+ maybeShowBatteryWarningV2(
+ plugged, bucket);
});
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
@@ -257,53 +266,150 @@
}
}
- protected void maybeShowBatteryWarning(int oldBatteryLevel, boolean plugged, boolean oldPlugged,
- int oldBucket, int bucket) {
- boolean isPowerSaver = mPowerManager.isPowerSaveMode();
- // only play SFX when the dialog comes up or the bucket changes
- final boolean playSound = bucket != oldBucket || oldPlugged;
+ protected void maybeShowBatteryWarningV2(boolean plugged, int bucket) {
final boolean hybridEnabled = mEnhancedEstimates.isHybridNotificationEnabled();
- if (hybridEnabled) {
- Estimate estimate = mLastEstimate;
- if (estimate == null || mBatteryLevel != oldBatteryLevel) {
- estimate = mEnhancedEstimates.getEstimate();
- mLastEstimate = estimate;
- }
- // Turbo is not always booted once SysUI is running so we have to make sure we actually
- // get data back
- if (estimate != null) {
- mTimeRemaining = estimate.estimateMillis;
- mWarnings.updateEstimate(estimate);
- mWarnings.updateThresholds(mEnhancedEstimates.getLowWarningThreshold(),
- mEnhancedEstimates.getSevereWarningThreshold());
+ final boolean isPowerSaverMode = mPowerManager.isPowerSaveMode();
- // if we are now over 45% battery & 6 hours remaining we can trigger hybrid
- // notification again
- if (mBatteryLevel >= CHARGE_CYCLE_PERCENT_RESET
- && mTimeRemaining > SIX_HOURS_MILLIS) {
- mLowWarningShownThisChargeCycle = false;
- mSevereWarningShownThisChargeCycle = false;
- }
+ // Stick current battery state into an immutable container to determine if we should show
+ // a warning.
+ if (DEBUG) {
+ Slog.d(TAG, "evaluating which notification to show");
+ }
+ if (hybridEnabled) {
+ if (DEBUG) {
+ Slog.d(TAG, "using hybrid");
+ }
+ Estimate estimate = refreshEstimateIfNeeded();
+ mCurrentBatteryStateSnapshot = new BatteryStateSnapshot(mBatteryLevel, isPowerSaverMode,
+ plugged, bucket, mBatteryStatus, mLowBatteryReminderLevels[1],
+ mLowBatteryReminderLevels[0], estimate.getEstimateMillis(),
+ mEnhancedEstimates.getSevereWarningThreshold(),
+ mEnhancedEstimates.getLowWarningThreshold(), estimate.isBasedOnUsage());
+ } else {
+ if (DEBUG) {
+ Slog.d(TAG, "using standard");
+ }
+ mCurrentBatteryStateSnapshot = new BatteryStateSnapshot(mBatteryLevel, isPowerSaverMode,
+ plugged, bucket, mBatteryStatus, mLowBatteryReminderLevels[1],
+ mLowBatteryReminderLevels[0]);
+ }
+
+ mWarnings.updateSnapshot(mCurrentBatteryStateSnapshot);
+ if (mCurrentBatteryStateSnapshot.isHybrid()) {
+ maybeShowHybridWarning(mCurrentBatteryStateSnapshot, mLastBatteryStateSnapshot);
+ } else {
+ maybeShowBatteryWarning(mCurrentBatteryStateSnapshot, mLastBatteryStateSnapshot);
+ }
+ }
+
+ // updates the time estimate if we don't have one or battery level has changed.
+ @VisibleForTesting
+ Estimate refreshEstimateIfNeeded() {
+ if (mLastBatteryStateSnapshot == null
+ || mLastBatteryStateSnapshot.getTimeRemainingMillis() == NO_ESTIMATE_AVAILABLE
+ || mBatteryLevel != mLastBatteryStateSnapshot.getBatteryLevel()) {
+ final Estimate estimate = mEnhancedEstimates.getEstimate();
+ if (DEBUG) {
+ Slog.d(TAG, "updated estimate: " + estimate.getEstimateMillis());
+ }
+ return estimate;
+ }
+ return new Estimate(mLastBatteryStateSnapshot.getTimeRemainingMillis(),
+ mLastBatteryStateSnapshot.isBasedOnUsage());
+ }
+
+ @VisibleForTesting
+ void maybeShowHybridWarning(BatteryStateSnapshot currentSnapshot,
+ BatteryStateSnapshot lastSnapshot) {
+ // if we are now over 45% battery & 6 hours remaining so we can trigger hybrid
+ // notification again
+ if (currentSnapshot.getBatteryLevel() >= CHARGE_CYCLE_PERCENT_RESET
+ && currentSnapshot.getTimeRemainingMillis() > SIX_HOURS_MILLIS) {
+ mLowWarningShownThisChargeCycle = false;
+ mSevereWarningShownThisChargeCycle = false;
+ if (DEBUG) {
+ Slog.d(TAG, "Charge cycle reset! Can show warnings again");
}
}
- if (shouldShowLowBatteryWarning(plugged, oldPlugged, oldBucket, bucket,
- mTimeRemaining, isPowerSaver, mBatteryStatus)) {
- mWarnings.showLowBatteryWarning(playSound);
+ final boolean playSound = currentSnapshot.getBucket() != lastSnapshot.getBucket()
+ || lastSnapshot.getPlugged();
+ if (shouldShowHybridWarning(currentSnapshot)) {
+ mWarnings.showLowBatteryWarning(playSound);
// mark if we've already shown a warning this cycle. This will prevent the notification
// trigger from spamming users by only showing low/critical warnings once per cycle
- if (hybridEnabled) {
- if (mTimeRemaining <= mEnhancedEstimates.getSevereWarningThreshold()
- || mBatteryLevel <= mLowBatteryReminderLevels[1]) {
- mSevereWarningShownThisChargeCycle = true;
- mLowWarningShownThisChargeCycle = true;
- } else {
- mLowWarningShownThisChargeCycle = true;
+ if (currentSnapshot.getTimeRemainingMillis()
+ <= currentSnapshot.getSevereLevelThreshold()
+ || currentSnapshot.getBatteryLevel() <= mLowBatteryReminderLevels[1]) {
+ mSevereWarningShownThisChargeCycle = true;
+ mLowWarningShownThisChargeCycle = true;
+ if (DEBUG) {
+ Slog.d(TAG, "Severe warning marked as shown this cycle");
}
+ } else {
+ Slog.d(TAG, "Low warning marked as shown this cycle");
+ mLowWarningShownThisChargeCycle = true;
}
- } else if (shouldDismissLowBatteryWarning(plugged, oldBucket, bucket, mTimeRemaining,
- isPowerSaver)) {
+
+ } else if (shouldDismissHybridWarning(currentSnapshot)) {
+ if (DEBUG) {
+ Slog.d(TAG, "Dismissing warning");
+ }
+ mWarnings.dismissLowBatteryWarning();
+ } else {
+ if (DEBUG) {
+ Slog.d(TAG, "Updating warning");
+ }
+ mWarnings.updateLowBatteryWarning();
+ }
+ }
+
+ @VisibleForTesting
+ boolean shouldShowHybridWarning(BatteryStateSnapshot snapshot) {
+ if (snapshot.getPlugged()
+ || snapshot.getBatteryStatus() == BatteryManager.BATTERY_STATUS_UNKNOWN) {
+ Slog.d(TAG, "can't show warning due to - plugged: " + snapshot.getPlugged()
+ + " status unknown: "
+ + (snapshot.getBatteryStatus() == BatteryManager.BATTERY_STATUS_UNKNOWN));
+ return false;
+ }
+
+ // Only show the low warning once per charge cycle & no battery saver
+ final boolean canShowWarning = !mLowWarningShownThisChargeCycle && !snapshot.isPowerSaver()
+ && (snapshot.getTimeRemainingMillis() < snapshot.getLowThresholdMillis()
+ || snapshot.getBatteryLevel() <= snapshot.getLowLevelThreshold());
+
+ // Only show the severe warning once per charge cycle
+ final boolean canShowSevereWarning = !mSevereWarningShownThisChargeCycle
+ && (snapshot.getTimeRemainingMillis() < snapshot.getSevereThresholdMillis()
+ || snapshot.getBatteryLevel() <= snapshot.getSevereLevelThreshold());
+
+ final boolean canShow = canShowWarning || canShowSevereWarning;
+ if (DEBUG) {
+ Slog.d(TAG, "Enhanced trigger is: " + canShow + "\nwith battery snapshot:"
+ + " mLowWarningShownThisChargeCycle: " + mLowWarningShownThisChargeCycle
+ + " mSevereWarningShownThisChargeCycle: " + mSevereWarningShownThisChargeCycle
+ + "\n" + snapshot.toString());
+ }
+ return canShow;
+ }
+
+ @VisibleForTesting
+ boolean shouldDismissHybridWarning(BatteryStateSnapshot snapshot) {
+ return snapshot.getPlugged()
+ || snapshot.getTimeRemainingMillis() > snapshot.getLowThresholdMillis();
+ }
+
+ protected void maybeShowBatteryWarning(
+ BatteryStateSnapshot currentSnapshot,
+ BatteryStateSnapshot lastSnapshot) {
+ final boolean playSound = currentSnapshot.getBucket() != lastSnapshot.getBucket()
+ || lastSnapshot.getPlugged();
+
+ if (shouldShowLowBatteryWarning(currentSnapshot, lastSnapshot)) {
+ mWarnings.showLowBatteryWarning(playSound);
+ } else if (shouldDismissLowBatteryWarning(currentSnapshot, lastSnapshot)) {
mWarnings.dismissLowBatteryWarning();
} else {
mWarnings.updateLowBatteryWarning();
@@ -311,64 +417,25 @@
}
@VisibleForTesting
- boolean shouldShowLowBatteryWarning(boolean plugged, boolean oldPlugged, int oldBucket,
- int bucket, long timeRemaining, boolean isPowerSaver, int batteryStatus) {
- if (mEnhancedEstimates.isHybridNotificationEnabled()) {
- // triggering logic when enhanced estimate is available
- return isEnhancedTrigger(plugged, timeRemaining, isPowerSaver, batteryStatus);
- }
- // legacy triggering logic
- return !plugged
- && !isPowerSaver
- && (((bucket < oldBucket || oldPlugged) && bucket < 0))
- && batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN;
+ boolean shouldShowLowBatteryWarning(
+ BatteryStateSnapshot currentSnapshot,
+ BatteryStateSnapshot lastSnapshot) {
+ return !currentSnapshot.getPlugged()
+ && !currentSnapshot.isPowerSaver()
+ && (((currentSnapshot.getBucket() < lastSnapshot.getBucket()
+ || lastSnapshot.getPlugged())
+ && currentSnapshot.getBucket() < 0))
+ && currentSnapshot.getBatteryStatus() != BatteryManager.BATTERY_STATUS_UNKNOWN;
}
@VisibleForTesting
- boolean shouldDismissLowBatteryWarning(boolean plugged, int oldBucket, int bucket,
- long timeRemaining, boolean isPowerSaver) {
- final boolean hybridEnabled = mEnhancedEstimates.isHybridNotificationEnabled();
- final boolean hybridWouldDismiss = hybridEnabled
- && timeRemaining > mEnhancedEstimates.getLowWarningThreshold();
- final boolean standardWouldDismiss = (bucket > oldBucket && bucket > 0);
- return (isPowerSaver && !hybridEnabled)
- || plugged
- || (standardWouldDismiss && (!mEnhancedEstimates.isHybridNotificationEnabled()
- || hybridWouldDismiss));
- }
-
- private boolean isEnhancedTrigger(boolean plugged, long timeRemaining, boolean isPowerSaver,
- int batteryStatus) {
- if (plugged || batteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
- return false;
- }
- int warnLevel = mLowBatteryReminderLevels[0];
- int critLevel = mLowBatteryReminderLevels[1];
-
- // Only show the low warning once per charge cycle & no battery saver
- final boolean canShowWarning = !mLowWarningShownThisChargeCycle && !isPowerSaver
- && (timeRemaining < mEnhancedEstimates.getLowWarningThreshold()
- || mBatteryLevel <= warnLevel);
-
- // Only show the severe warning once per charge cycle
- final boolean canShowSevereWarning = !mSevereWarningShownThisChargeCycle
- && (timeRemaining < mEnhancedEstimates.getSevereWarningThreshold()
- || mBatteryLevel <= critLevel);
-
- final boolean canShow = canShowWarning || canShowSevereWarning;
- if (DEBUG) {
- Slog.d(TAG, "Enhanced trigger is: " + canShow + "\nwith values: "
- + " mLowWarningShownThisChargeCycle: " + mLowWarningShownThisChargeCycle
- + " mSevereWarningShownThisChargeCycle: " + mSevereWarningShownThisChargeCycle
- + " mEnhancedEstimates.timeremaining: " + timeRemaining
- + " mBatteryLevel: " + mBatteryLevel
- + " canShowWarning: " + canShowWarning
- + " canShowSevereWarning: " + canShowSevereWarning
- + " plugged: " + plugged
- + " batteryStatus: " + batteryStatus
- + " isPowerSaver: " + isPowerSaver);
- }
- return canShowWarning || canShowSevereWarning;
+ boolean shouldDismissLowBatteryWarning(
+ BatteryStateSnapshot currentSnapshot,
+ BatteryStateSnapshot lastSnapshot) {
+ return currentSnapshot.isPowerSaver()
+ || currentSnapshot.getPlugged()
+ || (currentSnapshot.getBucket() > lastSnapshot.getBucket()
+ && currentSnapshot.getBucket() > 0);
}
private void initTemperature() {
@@ -453,13 +520,21 @@
mWarnings.dump(pw);
}
+ /**
+ * The interface to allow PowerUI to communicate with whatever implementation of WarningsUI
+ * is being used by the system.
+ */
public interface WarningsUI {
+
+ /**
+ * Updates battery and screen info for determining whether to trigger battery warnings or
+ * not.
+ * @param batteryLevel The current battery level
+ * @param bucket The current battery bucket
+ * @param screenOffTime How long the screen has been off in millis
+ */
void update(int batteryLevel, int bucket, long screenOffTime);
- void updateEstimate(Estimate estimate);
-
- void updateThresholds(long lowThreshold, long severeThreshold);
-
void dismissLowBatteryWarning();
void showLowBatteryWarning(boolean playSound);
@@ -486,6 +561,12 @@
void dump(PrintWriter pw);
void userSwitched();
+
+ /**
+ * Updates the snapshot of battery state used for evaluating battery warnings
+ * @param snapshot object containing relevant values for making battery warning decisions.
+ */
+ void updateSnapshot(BatteryStateSnapshot snapshot);
}
// Thermal event received from thermal service manager subsystem
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
index af3c96f..3fa3e1a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/BatteryControllerImpl.java
@@ -226,7 +226,7 @@
String percentage = NumberFormat.getPercentInstance().format((double) mLevel / 100.0);
return PowerUtil.getBatteryRemainingShortStringFormatted(
- mContext, mEstimate.estimateMillis);
+ mContext, mEstimate.getEstimateMillis());
}
private void updateEstimateInBackground() {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java b/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
index 5876ae1..58c9311 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/power/PowerNotificationWarningsTest.java
@@ -30,6 +30,7 @@
import android.app.Notification;
import android.app.NotificationManager;
+import android.os.BatteryManager;
import android.test.suitebuilder.annotation.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -57,6 +58,9 @@
// Test Instance.
mContext.addMockSystemService(NotificationManager.class, mMockNotificationManager);
mPowerNotificationWarnings = new PowerNotificationWarnings(mContext);
+ BatteryStateSnapshot snapshot = new BatteryStateSnapshot(100, false, false, 1,
+ BatteryManager.BATTERY_HEALTH_GOOD, 5, 15);
+ mPowerNotificationWarnings.updateSnapshot(snapshot);
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java b/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
index 0aed63d..f51e473 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/power/PowerUITest.java
@@ -17,8 +17,7 @@
import static android.provider.Settings.Global.SHOW_TEMPERATURE_WARNING;
import static android.provider.Settings.Global.SHOW_USB_TEMPERATURE_ALARM;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.anyObject;
@@ -29,7 +28,6 @@
import static org.mockito.Mockito.when;
import android.content.Context;
-import android.content.Intent;
import android.os.BatteryManager;
import android.os.IThermalEventListener;
import android.os.IThermalService;
@@ -42,22 +40,20 @@
import android.testing.TestableLooper.RunWithLooper;
import android.testing.TestableResources;
-import com.android.settingslib.utils.ThreadUtils;
import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.power.PowerUI.WarningsUI;
import com.android.systemui.statusbar.phone.StatusBar;
+import java.time.Duration;
+import java.util.concurrent.TimeUnit;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import java.time.Duration;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
@RunWith(AndroidTestingRunner.class)
@RunWithLooper
@SmallTest
@@ -75,6 +71,7 @@
private static final int OLD_BATTERY_LEVEL_NINE = 9;
private static final int OLD_BATTERY_LEVEL_10 = 10;
private static final long VERY_BELOW_SEVERE_HYBRID_THRESHOLD = TimeUnit.MINUTES.toMillis(15);
+ public static final int BATTERY_LEVEL_10 = 10;
private WarningsUI mMockWarnings;
private PowerUI mPowerUI;
private EnhancedEstimates mEnhancedEstimates;
@@ -176,368 +173,333 @@
}
@Test
- public void testShouldShowLowBatteryWarning_showHybridOnly_overrideThresholdHigh_returnsNoShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold())
- .thenReturn(Duration.ofHours(1).toMillis());
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
+ public void testMaybeShowHybridWarning() {
mPowerUI.start();
- // unplugged device that would not show the non-hybrid notification but would show the
- // hybrid but the threshold has been overriden to be too low
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
+ // verify low warning shown this cycle noticed
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
+ BatteryStateSnapshot lastState = state.get();
+ state.mTimeRemainingMillis = Duration.ofHours(2).toMillis();
+ state.mBatteryLevel = 15;
+
+ mPowerUI.maybeShowHybridWarning(state.get(), lastState);
+
+ assertThat(mPowerUI.mLowWarningShownThisChargeCycle).isTrue();
+ assertThat(mPowerUI.mSevereWarningShownThisChargeCycle).isFalse();
+
+ // verify severe warning noticed this cycle
+ lastState = state.get();
+ state.mBatteryLevel = 1;
+ state.mTimeRemainingMillis = Duration.ofMinutes(10).toMillis();
+
+ mPowerUI.maybeShowHybridWarning(state.get(), lastState);
+
+ assertThat(mPowerUI.mLowWarningShownThisChargeCycle).isTrue();
+ assertThat(mPowerUI.mSevereWarningShownThisChargeCycle).isTrue();
+
+ // verify getting past threshold resets values
+ lastState = state.get();
+ state.mBatteryLevel = 100;
+ state.mTimeRemainingMillis = Duration.ofDays(1).toMillis();
+
+ mPowerUI.maybeShowHybridWarning(state.get(), lastState);
+
+ assertThat(mPowerUI.mLowWarningShownThisChargeCycle).isFalse();
+ assertThat(mPowerUI.mSevereWarningShownThisChargeCycle).isFalse();
}
@Test
- public void testShouldShowLowBatteryWarning_showHybridOnly_overrideThresholdHigh_returnsShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold())
- .thenReturn(Duration.ofHours(5).toMillis());
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
+ public void testShouldShowHybridWarning_lowLevelWarning() {
mPowerUI.start();
+ mPowerUI.mLowWarningShownThisChargeCycle = false;
+ mPowerUI.mSevereWarningShownThisChargeCycle = false;
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
- // unplugged device that would not show the non-hybrid notification but would show the
- // hybrid since the threshold has been overriden to be much higher
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertTrue(shouldShow);
+ // sanity check to make sure we can show for a valid config
+ state.mBatteryLevel = 10;
+ state.mTimeRemainingMillis = Duration.ofHours(2).toMillis();
+ boolean shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Shouldn't show if plugged in
+ state.mPlugged = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Shouldn't show if battery is unknown
+ state.mPlugged = false;
+ state.mBatteryStatus = BatteryManager.BATTERY_STATUS_UNKNOWN;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ state.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
+ // Already shown both warnings
+ mPowerUI.mLowWarningShownThisChargeCycle = true;
+ mPowerUI.mSevereWarningShownThisChargeCycle = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Can show low warning
+ mPowerUI.mLowWarningShownThisChargeCycle = false;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Can't show if above the threshold for time & battery
+ state.mTimeRemainingMillis = Duration.ofHours(1000).toMillis();
+ state.mBatteryLevel = 100;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Battery under low percentage threshold but not time
+ state.mBatteryLevel = 10;
+ state.mLowLevelThreshold = 50;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Should also trigger if both level and time remaining under low threshold
+ state.mTimeRemainingMillis = Duration.ofHours(2).toMillis();
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // battery saver should block the low level warning though
+ state.mIsPowerSaver = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
}
@Test
- public void testShouldShowLowBatteryWarning_showHybridOnly_returnsShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
+ public void testShouldShowHybridWarning_severeLevelWarning() {
mPowerUI.start();
+ mPowerUI.mLowWarningShownThisChargeCycle = false;
+ mPowerUI.mSevereWarningShownThisChargeCycle = false;
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
- // unplugged device that would not show the non-hybrid notification but would show the
- // hybrid
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertTrue(shouldShow);
+ // sanity check to make sure we can show for a valid config
+ state.mBatteryLevel = 1;
+ state.mTimeRemainingMillis = Duration.ofMinutes(1).toMillis();
+ boolean shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Shouldn't show if plugged in
+ state.mPlugged = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Shouldn't show if battery is unknown
+ state.mPlugged = false;
+ state.mBatteryStatus = BatteryManager.BATTERY_STATUS_UNKNOWN;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ state.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
+ // Already shown both warnings
+ mPowerUI.mLowWarningShownThisChargeCycle = true;
+ mPowerUI.mSevereWarningShownThisChargeCycle = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Can show severe warning
+ mPowerUI.mSevereWarningShownThisChargeCycle = false;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Can't show if above the threshold for time & battery
+ state.mTimeRemainingMillis = Duration.ofHours(1000).toMillis();
+ state.mBatteryLevel = 100;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isFalse();
+
+ // Battery under low percentage threshold but not time
+ state.mBatteryLevel = 1;
+ state.mSevereLevelThreshold = 5;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // Should also trigger if both level and time remaining under low threshold
+ state.mTimeRemainingMillis = Duration.ofHours(2).toMillis();
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
+
+ // battery saver should not block the severe level warning though
+ state.mIsPowerSaver = true;
+ shouldShow = mPowerUI.shouldShowHybridWarning(state.get());
+ assertThat(shouldShow).isTrue();
}
@Test
- public void testShouldShowLowBatteryWarning_showHybrid_showStandard_returnsShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.mBatteryLevel = 10;
+ public void testShouldDismissHybridWarning() {
mPowerUI.start();
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
- // unplugged device that would show the non-hybrid notification and the hybrid
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertTrue(shouldShow);
+ // We should dismiss if the device is plugged in
+ state.mPlugged = true;
+ state.mTimeRemainingMillis = Duration.ofHours(1).toMillis();
+ state.mLowThresholdMillis = Duration.ofHours(2).toMillis();
+ boolean shouldDismiss = mPowerUI.shouldDismissHybridWarning(state.get());
+ assertThat(shouldDismiss).isTrue();
+
+ // If not plugged in and below the threshold we should not dismiss
+ state.mPlugged = false;
+ shouldDismiss = mPowerUI.shouldDismissHybridWarning(state.get());
+ assertThat(shouldDismiss).isFalse();
+
+ // If we go over the low warning threshold we should dismiss
+ state.mTimeRemainingMillis = Duration.ofHours(3).toMillis();
+ shouldDismiss = mPowerUI.shouldDismissHybridWarning(state.get());
+ assertThat(shouldDismiss).isTrue();
}
@Test
- public void testShouldShowLowBatteryWarning_showStandardOnly_returnsShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.mBatteryLevel = 10;
- mPowerUI.start();
-
- // unplugged device that would show the non-hybrid but not the hybrid
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertTrue(shouldShow);
- }
-
- @Test
- public void testShouldShowLowBatteryWarning_deviceHighBattery_returnsNoShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.start();
-
- // unplugged device that would show the neither due to battery level being good
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testShouldShowLowBatteryWarning_devicePlugged_returnsNoShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.start();
-
- // plugged device that would show the neither due to being plugged
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(!UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testShouldShowLowBatteryWarning_deviceBatteryStatusUnknown_returnsNoShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.start();
-
- // Unknown battery status device that would show the neither due to the battery status being
- // unknown
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- !POWER_SAVER_OFF, BatteryManager.BATTERY_STATUS_UNKNOWN);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testShouldShowLowBatteryWarning_batterySaverEnabled_returnsNoShow() {
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- mPowerUI.start();
-
- // BatterySaverEnabled device that would show the neither due to battery saver
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- !POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testShouldShowLowBatteryWarning_onlyShowsOncePerChargeCycle() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- when(mEnhancedEstimates.getEstimate())
- .thenReturn(new Estimate(BELOW_HYBRID_THRESHOLD, true));
- mPowerUI.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
-
- mPowerUI.maybeShowBatteryWarning(OLD_BATTERY_LEVEL_NINE, UNPLUGGED, UNPLUGGED,
- ABOVE_WARNING_BUCKET, ABOVE_WARNING_BUCKET);
-
- // reduce battery level to handle time based trigger -> level trigger interactions
- mPowerUI.mBatteryLevel = 10;
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_dismissWhenPowerSaverEnabledLegacy() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(false);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // device that gets power saver turned on should dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, !POWER_SAVER_OFF);
- assertTrue(shouldDismiss);
- }
-
- @Test
- public void testShouldNotDismissLowBatteryWarning_dismissWhenPowerSaverEnabledHybrid() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // device that gets power saver turned on should dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, !POWER_SAVER_OFF);
- assertFalse(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_dismissWhenPlugged() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // device that gets plugged in should dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(!UNPLUGGED, BELOW_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertTrue(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_dismissHybridSignal_showStandardSignal_shouldShow() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // would dismiss hybrid but not non-hybrid should not dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertFalse(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_showHybridSignal_dismissStandardSignal_shouldShow() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // would dismiss non-hybrid but not hybrid should not dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertFalse(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_showBothSignal_shouldShow() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // should not dismiss when both would not dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- BELOW_WARNING_BUCKET, BELOW_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertFalse(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_dismissBothSignal_shouldDismiss() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- //should dismiss if both would dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertTrue(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_dismissStandardSignal_hybridDisabled_shouldDismiss() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(false);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
-
- // would dismiss non-hybrid with hybrid disabled should dismiss
- boolean shouldDismiss =
- mPowerUI.shouldDismissLowBatteryWarning(UNPLUGGED, BELOW_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, ABOVE_HYBRID_THRESHOLD, POWER_SAVER_OFF);
- assertTrue(shouldDismiss);
- }
-
- @Test
- public void testShouldDismissLowBatteryWarning_powerSaverModeEnabled()
- throws InterruptedException {
- when(mPowerManager.isPowerSaveMode()).thenReturn(true);
-
- mPowerUI.start();
- mPowerUI.mReceiver.onReceive(mContext,
- new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED));
-
- CountDownLatch latch = new CountDownLatch(1);
- ThreadUtils.postOnBackgroundThread(() -> latch.countDown());
- latch.await(5, TimeUnit.SECONDS);
-
- verify(mMockWarnings).dismissLowBatteryWarning();
- }
-
- @Test
- public void testShouldNotDismissLowBatteryWarning_powerSaverModeDisabled()
- throws InterruptedException {
- when(mPowerManager.isPowerSaveMode()).thenReturn(false);
-
- mPowerUI.start();
- mPowerUI.mReceiver.onReceive(mContext,
- new Intent(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED));
-
- CountDownLatch latch = new CountDownLatch(1);
- ThreadUtils.postOnBackgroundThread(() -> latch.countDown());
- latch.await(5, TimeUnit.SECONDS);
-
- verify(mMockWarnings, never()).dismissLowBatteryWarning();
- }
-
- @Test
- public void testSevereWarning_countsAsLowAndSevere_WarningOnlyShownOnce() {
- mPowerUI.start();
- when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
- when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
- when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
- when(mEnhancedEstimates.getEstimate())
- .thenReturn(new Estimate(BELOW_SEVERE_HYBRID_THRESHOLD, true));
- mPowerUI.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
-
- // reduce battery level to handle time based trigger -> level trigger interactions
- mPowerUI.mBatteryLevel = 5;
- boolean shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, BELOW_SEVERE_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertTrue(shouldShow);
-
- // actually run the end to end since it handles changing the internal state.
- mPowerUI.maybeShowBatteryWarning(OLD_BATTERY_LEVEL_10, UNPLUGGED, UNPLUGGED,
- ABOVE_WARNING_BUCKET, ABOVE_WARNING_BUCKET);
-
- shouldShow =
- mPowerUI.shouldShowLowBatteryWarning(UNPLUGGED, UNPLUGGED, ABOVE_WARNING_BUCKET,
- ABOVE_WARNING_BUCKET, VERY_BELOW_SEVERE_HYBRID_THRESHOLD,
- POWER_SAVER_OFF, BatteryManager.BATTERY_HEALTH_GOOD);
- assertFalse(shouldShow);
- }
-
- @Test
- public void testMaybeShowBatteryWarning_onlyQueriesEstimateOnBatteryLevelChangeOrNull() {
+ public void testRefreshEstimateIfNeeded_onlyQueriesEstimateOnBatteryLevelChangeOrNull() {
mPowerUI.start();
Estimate estimate = new Estimate(BELOW_HYBRID_THRESHOLD, true);
when(mEnhancedEstimates.isHybridNotificationEnabled()).thenReturn(true);
when(mEnhancedEstimates.getLowWarningThreshold()).thenReturn(PowerUI.THREE_HOURS_IN_MILLIS);
when(mEnhancedEstimates.getSevereWarningThreshold()).thenReturn(ONE_HOUR_MILLIS);
when(mEnhancedEstimates.getEstimate()).thenReturn(estimate);
- mPowerUI.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
+ mPowerUI.mBatteryLevel = 10;
- // we expect that the first time it will query even if the level is the same
+ // we expect that the first time it will query since there is no last battery snapshot.
+ // However an invalid estimate (-1) is returned.
+ Estimate refreshedEstimate = mPowerUI.refreshEstimateIfNeeded();
+ assertThat(refreshedEstimate.getEstimateMillis()).isEqualTo(BELOW_HYBRID_THRESHOLD);
+ BatteryStateSnapshot snapshot = new BatteryStateSnapshot(
+ BATTERY_LEVEL_10, false, false, 0, BatteryManager.BATTERY_HEALTH_GOOD,
+ 0, 0, -1, 0, 0, false);
+ mPowerUI.mLastBatteryStateSnapshot = snapshot;
+
+ // query again since the estimate was -1
+ estimate = new Estimate(BELOW_SEVERE_HYBRID_THRESHOLD, true);
+ when(mEnhancedEstimates.getEstimate()).thenReturn(estimate);
+ refreshedEstimate = mPowerUI.refreshEstimateIfNeeded();
+ assertThat(refreshedEstimate.getEstimateMillis()).isEqualTo(BELOW_SEVERE_HYBRID_THRESHOLD);
+ snapshot = new BatteryStateSnapshot(
+ BATTERY_LEVEL_10, false, false, 0, BatteryManager.BATTERY_HEALTH_GOOD, 0,
+ 0, BELOW_SEVERE_HYBRID_THRESHOLD, 0, 0, false);
+ mPowerUI.mLastBatteryStateSnapshot = snapshot;
+
+ // Battery level hasn't changed, so we don't query again
+ estimate = new Estimate(BELOW_HYBRID_THRESHOLD, true);
+ when(mEnhancedEstimates.getEstimate()).thenReturn(estimate);
+ refreshedEstimate = mPowerUI.refreshEstimateIfNeeded();
+ assertThat(refreshedEstimate.getEstimateMillis()).isEqualTo(BELOW_SEVERE_HYBRID_THRESHOLD);
+
+ // Battery level changes so we update again
mPowerUI.mBatteryLevel = 9;
- mPowerUI.maybeShowBatteryWarning(OLD_BATTERY_LEVEL_NINE, UNPLUGGED, UNPLUGGED,
- ABOVE_WARNING_BUCKET, ABOVE_WARNING_BUCKET);
- verify(mEnhancedEstimates, times(1)).getEstimate();
+ refreshedEstimate = mPowerUI.refreshEstimateIfNeeded();
+ assertThat(refreshedEstimate.getEstimateMillis()).isEqualTo(BELOW_HYBRID_THRESHOLD);
+ }
- // We should NOT query again if the battery level hasn't changed
- mPowerUI.maybeShowBatteryWarning(OLD_BATTERY_LEVEL_NINE, UNPLUGGED, UNPLUGGED,
- ABOVE_WARNING_BUCKET, ABOVE_WARNING_BUCKET);
- verify(mEnhancedEstimates, times(1)).getEstimate();
+ @Test
+ public void testShouldShowStandardWarning() {
+ mPowerUI.start();
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
+ state.mIsHybrid = false;
+ BatteryStateSnapshot lastState = state.get();
- // Battery level has changed, so we should query again
- mPowerUI.maybeShowBatteryWarning(OLD_BATTERY_LEVEL_10, UNPLUGGED, UNPLUGGED,
- ABOVE_WARNING_BUCKET, ABOVE_WARNING_BUCKET);
- verify(mEnhancedEstimates, times(2)).getEstimate();
+ // sanity check to make sure we can show for a valid config
+ state.mBatteryLevel = 10;
+ state.mBucket = -1;
+ boolean shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isTrue();
+ lastState = state.get();
+
+ // Shouldn't show if plugged in
+ state.mPlugged = true;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isFalse();
+
+ state.mPlugged = false;
+ // Shouldn't show if battery saver
+ state.mIsPowerSaver = true;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isFalse();
+
+ state.mIsPowerSaver = false;
+ // Shouldn't show if battery is unknown
+ state.mPlugged = false;
+ state.mBatteryStatus = BatteryManager.BATTERY_STATUS_UNKNOWN;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isFalse();
+
+ state.mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
+ // show if plugged -> unplugged, bucket -1 -> -1
+ state.mPlugged = true;
+ state.mBucket = -1;
+ lastState = state.get();
+ state.mPlugged = false;
+ state.mBucket = -1;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isTrue();
+
+ // don't show if plugged -> unplugged, bucket 0 -> 0
+ state.mPlugged = true;
+ state.mBucket = 0;
+ lastState = state.get();
+ state.mPlugged = false;
+ state.mBucket = 0;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isFalse();
+
+ // show if unplugged -> unplugged, bucket 0 -> -1
+ state.mPlugged = false;
+ state.mBucket = 0;
+ lastState = state.get();
+ state.mPlugged = false;
+ state.mBucket = -1;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isTrue();
+
+ // don't show if unplugged -> unplugged, bucket -1 -> 1
+ state.mPlugged = false;
+ state.mBucket = -1;
+ lastState = state.get();
+ state.mPlugged = false;
+ state.mBucket = 1;
+ shouldShow = mPowerUI.shouldShowLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldShow).isFalse();
+ }
+
+ @Test
+ public void testShouldDismissStandardWarning() {
+ mPowerUI.start();
+ BatteryStateSnapshotWrapper state = new BatteryStateSnapshotWrapper();
+ state.mIsHybrid = false;
+ BatteryStateSnapshot lastState = state.get();
+
+ // should dismiss if battery saver
+ state.mIsPowerSaver = true;
+ boolean shouldDismiss = mPowerUI.shouldDismissLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldDismiss).isTrue();
+
+ state.mIsPowerSaver = false;
+ // should dismiss if plugged
+ state.mPlugged = true;
+ shouldDismiss = mPowerUI.shouldDismissLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldDismiss).isTrue();
+
+ state.mPlugged = false;
+ // should dismiss if bucket 0 -> 1
+ state.mBucket = 0;
+ lastState = state.get();
+ state.mBucket = 1;
+ shouldDismiss = mPowerUI.shouldDismissLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldDismiss).isTrue();
+
+ // shouldn't dismiss if bucket -1 -> 0
+ state.mBucket = -1;
+ lastState = state.get();
+ state.mBucket = 0;
+ shouldDismiss = mPowerUI.shouldDismissLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldDismiss).isFalse();
+
+ // should dismiss if powersaver & bucket 0 -> 1
+ state.mIsPowerSaver = true;
+ state.mBucket = 0;
+ lastState = state.get();
+ state.mBucket = 1;
+ shouldDismiss = mPowerUI.shouldDismissLowBatteryWarning(state.get(), lastState);
+ assertThat(shouldDismiss).isTrue();
}
private Temperature getEmergencyStatusTemp(int type, String name) {
@@ -556,4 +518,35 @@
mPowerUI.mComponents = mContext.getComponents();
mPowerUI.mThermalService = mThermalServiceMock;
}
+
+ /**
+ * A simple wrapper class that sets values by default and makes them not final to improve
+ * test clarity.
+ */
+ private class BatteryStateSnapshotWrapper {
+ public int mBatteryLevel = 100;
+ public boolean mIsPowerSaver = false;
+ public boolean mPlugged = false;
+ public long mSevereThresholdMillis = Duration.ofHours(1).toMillis();
+ public long mLowThresholdMillis = Duration.ofHours(3).toMillis();
+ public int mSevereLevelThreshold = 5;
+ public int mLowLevelThreshold = 15;
+ public int mBucket = 1;
+ public int mBatteryStatus = BatteryManager.BATTERY_HEALTH_GOOD;
+ public long mTimeRemainingMillis = Duration.ofHours(24).toMillis();
+ public boolean mIsBasedOnUsage = true;
+ public boolean mIsHybrid = true;
+
+ public BatteryStateSnapshot get() {
+ if (mIsHybrid) {
+ return new BatteryStateSnapshot(mBatteryLevel, mIsPowerSaver, mPlugged, mBucket,
+ mBatteryStatus, mSevereLevelThreshold, mLowLevelThreshold,
+ mTimeRemainingMillis, mSevereThresholdMillis, mLowThresholdMillis,
+ mIsBasedOnUsage);
+ } else {
+ return new BatteryStateSnapshot(mBatteryLevel, mIsPowerSaver, mPlugged, mBucket,
+ mBatteryStatus, mSevereLevelThreshold, mLowLevelThreshold);
+ }
+ }
+ }
}
diff --git a/services/core/java/com/android/server/pm/LauncherAppsService.java b/services/core/java/com/android/server/pm/LauncherAppsService.java
index 9e912843..05af13a 100644
--- a/services/core/java/com/android/server/pm/LauncherAppsService.java
+++ b/services/core/java/com/android/server/pm/LauncherAppsService.java
@@ -744,12 +744,8 @@
if (!canAccessProfile(user.getIdentifier(), "Cannot access usage limit")) {
return null;
}
-
- final PackageManagerInternal pmi =
- LocalServices.getService(PackageManagerInternal.class);
- final ComponentName cn = pmi.getDefaultHomeActivity(user.getIdentifier());
- if (!cn.getPackageName().equals(callingPackage)) {
- throw new SecurityException("Caller is not the active launcher");
+ if (!mActivityTaskManagerInternal.isCallerRecents(Binder.getCallingUid())) {
+ throw new SecurityException("Caller is not the recents app");
}
final UsageStatsManagerInternal.AppUsageLimitData data =