Merge "Revert "Uses back and home button for screen pinning when recents is invisible""
diff --git a/Android.bp b/Android.bp
index 129d676..d5e04f9 100644
--- a/Android.bp
+++ b/Android.bp
@@ -676,6 +676,7 @@
"android.hardware.vibrator-V1.1-java-constants",
"android.hardware.wifi-V1.0-java-constants",
"android.hardware.radio-V1.0-java",
+ "android.hardware.usb.gadget-V1.0-java",
],
// Loaded with System.loadLibrary by android.view.textclassifier
diff --git a/Android.mk b/Android.mk
index 35b5f92..a78a01a 100644
--- a/Android.mk
+++ b/Android.mk
@@ -821,39 +821,41 @@
LOCAL_SRC_FILES := \
$(call all-proto-files-under, core/proto) \
$(call all-proto-files-under, libs/incident/proto/android/os)
+# Protos have lots of MissingOverride and similar.
+LOCAL_ERROR_PRONE_FLAGS := -XepDisableAllChecks
include $(BUILD_STATIC_JAVA_LIBRARY)
# ==== hiddenapi lists =======================================
-# Copy blacklist and dark greylist over into the build folder.
+# Copy blacklist and light greylist over into the build folder.
# This is for ART buildbots which need to mock these lists and have alternative
# rules for building them. Other rules in the build system should depend on the
# files in the build folder.
$(eval $(call copy-one-file,frameworks/base/config/hiddenapi-blacklist.txt,\
$(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)))
-$(eval $(call copy-one-file,frameworks/base/config/hiddenapi-dark-greylist.txt,\
- $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST)))
+$(eval $(call copy-one-file,frameworks/base/config/hiddenapi-light-greylist.txt,\
+ $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST)))
-# Generate light greylist as private API minus (blacklist plus dark greylist).
+# Generate dark greylist as private API minus (blacklist plus light greylist).
-$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST): PRIVATE_API := $(INTERNAL_PLATFORM_PRIVATE_DEX_API_FILE)
-$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST): BLACKLIST := $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
-$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST): DARK_GREYLIST := $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST)
-$(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST): $(INTERNAL_PLATFORM_PRIVATE_DEX_API_FILE) \
- $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST) \
- $(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST)
- if [ ! -z "`comm -12 <(sort $(BLACKLIST)) <(sort $(DARK_GREYLIST))`" ]; then \
- echo "There should be no overlap between $(BLACKLIST) and $(DARK_GREYLIST)" 1>&2; \
+$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST): PRIVATE_API := $(INTERNAL_PLATFORM_PRIVATE_DEX_API_FILE)
+$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST): BLACKLIST := $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST)
+$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST): LIGHT_GREYLIST := $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST)
+$(INTERNAL_PLATFORM_HIDDENAPI_DARK_GREYLIST): $(INTERNAL_PLATFORM_PRIVATE_DEX_API_FILE) \
+ $(INTERNAL_PLATFORM_HIDDENAPI_BLACKLIST) \
+ $(INTERNAL_PLATFORM_HIDDENAPI_LIGHT_GREYLIST)
+ if [ ! -z "`comm -12 <(sort $(BLACKLIST)) <(sort $(LIGHT_GREYLIST))`" ]; then \
+ echo "There should be no overlap between $(BLACKLIST) and $(LIGHT_GREYLIST)" 1>&2; \
exit 1; \
elif [ ! -z "`comm -13 <(sort $(PRIVATE_API)) <(sort $(BLACKLIST))`" ]; then \
echo "$(BLACKLIST) must be a subset of $(PRIVATE_API)" 1>&2; \
exit 2; \
- elif [ ! -z "`comm -13 <(sort $(PRIVATE_API)) <(sort $(DARK_GREYLIST))`" ]; then \
- echo "$(DARK_GREYLIST) must be a subset of $(PRIVATE_API)" 1>&2; \
+ elif [ ! -z "`comm -13 <(sort $(PRIVATE_API)) <(sort $(LIGHT_GREYLIST))`" ]; then \
+ echo "$(LIGHT_GREYLIST) must be a subset of $(PRIVATE_API)" 1>&2; \
exit 3; \
fi
- comm -23 <(sort $(PRIVATE_API)) <(sort $(BLACKLIST) $(DARK_GREYLIST)) > $@
+ comm -23 <(sort $(PRIVATE_API)) <(sort $(BLACKLIST) $(LIGHT_GREYLIST)) > $@
# Include subdirectory makefiles
# ============================================================
diff --git a/api/current.txt b/api/current.txt
index 63db312..d415f52 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -969,7 +969,9 @@
field public static final int orderingFromXml = 16843239; // 0x10101e7
field public static final int orientation = 16842948; // 0x10100c4
field public static final int outAnimation = 16843128; // 0x1010178
+ field public static final int outlineAmbientShadowColor = 16844162; // 0x1010582
field public static final int outlineProvider = 16843960; // 0x10104b8
+ field public static final int outlineSpotShadowColor = 16844161; // 0x1010581
field public static final int overScrollFooter = 16843459; // 0x10102c3
field public static final int overScrollHeader = 16843458; // 0x10102c2
field public static final int overScrollMode = 16843457; // 0x10102c1
@@ -6085,16 +6087,16 @@
method public android.os.ParcelFileDescriptor executeShellCommand(java.lang.String);
method public android.view.accessibility.AccessibilityNodeInfo findFocus(int);
method public android.view.accessibility.AccessibilityNodeInfo getRootInActiveWindow();
- method public final android.accessibilityservice.AccessibilityServiceInfo getServiceInfo();
+ method public android.accessibilityservice.AccessibilityServiceInfo getServiceInfo();
method public android.view.WindowAnimationFrameStats getWindowAnimationFrameStats();
method public android.view.WindowContentFrameStats getWindowContentFrameStats(int);
method public java.util.List<android.view.accessibility.AccessibilityWindowInfo> getWindows();
method public boolean injectInputEvent(android.view.InputEvent, boolean);
- method public final boolean performGlobalAction(int);
+ method public boolean performGlobalAction(int);
method public void setOnAccessibilityEventListener(android.app.UiAutomation.OnAccessibilityEventListener);
method public boolean setRotation(int);
method public void setRunAsMonkey(boolean);
- method public final void setServiceInfo(android.accessibilityservice.AccessibilityServiceInfo);
+ method public void setServiceInfo(android.accessibilityservice.AccessibilityServiceInfo);
method public android.graphics.Bitmap takeScreenshot();
method public void waitForIdle(long, long) throws java.util.concurrent.TimeoutException;
field public static final int FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES = 1; // 0x1
@@ -7250,6 +7252,7 @@
method public android.app.slice.Slice bindSlice(android.content.Intent, java.util.List<android.app.slice.SliceSpec>);
method public java.util.List<android.app.slice.SliceSpec> getPinnedSpecs(android.net.Uri);
method public java.util.Collection<android.net.Uri> getSliceDescendants(android.net.Uri);
+ method public android.net.Uri mapIntentToUri(android.content.Intent);
method public void pinSlice(android.net.Uri, java.util.List<android.app.slice.SliceSpec>);
method public deprecated void registerSliceCallback(android.net.Uri, android.app.slice.SliceManager.SliceCallback, java.util.List<android.app.slice.SliceSpec>);
method public deprecated void registerSliceCallback(android.net.Uri, android.app.slice.SliceManager.SliceCallback, java.util.List<android.app.slice.SliceSpec>, java.util.concurrent.Executor);
@@ -10050,6 +10053,7 @@
field public static final int FLAG_ACTIVITY_FORWARD_RESULT = 33554432; // 0x2000000
field public static final int FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY = 1048576; // 0x100000
field public static final int FLAG_ACTIVITY_LAUNCH_ADJACENT = 4096; // 0x1000
+ field public static final int FLAG_ACTIVITY_MATCH_EXTERNAL = 2048; // 0x800
field public static final int FLAG_ACTIVITY_MULTIPLE_TASK = 134217728; // 0x8000000
field public static final int FLAG_ACTIVITY_NEW_DOCUMENT = 524288; // 0x80000
field public static final int FLAG_ACTIVITY_NEW_TASK = 268435456; // 0x10000000
@@ -11612,15 +11616,15 @@
public final class AssetManager implements java.lang.AutoCloseable {
method public void close();
- method public java.lang.String[] getLocales();
- method public java.lang.String[] list(java.lang.String) throws java.io.IOException;
- method public java.io.InputStream open(java.lang.String) throws java.io.IOException;
- method public java.io.InputStream open(java.lang.String, int) throws java.io.IOException;
- method public android.content.res.AssetFileDescriptor openFd(java.lang.String) throws java.io.IOException;
- method public android.content.res.AssetFileDescriptor openNonAssetFd(java.lang.String) throws java.io.IOException;
- method public android.content.res.AssetFileDescriptor openNonAssetFd(int, java.lang.String) throws java.io.IOException;
- method public android.content.res.XmlResourceParser openXmlResourceParser(java.lang.String) throws java.io.IOException;
- method public android.content.res.XmlResourceParser openXmlResourceParser(int, java.lang.String) throws java.io.IOException;
+ method public final java.lang.String[] getLocales();
+ method public final java.lang.String[] list(java.lang.String) throws java.io.IOException;
+ method public final java.io.InputStream open(java.lang.String) throws java.io.IOException;
+ method public final java.io.InputStream open(java.lang.String, int) throws java.io.IOException;
+ method public final android.content.res.AssetFileDescriptor openFd(java.lang.String) throws java.io.IOException;
+ method public final android.content.res.AssetFileDescriptor openNonAssetFd(java.lang.String) throws java.io.IOException;
+ method public final android.content.res.AssetFileDescriptor openNonAssetFd(int, java.lang.String) throws java.io.IOException;
+ method public final android.content.res.XmlResourceParser openXmlResourceParser(java.lang.String) throws java.io.IOException;
+ method public final android.content.res.XmlResourceParser openXmlResourceParser(int, java.lang.String) throws java.io.IOException;
field public static final int ACCESS_BUFFER = 3; // 0x3
field public static final int ACCESS_RANDOM = 1; // 0x1
field public static final int ACCESS_STREAMING = 2; // 0x2
@@ -11628,15 +11632,9 @@
}
public final class AssetManager.AssetInputStream extends java.io.InputStream {
- method public final int available() throws java.io.IOException;
- method public final void close() throws java.io.IOException;
- method public final void mark(int);
- method public final boolean markSupported();
- method public final int read() throws java.io.IOException;
- method public final int read(byte[]) throws java.io.IOException;
- method public final int read(byte[], int, int) throws java.io.IOException;
- method public final void reset() throws java.io.IOException;
- method public final long skip(long) throws java.io.IOException;
+ method public void mark(int);
+ method public int read() throws java.io.IOException;
+ method public void reset() throws java.io.IOException;
}
public class ColorStateList implements android.os.Parcelable {
@@ -12398,7 +12396,7 @@
method public java.util.List<android.util.Pair<java.lang.String, java.lang.String>> getAttachedDbs();
method public long getMaximumSize();
method public long getPageSize();
- method public final java.lang.String getPath();
+ method public java.lang.String getPath();
method public deprecated java.util.Map<java.lang.String, java.lang.String> getSyncedTables();
method public int getVersion();
method public boolean inTransaction();
@@ -13055,29 +13053,29 @@
method public void eraseColor(int);
method public android.graphics.Bitmap extractAlpha();
method public android.graphics.Bitmap extractAlpha(android.graphics.Paint, int[]);
- method public final int getAllocationByteCount();
- method public final int getByteCount();
- method public final android.graphics.ColorSpace getColorSpace();
- method public final android.graphics.Bitmap.Config getConfig();
+ method public int getAllocationByteCount();
+ method public int getByteCount();
+ method public android.graphics.ColorSpace getColorSpace();
+ method public android.graphics.Bitmap.Config getConfig();
method public int getDensity();
method public int getGenerationId();
- method public final int getHeight();
+ method public int getHeight();
method public byte[] getNinePatchChunk();
method public int getPixel(int, int);
method public void getPixels(int[], int, int, int, int, int, int);
- method public final int getRowBytes();
+ method public int getRowBytes();
method public int getScaledHeight(android.graphics.Canvas);
method public int getScaledHeight(android.util.DisplayMetrics);
method public int getScaledHeight(int);
method public int getScaledWidth(android.graphics.Canvas);
method public int getScaledWidth(android.util.DisplayMetrics);
method public int getScaledWidth(int);
- method public final int getWidth();
- method public final boolean hasAlpha();
- method public final boolean hasMipMap();
- method public final boolean isMutable();
- method public final boolean isPremultiplied();
- method public final boolean isRecycled();
+ method public int getWidth();
+ method public boolean hasAlpha();
+ method public boolean hasMipMap();
+ method public boolean isMutable();
+ method public boolean isPremultiplied();
+ method public boolean isRecycled();
method public void prepareToDraw();
method public void reconfigure(int, int, android.graphics.Bitmap.Config);
method public void recycle();
@@ -13085,11 +13083,11 @@
method public void setConfig(android.graphics.Bitmap.Config);
method public void setDensity(int);
method public void setHasAlpha(boolean);
- method public final void setHasMipMap(boolean);
+ method public void setHasMipMap(boolean);
method public void setHeight(int);
method public void setPixel(int, int, int);
method public void setPixels(int[], int, int, int, int, int, int);
- method public final void setPremultiplied(boolean);
+ method public void setPremultiplied(boolean);
method public void setWidth(int);
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.graphics.Bitmap> CREATOR;
@@ -13161,7 +13159,7 @@
method public android.graphics.Bitmap decodeRegion(android.graphics.Rect, android.graphics.BitmapFactory.Options);
method public int getHeight();
method public int getWidth();
- method public final boolean isRecycled();
+ method public boolean isRecycled();
method public static android.graphics.BitmapRegionDecoder newInstance(byte[], int, int, boolean) throws java.io.IOException;
method public static android.graphics.BitmapRegionDecoder newInstance(java.io.FileDescriptor, boolean) throws java.io.IOException;
method public static android.graphics.BitmapRegionDecoder newInstance(java.io.InputStream, boolean) throws java.io.IOException;
@@ -14221,22 +14219,22 @@
ctor public Rect();
ctor public Rect(int, int, int, int);
ctor public Rect(android.graphics.Rect);
- method public final int centerX();
- method public final int centerY();
+ method public int centerX();
+ method public int centerY();
method public boolean contains(int, int);
method public boolean contains(int, int, int, int);
method public boolean contains(android.graphics.Rect);
method public int describeContents();
- method public final float exactCenterX();
- method public final float exactCenterY();
+ method public float exactCenterX();
+ method public float exactCenterY();
method public java.lang.String flattenToString();
- method public final int height();
+ method public int height();
method public void inset(int, int);
method public boolean intersect(int, int, int, int);
method public boolean intersect(android.graphics.Rect);
method public boolean intersects(int, int, int, int);
method public static boolean intersects(android.graphics.Rect, android.graphics.Rect);
- method public final boolean isEmpty();
+ method public boolean isEmpty();
method public void offset(int, int);
method public void offsetTo(int, int);
method public void readFromParcel(android.os.Parcel);
@@ -14250,7 +14248,7 @@
method public void union(int, int, int, int);
method public void union(android.graphics.Rect);
method public void union(int, int);
- method public final int width();
+ method public int width();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.graphics.Rect> CREATOR;
field public int bottom;
@@ -15819,9 +15817,7 @@
}
public static final class CameraCharacteristics.Key<T> {
- method public final boolean equals(java.lang.Object);
method public java.lang.String getName();
- method public final int hashCode();
}
public abstract class CameraConstrainedHighSpeedCaptureSession extends android.hardware.camera2.CameraCaptureSession {
@@ -16183,9 +16179,7 @@
}
public static final class CaptureRequest.Key<T> {
- method public final boolean equals(java.lang.Object);
method public java.lang.String getName();
- method public final int hashCode();
}
public class CaptureResult extends android.hardware.camera2.CameraMetadata {
@@ -16278,9 +16272,7 @@
}
public static final class CaptureResult.Key<T> {
- method public final boolean equals(java.lang.Object);
method public java.lang.String getName();
- method public final int hashCode();
}
public final class DngCreator implements java.lang.AutoCloseable {
@@ -16392,7 +16384,7 @@
method public float getComponent(int);
method public float getGreenEven();
method public float getGreenOdd();
- method public final float getRed();
+ method public float getRed();
field public static final int BLUE = 3; // 0x3
field public static final int COUNT = 4; // 0x4
field public static final int GREEN_EVEN = 1; // 0x1
@@ -16420,16 +16412,16 @@
method public android.util.Range<java.lang.Integer>[] getHighSpeedVideoFpsRangesFor(android.util.Size);
method public android.util.Size[] getHighSpeedVideoSizes();
method public android.util.Size[] getHighSpeedVideoSizesFor(android.util.Range<java.lang.Integer>);
- method public final int[] getInputFormats();
+ method public int[] getInputFormats();
method public android.util.Size[] getInputSizes(int);
- method public final int[] getOutputFormats();
+ method public int[] getOutputFormats();
method public long getOutputMinFrameDuration(int, android.util.Size);
method public <T> long getOutputMinFrameDuration(java.lang.Class<T>, android.util.Size);
method public <T> android.util.Size[] getOutputSizes(java.lang.Class<T>);
method public android.util.Size[] getOutputSizes(int);
method public long getOutputStallDuration(int, android.util.Size);
method public <T> long getOutputStallDuration(java.lang.Class<T>, android.util.Size);
- method public final int[] getValidOutputFormatsForInput(int);
+ method public int[] getValidOutputFormatsForInput(int);
method public boolean isOutputSupportedFor(int);
method public static <T> boolean isOutputSupportedFor(java.lang.Class<T>);
method public boolean isOutputSupportedFor(android.view.Surface);
@@ -16737,12 +16729,12 @@
public final class UCharacter implements android.icu.lang.UCharacterEnums.ECharacterCategory android.icu.lang.UCharacterEnums.ECharacterDirection {
method public static int charCount(int);
- method public static final int codePointAt(java.lang.CharSequence, int);
- method public static final int codePointAt(char[], int);
- method public static final int codePointAt(char[], int, int);
- method public static final int codePointBefore(java.lang.CharSequence, int);
- method public static final int codePointBefore(char[], int);
- method public static final int codePointBefore(char[], int, int);
+ method public static int codePointAt(java.lang.CharSequence, int);
+ method public static int codePointAt(char[], int);
+ method public static int codePointAt(char[], int, int);
+ method public static int codePointBefore(java.lang.CharSequence, int);
+ method public static int codePointBefore(char[], int);
+ method public static int codePointBefore(char[], int, int);
method public static int codePointCount(java.lang.CharSequence, int, int);
method public static int codePointCount(char[], int, int);
method public static int digit(int, int);
@@ -16750,7 +16742,7 @@
method public static int foldCase(int, boolean);
method public static java.lang.String foldCase(java.lang.String, boolean);
method public static int foldCase(int, int);
- method public static final java.lang.String foldCase(java.lang.String, int);
+ method public static java.lang.String foldCase(java.lang.String, int);
method public static char forDigit(int, int);
method public static android.icu.util.VersionInfo getAge(int);
method public static int getBidiPairedBracket(int);
@@ -16802,8 +16794,8 @@
method public static boolean isPrintable(int);
method public static boolean isSpaceChar(int);
method public static boolean isSupplementary(int);
- method public static final boolean isSupplementaryCodePoint(int);
- method public static final boolean isSurrogatePair(char, char);
+ method public static boolean isSupplementaryCodePoint(int);
+ method public static boolean isSurrogatePair(char, char);
method public static boolean isTitleCase(int);
method public static boolean isUAlphabetic(int);
method public static boolean isULowercase(int);
@@ -16812,13 +16804,13 @@
method public static boolean isUnicodeIdentifierPart(int);
method public static boolean isUnicodeIdentifierStart(int);
method public static boolean isUpperCase(int);
- method public static final boolean isValidCodePoint(int);
+ method public static boolean isValidCodePoint(int);
method public static boolean isWhitespace(int);
method public static int offsetByCodePoints(java.lang.CharSequence, int, int);
method public static int offsetByCodePoints(char[], int, int, int, int);
- method public static final int toChars(int, char[], int);
- method public static final char[] toChars(int);
- method public static final int toCodePoint(char, char);
+ method public static int toChars(int, char[], int);
+ method public static char[] toChars(int);
+ method public static int toCodePoint(char, char);
method public static int toLowerCase(int);
method public static java.lang.String toLowerCase(java.lang.String);
method public static java.lang.String toLowerCase(java.util.Locale, java.lang.String);
@@ -17108,7 +17100,7 @@
}
public static final class UCharacter.UnicodeBlock extends java.lang.Character.Subset {
- method public static final android.icu.lang.UCharacter.UnicodeBlock forName(java.lang.String);
+ method public static android.icu.lang.UCharacter.UnicodeBlock forName(java.lang.String);
method public int getID();
method public static android.icu.lang.UCharacter.UnicodeBlock getInstance(int);
method public static android.icu.lang.UCharacter.UnicodeBlock of(int);
@@ -17915,20 +17907,20 @@
}
public final class UScript {
- method public static final boolean breaksBetweenLetters(int);
- method public static final int[] getCode(java.util.Locale);
- method public static final int[] getCode(android.icu.util.ULocale);
- method public static final int[] getCode(java.lang.String);
- method public static final int getCodeFromName(java.lang.String);
- method public static final java.lang.String getName(int);
- method public static final java.lang.String getSampleString(int);
- method public static final int getScript(int);
- method public static final int getScriptExtensions(int, java.util.BitSet);
- method public static final java.lang.String getShortName(int);
- method public static final android.icu.lang.UScript.ScriptUsage getUsage(int);
- method public static final boolean hasScript(int, int);
- method public static final boolean isCased(int);
- method public static final boolean isRightToLeft(int);
+ method public static boolean breaksBetweenLetters(int);
+ method public static int[] getCode(java.util.Locale);
+ method public static int[] getCode(android.icu.util.ULocale);
+ method public static int[] getCode(java.lang.String);
+ method public static int getCodeFromName(java.lang.String);
+ method public static java.lang.String getName(int);
+ method public static java.lang.String getSampleString(int);
+ method public static int getScript(int);
+ method public static int getScriptExtensions(int, java.util.BitSet);
+ method public static java.lang.String getShortName(int);
+ method public static android.icu.lang.UScript.ScriptUsage getUsage(int);
+ method public static boolean hasScript(int, int);
+ method public static boolean isCased(int);
+ method public static boolean isRightToLeft(int);
field public static final int ADLAM = 167; // 0xa7
field public static final int AFAKA = 147; // 0x93
field public static final int AHOM = 161; // 0xa1
@@ -18343,14 +18335,14 @@
method public deprecated int hashCode();
method public int next();
method public int previous();
- method public static final int primaryOrder(int);
+ method public static int primaryOrder(int);
method public void reset();
- method public static final int secondaryOrder(int);
+ method public static int secondaryOrder(int);
method public void setOffset(int);
method public void setText(java.lang.String);
method public void setText(android.icu.text.UCharacterIterator);
method public void setText(java.text.CharacterIterator);
- method public static final int tertiaryOrder(int);
+ method public static int tertiaryOrder(int);
field public static final int IGNORABLE = 0; // 0x0
field public static final int NULLORDER = -1; // 0xffffffff
}
@@ -19577,7 +19569,7 @@
method public boolean isUpperCaseFirst();
method public void setAlternateHandlingDefault();
method public void setAlternateHandlingShifted(boolean);
- method public final void setCaseFirstDefault();
+ method public void setCaseFirstDefault();
method public void setCaseLevel(boolean);
method public void setCaseLevelDefault();
method public void setDecompositionDefault();
@@ -20550,11 +20542,11 @@
public final class LocaleData {
method public static android.icu.util.VersionInfo getCLDRVersion();
method public java.lang.String getDelimiter(int);
- method public static final android.icu.util.LocaleData getInstance(android.icu.util.ULocale);
- method public static final android.icu.util.LocaleData getInstance();
- method public static final android.icu.util.LocaleData.MeasurementSystem getMeasurementSystem(android.icu.util.ULocale);
+ method public static android.icu.util.LocaleData getInstance(android.icu.util.ULocale);
+ method public static android.icu.util.LocaleData getInstance();
+ method public static android.icu.util.LocaleData.MeasurementSystem getMeasurementSystem(android.icu.util.ULocale);
method public boolean getNoSubstitute();
- method public static final android.icu.util.LocaleData.PaperSize getPaperSize(android.icu.util.ULocale);
+ method public static android.icu.util.LocaleData.PaperSize getPaperSize(android.icu.util.ULocale);
method public void setNoSubstitute(boolean);
field public static final int ALT_QUOTATION_END = 3; // 0x3
field public static final int ALT_QUOTATION_START = 2; // 0x2
@@ -21984,6 +21976,7 @@
method public java.util.List<android.media.AudioPlaybackConfiguration> getActivePlaybackConfigurations();
method public java.util.List<android.media.AudioRecordingConfiguration> getActiveRecordingConfigurations();
method public android.media.AudioDeviceInfo[] getDevices(int);
+ method public java.util.List<android.media.MicrophoneInfo> getMicrophones() throws java.io.IOException;
method public int getMode();
method public java.lang.String getParameters(java.lang.String);
method public java.lang.String getProperty(java.lang.String);
@@ -22157,11 +22150,26 @@
field public static final android.os.Parcelable.Creator<android.media.AudioPlaybackConfiguration> CREATOR;
}
+ public final class AudioPresentation {
+ method public java.util.Map<java.util.Locale, java.lang.String> getLabels();
+ method public java.util.Locale getLocale();
+ method public int getMasteringIndication();
+ method public boolean hasAudioDescription();
+ method public boolean hasDialogueEnhancement();
+ method public boolean hasSpokenSubtitles();
+ field public static final int MASTERED_FOR_3D = 3; // 0x3
+ field public static final int MASTERED_FOR_HEADPHONE = 4; // 0x4
+ field public static final int MASTERED_FOR_STEREO = 1; // 0x1
+ field public static final int MASTERED_FOR_SURROUND = 2; // 0x2
+ field public static final int MASTERING_NOT_INDICATED = 0; // 0x0
+ }
+
public class AudioRecord implements android.media.AudioRouting {
ctor public AudioRecord(int, int, int, int, int) throws java.lang.IllegalArgumentException;
method public void addOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener, android.os.Handler);
method public deprecated void addOnRoutingChangedListener(android.media.AudioRecord.OnRoutingChangedListener, android.os.Handler);
method protected void finalize();
+ method public java.util.List<android.media.MicrophoneInfo> getActiveMicrophones() throws java.io.IOException;
method public int getAudioFormat();
method public int getAudioSessionId();
method public int getAudioSource();
@@ -22322,6 +22330,7 @@
method public int setPlaybackRate(int);
method public int setPositionNotificationPeriod(int);
method public boolean setPreferredDevice(android.media.AudioDeviceInfo);
+ method public int setPresentation(android.media.AudioPresentation);
method protected deprecated void setState(int);
method public deprecated int setStereoVolume(float, float);
method public void setStreamEventCallback(java.util.concurrent.Executor, android.media.AudioTrack.StreamEventCallback);
@@ -22826,40 +22835,40 @@
method public static android.media.MediaCodec createByCodecName(java.lang.String) throws java.io.IOException;
method public static android.media.MediaCodec createDecoderByType(java.lang.String) throws java.io.IOException;
method public static android.media.MediaCodec createEncoderByType(java.lang.String) throws java.io.IOException;
- method public final android.view.Surface createInputSurface();
+ method public android.view.Surface createInputSurface();
method public static android.view.Surface createPersistentInputSurface();
- method public final int dequeueInputBuffer(long);
- method public final int dequeueOutputBuffer(android.media.MediaCodec.BufferInfo, long);
+ method public int dequeueInputBuffer(long);
+ method public int dequeueOutputBuffer(android.media.MediaCodec.BufferInfo, long);
method protected void finalize();
- method public final void flush();
+ method public void flush();
method public android.media.MediaCodecInfo getCodecInfo();
method public java.nio.ByteBuffer getInputBuffer(int);
method public deprecated java.nio.ByteBuffer[] getInputBuffers();
- method public final android.media.MediaFormat getInputFormat();
+ method public android.media.MediaFormat getInputFormat();
method public android.media.Image getInputImage(int);
method public android.os.PersistableBundle getMetrics();
- method public final java.lang.String getName();
+ method public java.lang.String getName();
method public java.nio.ByteBuffer getOutputBuffer(int);
method public deprecated java.nio.ByteBuffer[] getOutputBuffers();
- method public final android.media.MediaFormat getOutputFormat();
- method public final android.media.MediaFormat getOutputFormat(int);
+ method public android.media.MediaFormat getOutputFormat();
+ method public android.media.MediaFormat getOutputFormat(int);
method public android.media.Image getOutputImage(int);
- method public final void queueInputBuffer(int, int, int, long, int) throws android.media.MediaCodec.CryptoException;
- method public final void queueSecureInputBuffer(int, int, android.media.MediaCodec.CryptoInfo, long, int) throws android.media.MediaCodec.CryptoException;
- method public final void release();
- method public final void releaseOutputBuffer(int, boolean);
- method public final void releaseOutputBuffer(int, long);
- method public final void reset();
+ method public void queueInputBuffer(int, int, int, long, int) throws android.media.MediaCodec.CryptoException;
+ method public void queueSecureInputBuffer(int, int, android.media.MediaCodec.CryptoInfo, long, int) throws android.media.MediaCodec.CryptoException;
+ method public void release();
+ method public void releaseOutputBuffer(int, boolean);
+ method public void releaseOutputBuffer(int, long);
+ method public void reset();
method public void setCallback(android.media.MediaCodec.Callback, android.os.Handler);
method public void setCallback(android.media.MediaCodec.Callback);
method public void setInputSurface(android.view.Surface);
method public void setOnFrameRenderedListener(android.media.MediaCodec.OnFrameRenderedListener, android.os.Handler);
method public void setOutputSurface(android.view.Surface);
- method public final void setParameters(android.os.Bundle);
- method public final void setVideoScalingMode(int);
- method public final void signalEndOfInputStream();
- method public final void start();
- method public final void stop();
+ method public void setParameters(android.os.Bundle);
+ method public void setVideoScalingMode(int);
+ method public void signalEndOfInputStream();
+ method public void start();
+ method public void stop();
field public static final int BUFFER_FLAG_CODEC_CONFIG = 2; // 0x2
field public static final int BUFFER_FLAG_END_OF_STREAM = 4; // 0x4
field public static final int BUFFER_FLAG_KEY_FRAME = 1; // 0x1
@@ -22953,10 +22962,10 @@
}
public final class MediaCodecInfo {
- method public final android.media.MediaCodecInfo.CodecCapabilities getCapabilitiesForType(java.lang.String);
- method public final java.lang.String getName();
- method public final java.lang.String[] getSupportedTypes();
- method public final boolean isEncoder();
+ method public android.media.MediaCodecInfo.CodecCapabilities getCapabilitiesForType(java.lang.String);
+ method public java.lang.String getName();
+ method public java.lang.String[] getSupportedTypes();
+ method public boolean isEncoder();
}
public static final class MediaCodecInfo.AudioCapabilities {
@@ -22976,9 +22985,9 @@
method public int getMaxSupportedInstances();
method public java.lang.String getMimeType();
method public android.media.MediaCodecInfo.VideoCapabilities getVideoCapabilities();
- method public final boolean isFeatureRequired(java.lang.String);
- method public final boolean isFeatureSupported(java.lang.String);
- method public final boolean isFormatSupported(android.media.MediaFormat);
+ method public boolean isFeatureRequired(java.lang.String);
+ method public boolean isFeatureSupported(java.lang.String);
+ method public boolean isFormatSupported(android.media.MediaFormat);
field public static final deprecated int COLOR_Format12bitRGB444 = 3; // 0x3
field public static final deprecated int COLOR_Format16bitARGB1555 = 5; // 0x5
field public static final deprecated int COLOR_Format16bitARGB4444 = 4; // 0x4
@@ -23236,11 +23245,11 @@
public final class MediaCodecList {
ctor public MediaCodecList(int);
- method public final java.lang.String findDecoderForFormat(android.media.MediaFormat);
- method public final java.lang.String findEncoderForFormat(android.media.MediaFormat);
- method public static final deprecated int getCodecCount();
- method public static final deprecated android.media.MediaCodecInfo getCodecInfoAt(int);
- method public final android.media.MediaCodecInfo[] getCodecInfos();
+ method public java.lang.String findDecoderForFormat(android.media.MediaFormat);
+ method public java.lang.String findEncoderForFormat(android.media.MediaFormat);
+ method public static deprecated int getCodecCount();
+ method public static deprecated android.media.MediaCodecInfo getCodecInfoAt(int);
+ method public android.media.MediaCodecInfo[] getCodecInfos();
field public static final int ALL_CODECS = 1; // 0x1
field public static final int REGULAR_CODECS = 0; // 0x0
}
@@ -23248,10 +23257,10 @@
public final class MediaCrypto {
ctor public MediaCrypto(java.util.UUID, byte[]) throws android.media.MediaCryptoException;
method protected void finalize();
- method public static final boolean isCryptoSchemeSupported(java.util.UUID);
- method public final void release();
- method public final boolean requiresSecureDecoderComponent(java.lang.String);
- method public final void setMediaDrmSession(byte[]) throws android.media.MediaCryptoException;
+ method public static boolean isCryptoSchemeSupported(java.util.UUID);
+ method public void release();
+ method public boolean requiresSecureDecoderComponent(java.lang.String);
+ method public void setMediaDrmSession(byte[]) throws android.media.MediaCryptoException;
}
public final class MediaCryptoException extends java.lang.Exception {
@@ -23267,10 +23276,10 @@
public final class MediaDescrambler implements java.lang.AutoCloseable {
ctor public MediaDescrambler(int) throws android.media.MediaCasException.UnsupportedCasException;
method public void close();
- method public final int descramble(java.nio.ByteBuffer, java.nio.ByteBuffer, android.media.MediaCodec.CryptoInfo);
+ method public int descramble(java.nio.ByteBuffer, java.nio.ByteBuffer, android.media.MediaCodec.CryptoInfo);
method protected void finalize();
- method public final boolean requiresSecureDecoderComponent(java.lang.String);
- method public final void setMediaCasSession(android.media.MediaCas.Session);
+ method public boolean requiresSecureDecoderComponent(java.lang.String);
+ method public void setMediaCasSession(android.media.MediaCas.Session);
}
public class MediaDescription implements android.os.Parcelable {
@@ -23326,8 +23335,8 @@
method public java.util.List<byte[]> getSecureStopIds();
method public java.util.List<byte[]> getSecureStops();
method public int getSecurityLevel(byte[]);
- method public static final boolean isCryptoSchemeSupported(java.util.UUID);
- method public static final boolean isCryptoSchemeSupported(java.util.UUID, java.lang.String);
+ method public static boolean isCryptoSchemeSupported(java.util.UUID);
+ method public static boolean isCryptoSchemeSupported(java.util.UUID, java.lang.String);
method public byte[] openSession() throws android.media.NotProvisionedException, android.media.ResourceBusyException;
method public byte[] provideKeyResponse(byte[], byte[]) throws android.media.DeniedByServerException, android.media.NotProvisionedException;
method public void provideProvisionResponse(byte[]) throws android.media.DeniedByServerException;
@@ -23478,6 +23487,7 @@
ctor public MediaExtractor();
method public boolean advance();
method protected void finalize();
+ method public java.util.List<android.media.AudioPresentation> getAudioPresentations(int);
method public long getCachedDuration();
method public android.media.MediaExtractor.CasInfo getCasInfo(int);
method public android.media.DrmInitData getDrmInitData();
@@ -23488,21 +23498,21 @@
method public long getSampleSize();
method public long getSampleTime();
method public int getSampleTrackIndex();
- method public final int getTrackCount();
+ method public int getTrackCount();
method public android.media.MediaFormat getTrackFormat(int);
method public boolean hasCacheReachedEndOfStream();
method public int readSampleData(java.nio.ByteBuffer, int);
- method public final void release();
+ method public void release();
method public void seekTo(long, int);
method public void selectTrack(int);
- method public final void setDataSource(android.media.MediaDataSource) throws java.io.IOException;
- method public final void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException;
- method public final void setDataSource(java.lang.String, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException;
- method public final void setDataSource(java.lang.String) throws java.io.IOException;
- method public final void setDataSource(android.content.res.AssetFileDescriptor) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException;
- method public final void setDataSource(java.io.FileDescriptor) throws java.io.IOException;
- method public final void setDataSource(java.io.FileDescriptor, long, long) throws java.io.IOException;
- method public final void setMediaCas(android.media.MediaCas);
+ method public void setDataSource(android.media.MediaDataSource) throws java.io.IOException;
+ method public void setDataSource(android.content.Context, android.net.Uri, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException;
+ method public void setDataSource(java.lang.String, java.util.Map<java.lang.String, java.lang.String>) throws java.io.IOException;
+ method public void setDataSource(java.lang.String) throws java.io.IOException;
+ method public void setDataSource(android.content.res.AssetFileDescriptor) throws java.io.IOException, java.lang.IllegalArgumentException, java.lang.IllegalStateException;
+ method public void setDataSource(java.io.FileDescriptor) throws java.io.IOException;
+ method public void setDataSource(java.io.FileDescriptor, long, long) throws java.io.IOException;
+ method public void setMediaCas(android.media.MediaCas);
method public void unselectTrack(int);
field public static final int SAMPLE_FLAG_ENCRYPTED = 2; // 0x2
field public static final int SAMPLE_FLAG_PARTIAL_FRAME = 4; // 0x4
@@ -23525,22 +23535,22 @@
public final class MediaFormat {
ctor public MediaFormat();
- method public final boolean containsKey(java.lang.String);
- method public static final android.media.MediaFormat createAudioFormat(java.lang.String, int, int);
- method public static final android.media.MediaFormat createSubtitleFormat(java.lang.String, java.lang.String);
- method public static final android.media.MediaFormat createVideoFormat(java.lang.String, int, int);
- method public final java.nio.ByteBuffer getByteBuffer(java.lang.String);
+ method public boolean containsKey(java.lang.String);
+ method public static android.media.MediaFormat createAudioFormat(java.lang.String, int, int);
+ method public static android.media.MediaFormat createSubtitleFormat(java.lang.String, java.lang.String);
+ method public static android.media.MediaFormat createVideoFormat(java.lang.String, int, int);
+ method public java.nio.ByteBuffer getByteBuffer(java.lang.String);
method public boolean getFeatureEnabled(java.lang.String);
- method public final float getFloat(java.lang.String);
- method public final int getInteger(java.lang.String);
- method public final long getLong(java.lang.String);
- method public final java.lang.String getString(java.lang.String);
- method public final void setByteBuffer(java.lang.String, java.nio.ByteBuffer);
+ method public float getFloat(java.lang.String);
+ method public int getInteger(java.lang.String);
+ method public long getLong(java.lang.String);
+ method public java.lang.String getString(java.lang.String);
+ method public void setByteBuffer(java.lang.String, java.nio.ByteBuffer);
method public void setFeatureEnabled(java.lang.String, boolean);
- method public final void setFloat(java.lang.String, float);
- method public final void setInteger(java.lang.String, int);
- method public final void setLong(java.lang.String, long);
- method public final void setString(java.lang.String, java.lang.String);
+ method public void setFloat(java.lang.String, float);
+ method public void setInteger(java.lang.String, int);
+ method public void setLong(java.lang.String, long);
+ method public void setString(java.lang.String, java.lang.String);
field public static final int COLOR_RANGE_FULL = 1; // 0x1
field public static final int COLOR_RANGE_LIMITED = 2; // 0x2
field public static final int COLOR_STANDARD_BT2020 = 6; // 0x6
@@ -24166,6 +24176,7 @@
ctor public MediaRecorder();
method public void addOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener, android.os.Handler);
method protected void finalize();
+ method public java.util.List<android.media.MicrophoneInfo> getActiveMicrophones() throws java.io.IOException;
method public static final int getAudioSourceMax();
method public int getMaxAmplitude() throws java.lang.IllegalStateException;
method public android.os.PersistableBundle getMetrics();
@@ -24439,14 +24450,14 @@
public final class MediaSync {
ctor public MediaSync();
- method public final android.view.Surface createInputSurface();
+ method public android.view.Surface createInputSurface();
method protected void finalize();
method public void flush();
method public android.media.PlaybackParams getPlaybackParams();
method public android.media.SyncParams getSyncParams();
method public android.media.MediaTimestamp getTimestamp();
method public void queueAudio(java.nio.ByteBuffer, int, long);
- method public final void release();
+ method public void release();
method public void setAudioTrack(android.media.AudioTrack);
method public void setCallback(android.media.MediaSync.Callback, android.os.Handler);
method public void setOnErrorListener(android.media.MediaSync.OnErrorListener, android.os.Handler);
@@ -24481,6 +24492,41 @@
method public float getMediaClockRate();
}
+ public final class MicrophoneInfo {
+ method public java.util.List<android.util.Pair<java.lang.Integer, java.lang.Integer>> getChannelMapping();
+ method public java.lang.String getDescription();
+ method public int getDirectionality();
+ method public java.util.List<android.util.Pair<java.lang.Float, java.lang.Float>> getFrequencyResponse();
+ method public int getGroup();
+ method public int getId();
+ method public int getIndexInTheGroup();
+ method public int getLocation();
+ method public float getMaxSpl();
+ method public float getMinSpl();
+ method public android.media.MicrophoneInfo.Coordinate3F getOrientation();
+ method public android.media.MicrophoneInfo.Coordinate3F getPosition();
+ method public float getSensitivity();
+ method public int getType();
+ field public static final int CHANNEL_MAPPING_DIRECT = 1; // 0x1
+ field public static final int CHANNEL_MAPPING_PROCESSED = 2; // 0x2
+ field public static final int DIRECTIONALITY_BI_DIRECTIONAL = 2; // 0x2
+ field public static final int DIRECTIONALITY_CARDIOID = 3; // 0x3
+ field public static final int DIRECTIONALITY_HYPER_CARDIOID = 4; // 0x4
+ field public static final int DIRECTIONALITY_OMNI = 1; // 0x1
+ field public static final int DIRECTIONALITY_SUPER_CARDIOID = 5; // 0x5
+ field public static final int DIRECTIONALITY_UNKNOW = 0; // 0x0
+ field public static final int LOCATION_MAINBODY = 1; // 0x1
+ field public static final int LOCATION_MAINBODY_MOVABLE = 2; // 0x2
+ field public static final int LOCATION_PERIPHERAL = 3; // 0x3
+ field public static final int LOCATION_UNKNOWN = 0; // 0x0
+ }
+
+ public class MicrophoneInfo.Coordinate3F {
+ field public final float x;
+ field public final float y;
+ field public final float z;
+ }
+
public final class NotProvisionedException extends android.media.MediaDrmException {
ctor public NotProvisionedException(java.lang.String);
}
@@ -25401,7 +25447,7 @@
public final class MidiInputPort extends android.media.midi.MidiReceiver implements java.io.Closeable {
method public void close() throws java.io.IOException;
- method public final int getPortNumber();
+ method public int getPortNumber();
method public void onSend(byte[], int, int, long) throws java.io.IOException;
}
@@ -25426,7 +25472,7 @@
public final class MidiOutputPort extends android.media.midi.MidiSender implements java.io.Closeable {
method public void close() throws java.io.IOException;
- method public final int getPortNumber();
+ method public int getPortNumber();
method public void onConnect(android.media.midi.MidiReceiver);
method public void onDisconnect(android.media.midi.MidiReceiver);
}
@@ -25701,7 +25747,7 @@
package android.media.tv {
public final class TvContentRating {
- method public final boolean contains(android.media.tv.TvContentRating);
+ method public boolean contains(android.media.tv.TvContentRating);
method public static android.media.tv.TvContentRating createRating(java.lang.String, java.lang.String, java.lang.String, java.lang.String...);
method public java.lang.String flattenToString();
method public java.lang.String getDomain();
@@ -25751,7 +25797,7 @@
}
public static final class TvContract.Channels implements android.media.tv.TvContract.BaseTvColumns {
- method public static final java.lang.String getVideoResolution(java.lang.String);
+ method public static java.lang.String getVideoResolution(java.lang.String);
field public static final java.lang.String COLUMN_APP_LINK_COLOR = "app_link_color";
field public static final java.lang.String COLUMN_APP_LINK_ICON_URI = "app_link_icon_uri";
field public static final java.lang.String COLUMN_APP_LINK_INTENT_URI = "app_link_intent_uri";
@@ -26276,18 +26322,18 @@
public final class TvTrackInfo implements android.os.Parcelable {
method public int describeContents();
- method public final int getAudioChannelCount();
- method public final int getAudioSampleRate();
- method public final java.lang.CharSequence getDescription();
- method public final android.os.Bundle getExtra();
- method public final java.lang.String getId();
- method public final java.lang.String getLanguage();
- method public final int getType();
- method public final byte getVideoActiveFormatDescription();
- method public final float getVideoFrameRate();
- method public final int getVideoHeight();
- method public final float getVideoPixelAspectRatio();
- method public final int getVideoWidth();
+ method public int getAudioChannelCount();
+ method public int getAudioSampleRate();
+ method public java.lang.CharSequence getDescription();
+ method public android.os.Bundle getExtra();
+ method public java.lang.String getId();
+ method public java.lang.String getLanguage();
+ method public int getType();
+ method public byte getVideoActiveFormatDescription();
+ method public float getVideoFrameRate();
+ method public int getVideoHeight();
+ method public float getVideoPixelAspectRatio();
+ method public int getVideoWidth();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.media.tv.TvTrackInfo> CREATOR;
field public static final int TYPE_AUDIO = 0; // 0x0
@@ -26298,16 +26344,16 @@
public static final class TvTrackInfo.Builder {
ctor public TvTrackInfo.Builder(int, java.lang.String);
method public android.media.tv.TvTrackInfo build();
- method public final android.media.tv.TvTrackInfo.Builder setAudioChannelCount(int);
- method public final android.media.tv.TvTrackInfo.Builder setAudioSampleRate(int);
- method public final android.media.tv.TvTrackInfo.Builder setDescription(java.lang.CharSequence);
- method public final android.media.tv.TvTrackInfo.Builder setExtra(android.os.Bundle);
- method public final android.media.tv.TvTrackInfo.Builder setLanguage(java.lang.String);
- method public final android.media.tv.TvTrackInfo.Builder setVideoActiveFormatDescription(byte);
- method public final android.media.tv.TvTrackInfo.Builder setVideoFrameRate(float);
- method public final android.media.tv.TvTrackInfo.Builder setVideoHeight(int);
- method public final android.media.tv.TvTrackInfo.Builder setVideoPixelAspectRatio(float);
- method public final android.media.tv.TvTrackInfo.Builder setVideoWidth(int);
+ method public android.media.tv.TvTrackInfo.Builder setAudioChannelCount(int);
+ method public android.media.tv.TvTrackInfo.Builder setAudioSampleRate(int);
+ method public android.media.tv.TvTrackInfo.Builder setDescription(java.lang.CharSequence);
+ method public android.media.tv.TvTrackInfo.Builder setExtra(android.os.Bundle);
+ method public android.media.tv.TvTrackInfo.Builder setLanguage(java.lang.String);
+ method public android.media.tv.TvTrackInfo.Builder setVideoActiveFormatDescription(byte);
+ method public android.media.tv.TvTrackInfo.Builder setVideoFrameRate(float);
+ method public android.media.tv.TvTrackInfo.Builder setVideoHeight(int);
+ method public android.media.tv.TvTrackInfo.Builder setVideoPixelAspectRatio(float);
+ method public android.media.tv.TvTrackInfo.Builder setVideoWidth(int);
}
public class TvView extends android.view.ViewGroup {
@@ -26538,34 +26584,34 @@
}
public final class MtpObjectInfo {
- method public final int getAssociationDesc();
- method public final int getAssociationType();
- method public final int getCompressedSize();
- method public final long getCompressedSizeLong();
- method public final long getDateCreated();
- method public final long getDateModified();
- method public final int getFormat();
- method public final int getImagePixDepth();
- method public final long getImagePixDepthLong();
- method public final int getImagePixHeight();
- method public final long getImagePixHeightLong();
- method public final int getImagePixWidth();
- method public final long getImagePixWidthLong();
- method public final java.lang.String getKeywords();
- method public final java.lang.String getName();
- method public final int getObjectHandle();
- method public final int getParent();
- method public final int getProtectionStatus();
- method public final int getSequenceNumber();
- method public final long getSequenceNumberLong();
- method public final int getStorageId();
- method public final int getThumbCompressedSize();
- method public final long getThumbCompressedSizeLong();
- method public final int getThumbFormat();
- method public final int getThumbPixHeight();
- method public final long getThumbPixHeightLong();
- method public final int getThumbPixWidth();
- method public final long getThumbPixWidthLong();
+ method public int getAssociationDesc();
+ method public int getAssociationType();
+ method public int getCompressedSize();
+ method public long getCompressedSizeLong();
+ method public long getDateCreated();
+ method public long getDateModified();
+ method public int getFormat();
+ method public int getImagePixDepth();
+ method public long getImagePixDepthLong();
+ method public int getImagePixHeight();
+ method public long getImagePixHeightLong();
+ method public int getImagePixWidth();
+ method public long getImagePixWidthLong();
+ method public java.lang.String getKeywords();
+ method public java.lang.String getName();
+ method public int getObjectHandle();
+ method public int getParent();
+ method public int getProtectionStatus();
+ method public int getSequenceNumber();
+ method public long getSequenceNumberLong();
+ method public int getStorageId();
+ method public int getThumbCompressedSize();
+ method public long getThumbCompressedSizeLong();
+ method public int getThumbFormat();
+ method public int getThumbPixHeight();
+ method public long getThumbPixHeightLong();
+ method public int getThumbPixWidth();
+ method public long getThumbPixWidthLong();
}
public static class MtpObjectInfo.Builder {
@@ -26595,11 +26641,11 @@
}
public final class MtpStorageInfo {
- method public final java.lang.String getDescription();
- method public final long getFreeSpace();
- method public final long getMaxCapacity();
- method public final int getStorageId();
- method public final java.lang.String getVolumeIdentifier();
+ method public java.lang.String getDescription();
+ method public long getFreeSpace();
+ method public long getMaxCapacity();
+ method public int getStorageId();
+ method public java.lang.String getVolumeIdentifier();
}
}
@@ -27032,10 +27078,10 @@
public final class Proxy {
ctor public Proxy();
- method public static final deprecated java.lang.String getDefaultHost();
- method public static final deprecated int getDefaultPort();
- method public static final deprecated java.lang.String getHost(android.content.Context);
- method public static final deprecated int getPort(android.content.Context);
+ method public static deprecated java.lang.String getDefaultHost();
+ method public static deprecated int getDefaultPort();
+ method public static deprecated java.lang.String getHost(android.content.Context);
+ method public static deprecated int getPort(android.content.Context);
field public static final deprecated java.lang.String EXTRA_PROXY_INFO = "android.intent.extra.PROXY_INFO";
field public static final java.lang.String PROXY_CHANGE_ACTION = "android.intent.action.PROXY_CHANGE";
}
@@ -32062,9 +32108,9 @@
method public static void dumpHprofData(java.lang.String) throws java.io.IOException;
method public static boolean dumpService(java.lang.String, java.io.FileDescriptor, java.lang.String[]);
method public static void enableEmulatorTraceOutput();
- method public static final int getBinderDeathObjectCount();
- method public static final int getBinderLocalObjectCount();
- method public static final int getBinderProxyObjectCount();
+ method public static int getBinderDeathObjectCount();
+ method public static int getBinderLocalObjectCount();
+ method public static int getBinderProxyObjectCount();
method public static int getBinderReceivedTransactions();
method public static int getBinderSentTransactions();
method public static deprecated int getGlobalAllocCount();
@@ -32473,114 +32519,114 @@
}
public final class Parcel {
- method public final void appendFrom(android.os.Parcel, int, int);
- method public final android.os.IBinder[] createBinderArray();
- method public final java.util.ArrayList<android.os.IBinder> createBinderArrayList();
- method public final boolean[] createBooleanArray();
- method public final byte[] createByteArray();
- method public final char[] createCharArray();
- method public final double[] createDoubleArray();
- method public final float[] createFloatArray();
- method public final int[] createIntArray();
- method public final long[] createLongArray();
- method public final java.lang.String[] createStringArray();
- method public final java.util.ArrayList<java.lang.String> createStringArrayList();
- method public final <T> T[] createTypedArray(android.os.Parcelable.Creator<T>);
- method public final <T> java.util.ArrayList<T> createTypedArrayList(android.os.Parcelable.Creator<T>);
- method public final int dataAvail();
- method public final int dataCapacity();
- method public final int dataPosition();
- method public final int dataSize();
- method public final void enforceInterface(java.lang.String);
- method public final boolean hasFileDescriptors();
- method public final byte[] marshall();
+ method public void appendFrom(android.os.Parcel, int, int);
+ method public android.os.IBinder[] createBinderArray();
+ method public java.util.ArrayList<android.os.IBinder> createBinderArrayList();
+ method public boolean[] createBooleanArray();
+ method public byte[] createByteArray();
+ method public char[] createCharArray();
+ method public double[] createDoubleArray();
+ method public float[] createFloatArray();
+ method public int[] createIntArray();
+ method public long[] createLongArray();
+ method public java.lang.String[] createStringArray();
+ method public java.util.ArrayList<java.lang.String> createStringArrayList();
+ method public <T> T[] createTypedArray(android.os.Parcelable.Creator<T>);
+ method public <T> java.util.ArrayList<T> createTypedArrayList(android.os.Parcelable.Creator<T>);
+ method public int dataAvail();
+ method public int dataCapacity();
+ method public int dataPosition();
+ method public int dataSize();
+ method public void enforceInterface(java.lang.String);
+ method public boolean hasFileDescriptors();
+ method public byte[] marshall();
method public static android.os.Parcel obtain();
- method public final java.lang.Object[] readArray(java.lang.ClassLoader);
- method public final java.util.ArrayList readArrayList(java.lang.ClassLoader);
- method public final void readBinderArray(android.os.IBinder[]);
- method public final void readBinderList(java.util.List<android.os.IBinder>);
- method public final void readBooleanArray(boolean[]);
- method public final android.os.Bundle readBundle();
- method public final android.os.Bundle readBundle(java.lang.ClassLoader);
- method public final byte readByte();
- method public final void readByteArray(byte[]);
- method public final void readCharArray(char[]);
- method public final double readDouble();
- method public final void readDoubleArray(double[]);
- method public final void readException();
- method public final void readException(int, java.lang.String);
- method public final android.os.ParcelFileDescriptor readFileDescriptor();
- method public final float readFloat();
- method public final void readFloatArray(float[]);
- method public final java.util.HashMap readHashMap(java.lang.ClassLoader);
- method public final int readInt();
- method public final void readIntArray(int[]);
- method public final void readList(java.util.List, java.lang.ClassLoader);
- method public final long readLong();
- method public final void readLongArray(long[]);
- method public final void readMap(java.util.Map, java.lang.ClassLoader);
- method public final <T extends android.os.Parcelable> T readParcelable(java.lang.ClassLoader);
- method public final android.os.Parcelable[] readParcelableArray(java.lang.ClassLoader);
- method public final android.os.PersistableBundle readPersistableBundle();
- method public final android.os.PersistableBundle readPersistableBundle(java.lang.ClassLoader);
- method public final java.io.Serializable readSerializable();
- method public final android.util.Size readSize();
- method public final android.util.SizeF readSizeF();
- method public final android.util.SparseArray readSparseArray(java.lang.ClassLoader);
- method public final android.util.SparseBooleanArray readSparseBooleanArray();
- method public final java.lang.String readString();
- method public final void readStringArray(java.lang.String[]);
- method public final void readStringList(java.util.List<java.lang.String>);
- method public final android.os.IBinder readStrongBinder();
- method public final <T> void readTypedArray(T[], android.os.Parcelable.Creator<T>);
- method public final <T> void readTypedList(java.util.List<T>, android.os.Parcelable.Creator<T>);
- method public final <T> T readTypedObject(android.os.Parcelable.Creator<T>);
- method public final java.lang.Object readValue(java.lang.ClassLoader);
- method public final void recycle();
- method public final void setDataCapacity(int);
- method public final void setDataPosition(int);
- method public final void setDataSize(int);
- method public final void unmarshall(byte[], int, int);
- method public final void writeArray(java.lang.Object[]);
- method public final void writeBinderArray(android.os.IBinder[]);
- method public final void writeBinderList(java.util.List<android.os.IBinder>);
- method public final void writeBooleanArray(boolean[]);
- method public final void writeBundle(android.os.Bundle);
- method public final void writeByte(byte);
- method public final void writeByteArray(byte[]);
- method public final void writeByteArray(byte[], int, int);
- method public final void writeCharArray(char[]);
- method public final void writeDouble(double);
- method public final void writeDoubleArray(double[]);
- method public final void writeException(java.lang.Exception);
- method public final void writeFileDescriptor(java.io.FileDescriptor);
- method public final void writeFloat(float);
- method public final void writeFloatArray(float[]);
- method public final void writeInt(int);
- method public final void writeIntArray(int[]);
- method public final void writeInterfaceToken(java.lang.String);
- method public final void writeList(java.util.List);
- method public final void writeLong(long);
- method public final void writeLongArray(long[]);
- method public final void writeMap(java.util.Map);
- method public final void writeNoException();
- method public final void writeParcelable(android.os.Parcelable, int);
- method public final <T extends android.os.Parcelable> void writeParcelableArray(T[], int);
- method public final void writePersistableBundle(android.os.PersistableBundle);
- method public final void writeSerializable(java.io.Serializable);
- method public final void writeSize(android.util.Size);
- method public final void writeSizeF(android.util.SizeF);
- method public final void writeSparseArray(android.util.SparseArray<java.lang.Object>);
- method public final void writeSparseBooleanArray(android.util.SparseBooleanArray);
- method public final void writeString(java.lang.String);
- method public final void writeStringArray(java.lang.String[]);
- method public final void writeStringList(java.util.List<java.lang.String>);
- method public final void writeStrongBinder(android.os.IBinder);
- method public final void writeStrongInterface(android.os.IInterface);
- method public final <T extends android.os.Parcelable> void writeTypedArray(T[], int);
- method public final <T extends android.os.Parcelable> void writeTypedList(java.util.List<T>);
- method public final <T extends android.os.Parcelable> void writeTypedObject(T, int);
- method public final void writeValue(java.lang.Object);
+ method public java.lang.Object[] readArray(java.lang.ClassLoader);
+ method public java.util.ArrayList readArrayList(java.lang.ClassLoader);
+ method public void readBinderArray(android.os.IBinder[]);
+ method public void readBinderList(java.util.List<android.os.IBinder>);
+ method public void readBooleanArray(boolean[]);
+ method public android.os.Bundle readBundle();
+ method public android.os.Bundle readBundle(java.lang.ClassLoader);
+ method public byte readByte();
+ method public void readByteArray(byte[]);
+ method public void readCharArray(char[]);
+ method public double readDouble();
+ method public void readDoubleArray(double[]);
+ method public void readException();
+ method public void readException(int, java.lang.String);
+ method public android.os.ParcelFileDescriptor readFileDescriptor();
+ method public float readFloat();
+ method public void readFloatArray(float[]);
+ method public java.util.HashMap readHashMap(java.lang.ClassLoader);
+ method public int readInt();
+ method public void readIntArray(int[]);
+ method public void readList(java.util.List, java.lang.ClassLoader);
+ method public long readLong();
+ method public void readLongArray(long[]);
+ method public void readMap(java.util.Map, java.lang.ClassLoader);
+ method public <T extends android.os.Parcelable> T readParcelable(java.lang.ClassLoader);
+ method public android.os.Parcelable[] readParcelableArray(java.lang.ClassLoader);
+ method public android.os.PersistableBundle readPersistableBundle();
+ method public android.os.PersistableBundle readPersistableBundle(java.lang.ClassLoader);
+ method public java.io.Serializable readSerializable();
+ method public android.util.Size readSize();
+ method public android.util.SizeF readSizeF();
+ method public android.util.SparseArray readSparseArray(java.lang.ClassLoader);
+ method public android.util.SparseBooleanArray readSparseBooleanArray();
+ method public java.lang.String readString();
+ method public void readStringArray(java.lang.String[]);
+ method public void readStringList(java.util.List<java.lang.String>);
+ method public android.os.IBinder readStrongBinder();
+ method public <T> void readTypedArray(T[], android.os.Parcelable.Creator<T>);
+ method public <T> void readTypedList(java.util.List<T>, android.os.Parcelable.Creator<T>);
+ method public <T> T readTypedObject(android.os.Parcelable.Creator<T>);
+ method public java.lang.Object readValue(java.lang.ClassLoader);
+ method public void recycle();
+ method public void setDataCapacity(int);
+ method public void setDataPosition(int);
+ method public void setDataSize(int);
+ method public void unmarshall(byte[], int, int);
+ method public void writeArray(java.lang.Object[]);
+ method public void writeBinderArray(android.os.IBinder[]);
+ method public void writeBinderList(java.util.List<android.os.IBinder>);
+ method public void writeBooleanArray(boolean[]);
+ method public void writeBundle(android.os.Bundle);
+ method public void writeByte(byte);
+ method public void writeByteArray(byte[]);
+ method public void writeByteArray(byte[], int, int);
+ method public void writeCharArray(char[]);
+ method public void writeDouble(double);
+ method public void writeDoubleArray(double[]);
+ method public void writeException(java.lang.Exception);
+ method public void writeFileDescriptor(java.io.FileDescriptor);
+ method public void writeFloat(float);
+ method public void writeFloatArray(float[]);
+ method public void writeInt(int);
+ method public void writeIntArray(int[]);
+ method public void writeInterfaceToken(java.lang.String);
+ method public void writeList(java.util.List);
+ method public void writeLong(long);
+ method public void writeLongArray(long[]);
+ method public void writeMap(java.util.Map);
+ method public void writeNoException();
+ method public void writeParcelable(android.os.Parcelable, int);
+ method public <T extends android.os.Parcelable> void writeParcelableArray(T[], int);
+ method public void writePersistableBundle(android.os.PersistableBundle);
+ method public void writeSerializable(java.io.Serializable);
+ method public void writeSize(android.util.Size);
+ method public void writeSizeF(android.util.SizeF);
+ method public void writeSparseArray(android.util.SparseArray<java.lang.Object>);
+ method public void writeSparseBooleanArray(android.util.SparseBooleanArray);
+ method public void writeString(java.lang.String);
+ method public void writeStringArray(java.lang.String[]);
+ method public void writeStringList(java.util.List<java.lang.String>);
+ method public void writeStrongBinder(android.os.IBinder);
+ method public void writeStrongInterface(android.os.IInterface);
+ method public <T extends android.os.Parcelable> void writeTypedArray(T[], int);
+ method public <T extends android.os.Parcelable> void writeTypedList(java.util.List<T>);
+ method public <T extends android.os.Parcelable> void writeTypedObject(T, int);
+ method public void writeValue(java.lang.Object);
field public static final android.os.Parcelable.Creator<java.lang.String> STRING_CREATOR;
}
@@ -34234,7 +34280,7 @@
}
public static final class CalendarContract.Attendees implements android.provider.BaseColumns android.provider.CalendarContract.AttendeesColumns android.provider.CalendarContract.EventsColumns {
- method public static final android.database.Cursor query(android.content.ContentResolver, long, java.lang.String[]);
+ method public static android.database.Cursor query(android.content.ContentResolver, long, java.lang.String[]);
field public static final android.net.Uri CONTENT_URI;
}
@@ -34363,7 +34409,7 @@
}
public static final class CalendarContract.EventDays implements android.provider.CalendarContract.EventDaysColumns {
- method public static final android.database.Cursor query(android.content.ContentResolver, int, int, java.lang.String[]);
+ method public static android.database.Cursor query(android.content.ContentResolver, int, int, java.lang.String[]);
field public static final android.net.Uri CONTENT_URI;
}
@@ -34456,8 +34502,8 @@
}
public static final class CalendarContract.Instances implements android.provider.BaseColumns android.provider.CalendarContract.CalendarColumns android.provider.CalendarContract.EventsColumns {
- method public static final android.database.Cursor query(android.content.ContentResolver, java.lang.String[], long, long);
- method public static final android.database.Cursor query(android.content.ContentResolver, java.lang.String[], long, long, java.lang.String);
+ method public static android.database.Cursor query(android.content.ContentResolver, java.lang.String[], long, long);
+ method public static android.database.Cursor query(android.content.ContentResolver, java.lang.String[], long, long, java.lang.String);
field public static final java.lang.String BEGIN = "begin";
field public static final android.net.Uri CONTENT_BY_DAY_URI;
field public static final android.net.Uri CONTENT_SEARCH_BY_DAY_URI;
@@ -34472,7 +34518,7 @@
}
public static final class CalendarContract.Reminders implements android.provider.BaseColumns android.provider.CalendarContract.EventsColumns android.provider.CalendarContract.RemindersColumns {
- method public static final android.database.Cursor query(android.content.ContentResolver, long, java.lang.String[]);
+ method public static android.database.Cursor query(android.content.ContentResolver, long, java.lang.String[]);
field public static final android.net.Uri CONTENT_URI;
}
@@ -34581,7 +34627,7 @@
method public static deprecated java.lang.Object decodeImProtocol(java.lang.String);
method public static deprecated java.lang.String encodeCustomImProtocol(java.lang.String);
method public static deprecated java.lang.String encodePredefinedImProtocol(int);
- method public static final deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, int, java.lang.CharSequence);
+ method public static deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, int, java.lang.CharSequence);
field public static final deprecated java.lang.String CONTENT_EMAIL_ITEM_TYPE = "vnd.android.cursor.item/email";
field public static final deprecated java.lang.String CONTENT_EMAIL_TYPE = "vnd.android.cursor.dir/email";
field public static final deprecated android.net.Uri CONTENT_EMAIL_URI;
@@ -34731,7 +34777,7 @@
}
public static final deprecated class Contacts.Organizations implements android.provider.BaseColumns android.provider.Contacts.OrganizationColumns {
- method public static final deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence);
+ method public static deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence);
field public static final deprecated java.lang.String CONTENT_DIRECTORY = "organizations";
field public static final deprecated android.net.Uri CONTENT_URI;
field public static final deprecated java.lang.String DEFAULT_SORT_ORDER = "company, title, isprimary ASC";
@@ -34788,8 +34834,8 @@
}
public static final deprecated class Contacts.Phones implements android.provider.BaseColumns android.provider.Contacts.PeopleColumns android.provider.Contacts.PhonesColumns {
- method public static final deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence, java.lang.CharSequence[]);
- method public static final deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence);
+ method public static deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence, java.lang.CharSequence[]);
+ method public static deprecated java.lang.CharSequence getDisplayLabel(android.content.Context, int, java.lang.CharSequence);
field public static final deprecated android.net.Uri CONTENT_FILTER_URL;
field public static final deprecated java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/phone";
field public static final deprecated java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/phone";
@@ -34929,8 +34975,8 @@
}
public static final class ContactsContract.CommonDataKinds.Email implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String ADDRESS = "data1";
field public static final android.net.Uri CONTENT_FILTER_URI;
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/email_v2";
@@ -34950,7 +34996,7 @@
}
public static final class ContactsContract.CommonDataKinds.Event implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
method public static int getTypeResource(java.lang.Integer);
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/contact_event";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX = "android.provider.extra.ADDRESS_BOOK_INDEX";
@@ -34981,10 +35027,10 @@
}
public static final class ContactsContract.CommonDataKinds.Im implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getProtocolLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getProtocolLabelResource(int);
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getProtocolLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getProtocolLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/im";
field public static final java.lang.String CUSTOM_PROTOCOL = "data6";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX = "android.provider.extra.ADDRESS_BOOK_INDEX";
@@ -35029,8 +35075,8 @@
}
public static final class ContactsContract.CommonDataKinds.Organization implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String COMPANY = "data1";
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/organization";
field public static final java.lang.String DEPARTMENT = "data5";
@@ -35048,8 +35094,8 @@
}
public static final class ContactsContract.CommonDataKinds.Phone implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final android.net.Uri CONTENT_FILTER_URI;
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/phone_v2";
field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/phone_v2";
@@ -35094,8 +35140,8 @@
}
public static final class ContactsContract.CommonDataKinds.Relation implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/relation";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX = "android.provider.extra.ADDRESS_BOOK_INDEX";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX_COUNTS = "android.provider.extra.ADDRESS_BOOK_INDEX_COUNTS";
@@ -35118,8 +35164,8 @@
}
public static final class ContactsContract.CommonDataKinds.SipAddress implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/sip_address";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX = "android.provider.extra.ADDRESS_BOOK_INDEX";
field public static final java.lang.String EXTRA_ADDRESS_BOOK_INDEX_COUNTS = "android.provider.extra.ADDRESS_BOOK_INDEX_COUNTS";
@@ -35149,8 +35195,8 @@
}
public static final class ContactsContract.CommonDataKinds.StructuredPostal implements android.provider.ContactsContract.CommonDataKinds.CommonColumns android.provider.ContactsContract.DataColumnsWithJoins {
- method public static final java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
- method public static final int getTypeLabelResource(int);
+ method public static java.lang.CharSequence getTypeLabel(android.content.res.Resources, int, java.lang.CharSequence);
+ method public static int getTypeLabelResource(int);
field public static final java.lang.String CITY = "data7";
field public static final java.lang.String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/postal-address_v2";
field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/postal-address_v2";
@@ -35977,7 +36023,7 @@
public static final class MediaStore.Audio.Artists.Albums implements android.provider.MediaStore.Audio.AlbumColumns {
ctor public MediaStore.Audio.Artists.Albums();
- method public static final android.net.Uri getContentUri(java.lang.String, long);
+ method public static android.net.Uri getContentUri(java.lang.String, long);
}
public static abstract interface MediaStore.Audio.AudioColumns implements android.provider.MediaStore.MediaColumns {
@@ -36013,7 +36059,7 @@
public static final class MediaStore.Audio.Genres.Members implements android.provider.MediaStore.Audio.AudioColumns {
ctor public MediaStore.Audio.Genres.Members();
- method public static final android.net.Uri getContentUri(java.lang.String, long);
+ method public static android.net.Uri getContentUri(java.lang.String, long);
field public static final java.lang.String AUDIO_ID = "audio_id";
field public static final java.lang.String CONTENT_DIRECTORY = "members";
field public static final java.lang.String DEFAULT_SORT_ORDER = "title_key";
@@ -36049,8 +36095,8 @@
public static final class MediaStore.Audio.Playlists.Members implements android.provider.MediaStore.Audio.AudioColumns {
ctor public MediaStore.Audio.Playlists.Members();
- method public static final android.net.Uri getContentUri(java.lang.String, long);
- method public static final boolean moveItem(android.content.ContentResolver, long, int, int);
+ method public static android.net.Uri getContentUri(java.lang.String, long);
+ method public static boolean moveItem(android.content.ContentResolver, long, int, int);
field public static final java.lang.String AUDIO_ID = "audio_id";
field public static final java.lang.String CONTENT_DIRECTORY = "members";
field public static final java.lang.String DEFAULT_SORT_ORDER = "play_order";
@@ -36073,7 +36119,7 @@
public static final class MediaStore.Files {
ctor public MediaStore.Files();
method public static android.net.Uri getContentUri(java.lang.String);
- method public static final android.net.Uri getContentUri(java.lang.String, long);
+ method public static android.net.Uri getContentUri(java.lang.String, long);
}
public static abstract interface MediaStore.Files.FileColumns implements android.provider.MediaStore.MediaColumns {
@@ -36107,13 +36153,13 @@
public static final class MediaStore.Images.Media implements android.provider.MediaStore.Images.ImageColumns {
ctor public MediaStore.Images.Media();
- method public static final android.graphics.Bitmap getBitmap(android.content.ContentResolver, android.net.Uri) throws java.io.FileNotFoundException, java.io.IOException;
+ method public static android.graphics.Bitmap getBitmap(android.content.ContentResolver, android.net.Uri) throws java.io.FileNotFoundException, java.io.IOException;
method public static android.net.Uri getContentUri(java.lang.String);
- method public static final java.lang.String insertImage(android.content.ContentResolver, java.lang.String, java.lang.String, java.lang.String) throws java.io.FileNotFoundException;
- method public static final java.lang.String insertImage(android.content.ContentResolver, android.graphics.Bitmap, java.lang.String, java.lang.String);
- method public static final android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[]);
- method public static final android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String);
- method public static final android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String);
+ method public static java.lang.String insertImage(android.content.ContentResolver, java.lang.String, java.lang.String, java.lang.String) throws java.io.FileNotFoundException;
+ method public static java.lang.String insertImage(android.content.ContentResolver, android.graphics.Bitmap, java.lang.String, java.lang.String);
+ method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[]);
+ method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String);
+ method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String);
field public static final java.lang.String CONTENT_TYPE = "vnd.android.cursor.dir/image";
field public static final java.lang.String DEFAULT_SORT_ORDER = "bucket_display_name";
field public static final android.net.Uri EXTERNAL_CONTENT_URI;
@@ -36158,7 +36204,7 @@
public static final class MediaStore.Video {
ctor public MediaStore.Video();
- method public static final android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[]);
+ method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[]);
field public static final java.lang.String DEFAULT_SORT_ORDER = "_display_name";
}
@@ -36390,12 +36436,12 @@
method public static long getLong(android.content.ContentResolver, java.lang.String) throws android.provider.Settings.SettingNotFoundException;
method public static java.lang.String getString(android.content.ContentResolver, java.lang.String);
method public static android.net.Uri getUriFor(java.lang.String);
- method public static final deprecated boolean isLocationProviderEnabled(android.content.ContentResolver, java.lang.String);
+ method public static deprecated boolean isLocationProviderEnabled(android.content.ContentResolver, java.lang.String);
method public static boolean putFloat(android.content.ContentResolver, java.lang.String, float);
method public static boolean putInt(android.content.ContentResolver, java.lang.String, int);
method public static boolean putLong(android.content.ContentResolver, java.lang.String, long);
method public static boolean putString(android.content.ContentResolver, java.lang.String, java.lang.String);
- method public static final deprecated void setLocationProviderEnabled(android.content.ContentResolver, java.lang.String, boolean);
+ method public static deprecated void setLocationProviderEnabled(android.content.ContentResolver, java.lang.String, boolean);
field public static final java.lang.String ACCESSIBILITY_DISPLAY_INVERSION_ENABLED = "accessibility_display_inversion_enabled";
field public static final java.lang.String ACCESSIBILITY_ENABLED = "accessibility_enabled";
field public static final deprecated java.lang.String ACCESSIBILITY_SPEAK_PASSWORD = "speak_password";
@@ -40427,12 +40473,12 @@
method public void playDtmfTone(char);
method public void postDialContinue(boolean);
method public void pullExternalCall();
- method public final void putExtras(android.os.Bundle);
+ method public void putExtras(android.os.Bundle);
method public void registerCallback(android.telecom.Call.Callback);
method public void registerCallback(android.telecom.Call.Callback, android.os.Handler);
method public void reject(boolean, java.lang.String);
- method public final void removeExtras(java.util.List<java.lang.String>);
- method public final void removeExtras(java.lang.String...);
+ method public void removeExtras(java.util.List<java.lang.String>);
+ method public void removeExtras(java.lang.String...);
method public void respondToRttRequest(int, boolean);
method public void sendCallEvent(java.lang.String, android.os.Bundle);
method public void sendRttRequest();
@@ -41001,23 +41047,23 @@
public final class RemoteConference {
method public void disconnect();
method public java.util.List<android.telecom.RemoteConnection> getConferenceableConnections();
- method public final int getConnectionCapabilities();
- method public final int getConnectionProperties();
- method public final java.util.List<android.telecom.RemoteConnection> getConnections();
+ method public int getConnectionCapabilities();
+ method public int getConnectionProperties();
+ method public java.util.List<android.telecom.RemoteConnection> getConnections();
method public android.telecom.DisconnectCause getDisconnectCause();
- method public final android.os.Bundle getExtras();
- method public final int getState();
+ method public android.os.Bundle getExtras();
+ method public int getState();
method public void hold();
method public void merge();
method public void playDtmfTone(char);
- method public final void registerCallback(android.telecom.RemoteConference.Callback);
- method public final void registerCallback(android.telecom.RemoteConference.Callback, android.os.Handler);
+ method public void registerCallback(android.telecom.RemoteConference.Callback);
+ method public void registerCallback(android.telecom.RemoteConference.Callback, android.os.Handler);
method public void separate(android.telecom.RemoteConnection);
method public void setCallAudioState(android.telecom.CallAudioState);
method public void stopDtmfTone();
method public void swap();
method public void unhold();
- method public final void unregisterCallback(android.telecom.RemoteConference.Callback);
+ method public void unregisterCallback(android.telecom.RemoteConference.Callback);
}
public static abstract class RemoteConference.Callback {
@@ -41046,10 +41092,10 @@
method public int getConnectionCapabilities();
method public int getConnectionProperties();
method public android.telecom.DisconnectCause getDisconnectCause();
- method public final android.os.Bundle getExtras();
+ method public android.os.Bundle getExtras();
method public int getState();
method public android.telecom.StatusHints getStatusHints();
- method public final android.telecom.RemoteConnection.VideoProvider getVideoProvider();
+ method public android.telecom.RemoteConnection.VideoProvider getVideoProvider();
method public int getVideoState();
method public void hold();
method public boolean isRingbackRequested();
@@ -42502,11 +42548,11 @@
}
public final deprecated class SmsManager {
- method public final deprecated java.util.ArrayList<java.lang.String> divideMessage(java.lang.String);
- method public static final deprecated android.telephony.gsm.SmsManager getDefault();
- method public final deprecated void sendDataMessage(java.lang.String, java.lang.String, short, byte[], android.app.PendingIntent, android.app.PendingIntent);
- method public final deprecated void sendMultipartTextMessage(java.lang.String, java.lang.String, java.util.ArrayList<java.lang.String>, java.util.ArrayList<android.app.PendingIntent>, java.util.ArrayList<android.app.PendingIntent>);
- method public final deprecated void sendTextMessage(java.lang.String, java.lang.String, java.lang.String, android.app.PendingIntent, android.app.PendingIntent);
+ method public deprecated java.util.ArrayList<java.lang.String> divideMessage(java.lang.String);
+ method public static deprecated android.telephony.gsm.SmsManager getDefault();
+ method public deprecated void sendDataMessage(java.lang.String, java.lang.String, short, byte[], android.app.PendingIntent, android.app.PendingIntent);
+ method public deprecated void sendMultipartTextMessage(java.lang.String, java.lang.String, java.util.ArrayList<java.lang.String>, java.util.ArrayList<android.app.PendingIntent>, java.util.ArrayList<android.app.PendingIntent>);
+ method public deprecated void sendTextMessage(java.lang.String, java.lang.String, java.lang.String, android.app.PendingIntent, android.app.PendingIntent);
field public static final deprecated int RESULT_ERROR_GENERIC_FAILURE = 1; // 0x1
field public static final deprecated int RESULT_ERROR_NO_SERVICE = 4; // 0x4
field public static final deprecated int RESULT_ERROR_NULL_PDU = 3; // 0x3
@@ -46565,76 +46611,76 @@
public final class MotionEvent extends android.view.InputEvent implements android.os.Parcelable {
method public static java.lang.String actionToString(int);
- method public final void addBatch(long, float, float, float, float, int);
- method public final void addBatch(long, android.view.MotionEvent.PointerCoords[], int);
+ method public void addBatch(long, float, float, float, float, int);
+ method public void addBatch(long, android.view.MotionEvent.PointerCoords[], int);
method public static int axisFromString(java.lang.String);
method public static java.lang.String axisToString(int);
- method public final int findPointerIndex(int);
- method public final int getAction();
- method public final int getActionButton();
- method public final int getActionIndex();
- method public final int getActionMasked();
- method public final float getAxisValue(int);
- method public final float getAxisValue(int, int);
- method public final int getButtonState();
- method public final int getDeviceId();
- method public final long getDownTime();
- method public final int getEdgeFlags();
- method public final long getEventTime();
- method public final int getFlags();
- method public final float getHistoricalAxisValue(int, int);
- method public final float getHistoricalAxisValue(int, int, int);
- method public final long getHistoricalEventTime(int);
- method public final float getHistoricalOrientation(int);
- method public final float getHistoricalOrientation(int, int);
- method public final void getHistoricalPointerCoords(int, int, android.view.MotionEvent.PointerCoords);
- method public final float getHistoricalPressure(int);
- method public final float getHistoricalPressure(int, int);
- method public final float getHistoricalSize(int);
- method public final float getHistoricalSize(int, int);
- method public final float getHistoricalToolMajor(int);
- method public final float getHistoricalToolMajor(int, int);
- method public final float getHistoricalToolMinor(int);
- method public final float getHistoricalToolMinor(int, int);
- method public final float getHistoricalTouchMajor(int);
- method public final float getHistoricalTouchMajor(int, int);
- method public final float getHistoricalTouchMinor(int);
- method public final float getHistoricalTouchMinor(int, int);
- method public final float getHistoricalX(int);
- method public final float getHistoricalX(int, int);
- method public final float getHistoricalY(int);
- method public final float getHistoricalY(int, int);
- method public final int getHistorySize();
- method public final int getMetaState();
- method public final float getOrientation();
- method public final float getOrientation(int);
- method public final void getPointerCoords(int, android.view.MotionEvent.PointerCoords);
- method public final int getPointerCount();
- method public final int getPointerId(int);
- method public final void getPointerProperties(int, android.view.MotionEvent.PointerProperties);
- method public final float getPressure();
- method public final float getPressure(int);
- method public final float getRawX();
- method public final float getRawY();
- method public final float getSize();
- method public final float getSize(int);
- method public final int getSource();
- method public final float getToolMajor();
- method public final float getToolMajor(int);
- method public final float getToolMinor();
- method public final float getToolMinor(int);
- method public final int getToolType(int);
- method public final float getTouchMajor();
- method public final float getTouchMajor(int);
- method public final float getTouchMinor();
- method public final float getTouchMinor(int);
- method public final float getX();
- method public final float getX(int);
- method public final float getXPrecision();
- method public final float getY();
- method public final float getY(int);
- method public final float getYPrecision();
- method public final boolean isButtonPressed(int);
+ method public int findPointerIndex(int);
+ method public int getAction();
+ method public int getActionButton();
+ method public int getActionIndex();
+ method public int getActionMasked();
+ method public float getAxisValue(int);
+ method public float getAxisValue(int, int);
+ method public int getButtonState();
+ method public int getDeviceId();
+ method public long getDownTime();
+ method public int getEdgeFlags();
+ method public long getEventTime();
+ method public int getFlags();
+ method public float getHistoricalAxisValue(int, int);
+ method public float getHistoricalAxisValue(int, int, int);
+ method public long getHistoricalEventTime(int);
+ method public float getHistoricalOrientation(int);
+ method public float getHistoricalOrientation(int, int);
+ method public void getHistoricalPointerCoords(int, int, android.view.MotionEvent.PointerCoords);
+ method public float getHistoricalPressure(int);
+ method public float getHistoricalPressure(int, int);
+ method public float getHistoricalSize(int);
+ method public float getHistoricalSize(int, int);
+ method public float getHistoricalToolMajor(int);
+ method public float getHistoricalToolMajor(int, int);
+ method public float getHistoricalToolMinor(int);
+ method public float getHistoricalToolMinor(int, int);
+ method public float getHistoricalTouchMajor(int);
+ method public float getHistoricalTouchMajor(int, int);
+ method public float getHistoricalTouchMinor(int);
+ method public float getHistoricalTouchMinor(int, int);
+ method public float getHistoricalX(int);
+ method public float getHistoricalX(int, int);
+ method public float getHistoricalY(int);
+ method public float getHistoricalY(int, int);
+ method public int getHistorySize();
+ method public int getMetaState();
+ method public float getOrientation();
+ method public float getOrientation(int);
+ method public void getPointerCoords(int, android.view.MotionEvent.PointerCoords);
+ method public int getPointerCount();
+ method public int getPointerId(int);
+ method public void getPointerProperties(int, android.view.MotionEvent.PointerProperties);
+ method public float getPressure();
+ method public float getPressure(int);
+ method public float getRawX();
+ method public float getRawY();
+ method public float getSize();
+ method public float getSize(int);
+ method public int getSource();
+ method public float getToolMajor();
+ method public float getToolMajor(int);
+ method public float getToolMinor();
+ method public float getToolMinor(int);
+ method public int getToolType(int);
+ method public float getTouchMajor();
+ method public float getTouchMajor(int);
+ method public float getTouchMinor();
+ method public float getTouchMinor(int);
+ method public float getX();
+ method public float getX(int);
+ method public float getXPrecision();
+ method public float getY();
+ method public float getY(int);
+ method public float getYPrecision();
+ method public boolean isButtonPressed(int);
method public static android.view.MotionEvent obtain(long, long, int, int, android.view.MotionEvent.PointerProperties[], android.view.MotionEvent.PointerCoords[], int, int, float, float, int, int, int, int);
method public static deprecated android.view.MotionEvent obtain(long, long, int, int, int[], android.view.MotionEvent.PointerCoords[], int, float, float, int, int, int, int);
method public static android.view.MotionEvent obtain(long, long, int, float, float, float, float, int, float, float, int, int);
@@ -46642,13 +46688,13 @@
method public static android.view.MotionEvent obtain(long, long, int, float, float, int);
method public static android.view.MotionEvent obtain(android.view.MotionEvent);
method public static android.view.MotionEvent obtainNoHistory(android.view.MotionEvent);
- method public final void offsetLocation(float, float);
- method public final void recycle();
- method public final void setAction(int);
- method public final void setEdgeFlags(int);
- method public final void setLocation(float, float);
- method public final void setSource(int);
- method public final void transform(android.graphics.Matrix);
+ method public void offsetLocation(float, float);
+ method public void recycle();
+ method public void setAction(int);
+ method public void setEdgeFlags(int);
+ method public void setLocation(float, float);
+ method public void setSource(int);
+ method public void transform(android.graphics.Matrix);
method public void writeToParcel(android.os.Parcel, int);
field public static final int ACTION_BUTTON_PRESS = 11; // 0xb
field public static final int ACTION_BUTTON_RELEASE = 12; // 0xc
@@ -47209,7 +47255,9 @@
method public int getNextFocusRightId();
method public int getNextFocusUpId();
method public android.view.View.OnFocusChangeListener getOnFocusChangeListener();
+ method public int getOutlineAmbientShadowColor();
method public android.view.ViewOutlineProvider getOutlineProvider();
+ method public int getOutlineSpotShadowColor();
method public int getOverScrollMode();
method public android.view.ViewOverlay getOverlay();
method public int getPaddingBottom();
@@ -47531,7 +47579,9 @@
method public void setOnScrollChangeListener(android.view.View.OnScrollChangeListener);
method public void setOnSystemUiVisibilityChangeListener(android.view.View.OnSystemUiVisibilityChangeListener);
method public void setOnTouchListener(android.view.View.OnTouchListener);
+ method public void setOutlineAmbientShadowColor(int);
method public void setOutlineProvider(android.view.ViewOutlineProvider);
+ method public void setOutlineSpotShadowColor(int);
method public void setOverScrollMode(int);
method public void setPadding(int, int, int, int);
method public void setPaddingRelative(int, int, int, int);
@@ -48366,9 +48416,9 @@
method public void addOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener);
method public void addOnWindowAttachListener(android.view.ViewTreeObserver.OnWindowAttachListener);
method public void addOnWindowFocusChangeListener(android.view.ViewTreeObserver.OnWindowFocusChangeListener);
- method public final void dispatchOnDraw();
- method public final void dispatchOnGlobalLayout();
- method public final boolean dispatchOnPreDraw();
+ method public void dispatchOnDraw();
+ method public void dispatchOnGlobalLayout();
+ method public boolean dispatchOnPreDraw();
method public boolean isAlive();
method public deprecated void removeGlobalOnLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener);
method public void removeOnDrawListener(android.view.ViewTreeObserver.OnDrawListener);
@@ -50629,7 +50679,7 @@
ctor public URLUtil();
method public static java.lang.String composeSearchUrl(java.lang.String, java.lang.String, java.lang.String);
method public static byte[] decode(byte[]) throws java.lang.IllegalArgumentException;
- method public static final java.lang.String guessFileName(java.lang.String, java.lang.String, java.lang.String);
+ method public static java.lang.String guessFileName(java.lang.String, java.lang.String, java.lang.String);
method public static java.lang.String guessUrl(java.lang.String);
method public static boolean isAboutUrl(java.lang.String);
method public static boolean isAssetUrl(java.lang.String);
@@ -55698,7 +55748,7 @@
}
public static final class Character.UnicodeBlock extends java.lang.Character.Subset {
- method public static final java.lang.Character.UnicodeBlock forName(java.lang.String);
+ method public static java.lang.Character.UnicodeBlock forName(java.lang.String);
method public static java.lang.Character.UnicodeBlock of(char);
method public static java.lang.Character.UnicodeBlock of(int);
field public static final java.lang.Character.UnicodeBlock AEGEAN_NUMBERS;
@@ -55925,7 +55975,7 @@
}
public static final class Character.UnicodeScript extends java.lang.Enum {
- method public static final java.lang.Character.UnicodeScript forName(java.lang.String);
+ method public static java.lang.Character.UnicodeScript forName(java.lang.String);
method public static java.lang.Character.UnicodeScript of(int);
method public static java.lang.Character.UnicodeScript valueOf(java.lang.String);
method public static final java.lang.Character.UnicodeScript[] values();
@@ -58741,8 +58791,8 @@
ctor public URL(java.net.URL, java.lang.String) throws java.net.MalformedURLException;
ctor public URL(java.net.URL, java.lang.String, java.net.URLStreamHandler) throws java.net.MalformedURLException;
method public java.lang.String getAuthority();
- method public final java.lang.Object getContent() throws java.io.IOException;
- method public final java.lang.Object getContent(java.lang.Class[]) throws java.io.IOException;
+ method public java.lang.Object getContent() throws java.io.IOException;
+ method public java.lang.Object getContent(java.lang.Class[]) throws java.io.IOException;
method public int getDefaultPort();
method public java.lang.String getFile();
method public java.lang.String getHost();
@@ -58755,7 +58805,7 @@
method public synchronized int hashCode();
method public java.net.URLConnection openConnection() throws java.io.IOException;
method public java.net.URLConnection openConnection(java.net.Proxy) throws java.io.IOException;
- method public final java.io.InputStream openStream() throws java.io.IOException;
+ method public java.io.InputStream openStream() throws java.io.IOException;
method public boolean sameFile(java.net.URL);
method public static void setURLStreamHandlerFactory(java.net.URLStreamHandlerFactory);
method public java.lang.String toExternalForm();
@@ -63411,13 +63461,13 @@
method public int getOffset();
method public int next();
method public int previous();
- method public static final int primaryOrder(int);
+ method public static int primaryOrder(int);
method public void reset();
- method public static final short secondaryOrder(int);
+ method public static short secondaryOrder(int);
method public void setOffset(int);
method public void setText(java.lang.String);
method public void setText(java.text.CharacterIterator);
- method public static final short tertiaryOrder(int);
+ method public static short tertiaryOrder(int);
field public static final int NULLORDER = -1; // 0xffffffff
}
@@ -64698,7 +64748,7 @@
}
public final class HijrahDate implements java.time.chrono.ChronoLocalDate java.io.Serializable java.time.temporal.Temporal java.time.temporal.TemporalAdjuster {
- method public final java.time.chrono.ChronoLocalDateTime<java.time.chrono.HijrahDate> atTime(java.time.LocalTime);
+ method public java.time.chrono.ChronoLocalDateTime<java.time.chrono.HijrahDate> atTime(java.time.LocalTime);
method public static java.time.chrono.HijrahDate from(java.time.temporal.TemporalAccessor);
method public java.time.chrono.HijrahChronology getChronology();
method public java.time.chrono.HijrahEra getEra();
@@ -64785,7 +64835,7 @@
}
public final class JapaneseDate implements java.time.chrono.ChronoLocalDate java.io.Serializable java.time.temporal.Temporal java.time.temporal.TemporalAdjuster {
- method public final java.time.chrono.ChronoLocalDateTime<java.time.chrono.JapaneseDate> atTime(java.time.LocalTime);
+ method public java.time.chrono.ChronoLocalDateTime<java.time.chrono.JapaneseDate> atTime(java.time.LocalTime);
method public static java.time.chrono.JapaneseDate from(java.time.temporal.TemporalAccessor);
method public java.time.chrono.JapaneseChronology getChronology();
method public java.time.chrono.JapaneseEra getEra();
@@ -64841,7 +64891,7 @@
}
public final class MinguoDate implements java.time.chrono.ChronoLocalDate java.io.Serializable java.time.temporal.Temporal java.time.temporal.TemporalAdjuster {
- method public final java.time.chrono.ChronoLocalDateTime<java.time.chrono.MinguoDate> atTime(java.time.LocalTime);
+ method public java.time.chrono.ChronoLocalDateTime<java.time.chrono.MinguoDate> atTime(java.time.LocalTime);
method public static java.time.chrono.MinguoDate from(java.time.temporal.TemporalAccessor);
method public java.time.chrono.MinguoChronology getChronology();
method public java.time.chrono.MinguoEra getEra();
@@ -64894,7 +64944,7 @@
}
public final class ThaiBuddhistDate implements java.time.chrono.ChronoLocalDate java.io.Serializable java.time.temporal.Temporal java.time.temporal.TemporalAdjuster {
- method public final java.time.chrono.ChronoLocalDateTime<java.time.chrono.ThaiBuddhistDate> atTime(java.time.LocalTime);
+ method public java.time.chrono.ChronoLocalDateTime<java.time.chrono.ThaiBuddhistDate> atTime(java.time.LocalTime);
method public static java.time.chrono.ThaiBuddhistDate from(java.time.temporal.TemporalAccessor);
method public java.time.chrono.ThaiBuddhistChronology getChronology();
method public java.time.chrono.ThaiBuddhistEra getEra();
@@ -64946,8 +64996,8 @@
method public <T> T parse(java.lang.CharSequence, java.time.temporal.TemporalQuery<T>);
method public java.time.temporal.TemporalAccessor parseBest(java.lang.CharSequence, java.time.temporal.TemporalQuery<?>...);
method public java.time.temporal.TemporalAccessor parseUnresolved(java.lang.CharSequence, java.text.ParsePosition);
- method public static final java.time.temporal.TemporalQuery<java.time.Period> parsedExcessDays();
- method public static final java.time.temporal.TemporalQuery<java.lang.Boolean> parsedLeapSecond();
+ method public static java.time.temporal.TemporalQuery<java.time.Period> parsedExcessDays();
+ method public static java.time.temporal.TemporalQuery<java.lang.Boolean> parsedLeapSecond();
method public java.text.Format toFormat();
method public java.text.Format toFormat(java.time.temporal.TemporalQuery<?>);
method public java.time.format.DateTimeFormatter withChronology(java.time.chrono.Chronology);
@@ -66396,15 +66446,15 @@
method public java.lang.String getCountry();
method public static java.util.Locale getDefault();
method public static java.util.Locale getDefault(java.util.Locale.Category);
- method public final java.lang.String getDisplayCountry();
+ method public java.lang.String getDisplayCountry();
method public java.lang.String getDisplayCountry(java.util.Locale);
- method public final java.lang.String getDisplayLanguage();
+ method public java.lang.String getDisplayLanguage();
method public java.lang.String getDisplayLanguage(java.util.Locale);
- method public final java.lang.String getDisplayName();
+ method public java.lang.String getDisplayName();
method public java.lang.String getDisplayName(java.util.Locale);
method public java.lang.String getDisplayScript();
method public java.lang.String getDisplayScript(java.util.Locale);
- method public final java.lang.String getDisplayVariant();
+ method public java.lang.String getDisplayVariant();
method public java.lang.String getDisplayVariant(java.util.Locale);
method public java.lang.String getExtension(char);
method public java.util.Set<java.lang.Character> getExtensionKeys();
@@ -66425,7 +66475,6 @@
method public static synchronized void setDefault(java.util.Locale.Category, java.util.Locale);
method public java.util.Locale stripExtensions();
method public java.lang.String toLanguageTag();
- method public final java.lang.String toString();
field public static final java.util.Locale CANADA;
field public static final java.util.Locale CANADA_FRENCH;
field public static final java.util.Locale CHINA;
diff --git a/api/system-current.txt b/api/system-current.txt
index 034ee30..62cc2a3 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -311,8 +311,10 @@
ctor public InstantAppResolverService();
method public final void attachBaseContext(android.content.Context);
method public final android.os.IBinder onBind(android.content.Intent);
- method public void onGetInstantAppIntentFilter(int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
- method public void onGetInstantAppResolveInfo(int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public deprecated void onGetInstantAppIntentFilter(int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public void onGetInstantAppIntentFilter(android.content.Intent, int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public deprecated void onGetInstantAppResolveInfo(int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
+ method public void onGetInstantAppResolveInfo(android.content.Intent, int[], java.lang.String, android.app.InstantAppResolverService.InstantAppResolutionCallback);
}
public static final class InstantAppResolverService.InstantAppResolutionCallback {
@@ -820,13 +822,24 @@
field public static final java.lang.String ACTION_USER_REMOVED = "android.intent.action.USER_REMOVED";
field public static final java.lang.String ACTION_VOICE_ASSIST = "android.intent.action.VOICE_ASSIST";
field public static final java.lang.String CATEGORY_LEANBACK_SETTINGS = "android.intent.category.LEANBACK_SETTINGS";
+ field public static final java.lang.String EXTRA_CALLING_PACKAGE = "android.intent.extra.CALLING_PACKAGE";
field public static final java.lang.String EXTRA_FORCE_FACTORY_RESET = "android.intent.extra.FORCE_FACTORY_RESET";
+ field public static final java.lang.String EXTRA_INSTANT_APP_ACTION = "android.intent.extra.INSTANT_APP_ACTION";
+ field public static final java.lang.String EXTRA_INSTANT_APP_BUNDLES = "android.intent.extra.INSTANT_APP_BUNDLES";
+ field public static final java.lang.String EXTRA_INSTANT_APP_EXTRAS = "android.intent.extra.INSTANT_APP_EXTRAS";
+ field public static final java.lang.String EXTRA_INSTANT_APP_FAILURE = "android.intent.extra.INSTANT_APP_FAILURE";
+ field public static final java.lang.String EXTRA_INSTANT_APP_HOSTNAME = "android.intent.extra.INSTANT_APP_HOSTNAME";
+ field public static final java.lang.String EXTRA_INSTANT_APP_SUCCESS = "android.intent.extra.INSTANT_APP_SUCCESS";
+ field public static final java.lang.String EXTRA_INSTANT_APP_TOKEN = "android.intent.extra.INSTANT_APP_TOKEN";
+ field public static final java.lang.String EXTRA_LONG_VERSION_CODE = "android.intent.extra.LONG_VERSION_CODE";
field public static final java.lang.String EXTRA_ORIGINATING_UID = "android.intent.extra.ORIGINATING_UID";
field public static final java.lang.String EXTRA_PACKAGES = "android.intent.extra.PACKAGES";
field public static final java.lang.String EXTRA_PERMISSION_NAME = "android.intent.extra.PERMISSION_NAME";
field public static final java.lang.String EXTRA_REASON = "android.intent.extra.REASON";
field public static final java.lang.String EXTRA_REMOTE_CALLBACK = "android.intent.extra.REMOTE_CALLBACK";
field public static final java.lang.String EXTRA_RESULT_NEEDED = "android.intent.extra.RESULT_NEEDED";
+ field public static final java.lang.String EXTRA_UNKNOWN_INSTANT_APP = "android.intent.extra.UNKNOWN_INSTANT_APP";
+ field public static final java.lang.String EXTRA_VERIFICATION_BUNDLE = "android.intent.extra.VERIFICATION_BUNDLE";
}
public class IntentFilter implements android.os.Parcelable {
@@ -839,7 +852,9 @@
package android.content.pm {
public class ApplicationInfo extends android.content.pm.PackageItemInfo implements android.os.Parcelable {
+ method public boolean isInstantApp();
field public java.lang.String credentialProtectedDataDir;
+ field public int targetSandboxVersion;
}
public final class InstantAppInfo implements android.os.Parcelable {
@@ -869,6 +884,7 @@
ctor public InstantAppResolveInfo(android.content.pm.InstantAppResolveInfo.InstantAppDigest, java.lang.String, java.util.List<android.content.pm.InstantAppIntentFilter>, int);
ctor public InstantAppResolveInfo(android.content.pm.InstantAppResolveInfo.InstantAppDigest, java.lang.String, java.util.List<android.content.pm.InstantAppIntentFilter>, long, android.os.Bundle);
ctor public InstantAppResolveInfo(java.lang.String, java.lang.String, java.util.List<android.content.pm.InstantAppIntentFilter>);
+ ctor public InstantAppResolveInfo(android.os.Bundle);
method public int describeContents();
method public byte[] getDigestBytes();
method public int getDigestPrefix();
@@ -877,6 +893,7 @@
method public long getLongVersionCode();
method public java.lang.String getPackageName();
method public deprecated int getVersionCode();
+ method public boolean shouldLetInstallerDecide();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo> CREATOR;
}
@@ -888,6 +905,7 @@
method public int[] getDigestPrefix();
method public void writeToParcel(android.os.Parcel, int);
field public static final android.os.Parcelable.Creator<android.content.pm.InstantAppResolveInfo.InstantAppDigest> CREATOR;
+ field public static final android.content.pm.InstantAppResolveInfo.InstantAppDigest UNDEFINED;
}
public final class IntentFilterVerificationInfo implements android.os.Parcelable {
@@ -1129,11 +1147,14 @@
field public final float batteryLevel;
field public final float brightness;
field public final int colorTemperature;
+ field public final boolean isDefaultBrightnessConfig;
+ field public final boolean isUserSetBrightness;
field public final float lastBrightness;
field public final long[] luxTimestamps;
field public final float[] luxValues;
field public final boolean nightMode;
field public final java.lang.String packageName;
+ field public final float powerBrightnessFactor;
field public final long timeStamp;
}
@@ -2673,10 +2694,10 @@
package android.media.tv {
public final class TvContentRatingSystemInfo implements android.os.Parcelable {
- method public static final android.media.tv.TvContentRatingSystemInfo createTvContentRatingSystemInfo(int, android.content.pm.ApplicationInfo);
+ method public static android.media.tv.TvContentRatingSystemInfo createTvContentRatingSystemInfo(int, android.content.pm.ApplicationInfo);
method public int describeContents();
- method public final android.net.Uri getXmlUri();
- method public final boolean isSystemDefined();
+ method public android.net.Uri getXmlUri();
+ method public boolean isSystemDefined();
method public void writeToParcel(android.os.Parcel, int);
}
@@ -4657,15 +4678,15 @@
}
public final deprecated class Phone {
- method public final void addListener(android.telecom.Phone.Listener);
- method public final boolean canAddCall();
- method public final deprecated android.telecom.AudioState getAudioState();
- method public final android.telecom.CallAudioState getCallAudioState();
- method public final java.util.List<android.telecom.Call> getCalls();
- method public final void removeListener(android.telecom.Phone.Listener);
+ method public void addListener(android.telecom.Phone.Listener);
+ method public boolean canAddCall();
+ method public deprecated android.telecom.AudioState getAudioState();
+ method public android.telecom.CallAudioState getCallAudioState();
+ method public java.util.List<android.telecom.Call> getCalls();
+ method public void removeListener(android.telecom.Phone.Listener);
method public void requestBluetoothAudio(java.lang.String);
- method public final void setAudioRoute(int);
- method public final void setMuted(boolean);
+ method public void setAudioRoute(int);
+ method public void setMuted(boolean);
}
public static abstract class Phone.Listener {
diff --git a/api/system-removed.txt b/api/system-removed.txt
index b63703d..48f43e0 100644
--- a/api/system-removed.txt
+++ b/api/system-removed.txt
@@ -1,13 +1,5 @@
package android.app {
- public abstract deprecated class EphemeralResolverService extends android.app.InstantAppResolverService {
- ctor public EphemeralResolverService();
- method public android.os.Looper getLooper();
- method public abstract deprecated java.util.List<android.content.pm.EphemeralResolveInfo> onEphemeralResolveInfoList(int[], int);
- method public android.content.pm.EphemeralResolveInfo onGetEphemeralIntentFilter(java.lang.String);
- method public java.util.List<android.content.pm.EphemeralResolveInfo> onGetEphemeralResolveInfo(int[]);
- }
-
public class Notification implements android.os.Parcelable {
method public static java.lang.Class<? extends android.app.Notification.Style> getNotificationStyleClass(java.lang.String);
}
@@ -31,10 +23,7 @@
public class Intent implements java.lang.Cloneable android.os.Parcelable {
field public static final deprecated java.lang.String ACTION_DEVICE_INITIALIZATION_WIZARD = "android.intent.action.DEVICE_INITIALIZATION_WIZARD";
- field public static final deprecated java.lang.String ACTION_EPHEMERAL_RESOLVER_SETTINGS = "android.intent.action.EPHEMERAL_RESOLVER_SETTINGS";
- field public static final deprecated java.lang.String ACTION_INSTALL_EPHEMERAL_PACKAGE = "android.intent.action.INSTALL_EPHEMERAL_PACKAGE";
field public static final deprecated java.lang.String ACTION_MASTER_CLEAR = "android.intent.action.MASTER_CLEAR";
- field public static final deprecated java.lang.String ACTION_RESOLVE_EPHEMERAL_PACKAGE = "android.intent.action.RESOLVE_EPHEMERAL_PACKAGE";
field public static final deprecated java.lang.String ACTION_SERVICE_STATE = "android.intent.action.SERVICE_STATE";
field public static final deprecated java.lang.String EXTRA_CDMA_DEFAULT_ROAMING_INDICATOR = "cdmaDefaultRoamingIndicator";
field public static final deprecated java.lang.String EXTRA_CDMA_ROAMING_INDICATOR = "cdmaRoamingIndicator";
@@ -62,45 +51,6 @@
}
-package android.content.pm {
-
- public final deprecated class EphemeralIntentFilter implements android.os.Parcelable {
- ctor public EphemeralIntentFilter(java.lang.String, java.util.List<android.content.IntentFilter>);
- method public int describeContents();
- method public java.util.List<android.content.IntentFilter> getFilters();
- method public java.lang.String getSplitName();
- method public void writeToParcel(android.os.Parcel, int);
- field public static final android.os.Parcelable.Creator<android.content.pm.EphemeralIntentFilter> CREATOR;
- }
-
- public final deprecated class EphemeralResolveInfo implements android.os.Parcelable {
- ctor public deprecated EphemeralResolveInfo(android.net.Uri, java.lang.String, java.util.List<android.content.IntentFilter>);
- ctor public deprecated EphemeralResolveInfo(android.content.pm.EphemeralResolveInfo.EphemeralDigest, java.lang.String, java.util.List<android.content.pm.EphemeralIntentFilter>);
- ctor public EphemeralResolveInfo(android.content.pm.EphemeralResolveInfo.EphemeralDigest, java.lang.String, java.util.List<android.content.pm.EphemeralIntentFilter>, int);
- ctor public EphemeralResolveInfo(java.lang.String, java.lang.String, java.util.List<android.content.pm.EphemeralIntentFilter>);
- method public int describeContents();
- method public byte[] getDigestBytes();
- method public int getDigestPrefix();
- method public deprecated java.util.List<android.content.IntentFilter> getFilters();
- method public java.util.List<android.content.pm.EphemeralIntentFilter> getIntentFilters();
- method public java.lang.String getPackageName();
- method public int getVersionCode();
- method public void writeToParcel(android.os.Parcel, int);
- field public static final android.os.Parcelable.Creator<android.content.pm.EphemeralResolveInfo> CREATOR;
- field public static final java.lang.String SHA_ALGORITHM = "SHA-256";
- }
-
- public static final class EphemeralResolveInfo.EphemeralDigest implements android.os.Parcelable {
- ctor public EphemeralResolveInfo.EphemeralDigest(java.lang.String);
- method public int describeContents();
- method public byte[][] getDigestBytes();
- method public int[] getDigestPrefix();
- method public void writeToParcel(android.os.Parcel, int);
- field public static final android.os.Parcelable.Creator<android.content.pm.EphemeralResolveInfo.EphemeralDigest> CREATOR;
- }
-
-}
-
package android.media.tv {
public final class TvInputManager {
diff --git a/api/test-current.txt b/api/test-current.txt
index d834cf7..9af80e3 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -305,11 +305,14 @@
field public final float batteryLevel;
field public final float brightness;
field public final int colorTemperature;
+ field public final boolean isDefaultBrightnessConfig;
+ field public final boolean isUserSetBrightness;
field public final float lastBrightness;
field public final long[] luxTimestamps;
field public final float[] luxValues;
field public final boolean nightMode;
field public final java.lang.String packageName;
+ field public final float powerBrightnessFactor;
field public final long timeStamp;
}
@@ -995,8 +998,8 @@
}
public final class MotionEvent extends android.view.InputEvent implements android.os.Parcelable {
- method public final void setActionButton(int);
- method public final void setButtonState(int);
+ method public void setActionButton(int);
+ method public void setButtonState(int);
}
public class View implements android.view.accessibility.AccessibilityEventSource android.graphics.drawable.Drawable.Callback android.view.KeyEvent.Callback {
diff --git a/cmds/content/src/com/android/commands/content/Content.java b/cmds/content/src/com/android/commands/content/Content.java
index f75678b..6e0bd3a 100644
--- a/cmds/content/src/com/android/commands/content/Content.java
+++ b/cmds/content/src/com/android/commands/content/Content.java
@@ -26,6 +26,7 @@
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
+import android.os.FileUtils;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.Process;
@@ -34,6 +35,7 @@
import libcore.io.Streams;
+import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -583,7 +585,7 @@
@Override
public void onExecute(IContentProvider provider) throws Exception {
try (ParcelFileDescriptor fd = provider.openFile(null, mUri, "r", null, null)) {
- Streams.copy(new FileInputStream(fd.getFileDescriptor()), System.out);
+ FileUtils.copy(fd.getFileDescriptor(), FileDescriptor.out);
}
}
}
@@ -596,7 +598,7 @@
@Override
public void onExecute(IContentProvider provider) throws Exception {
try (ParcelFileDescriptor fd = provider.openFile(null, mUri, "w", null, null)) {
- Streams.copy(System.in, new FileOutputStream(fd.getFileDescriptor()));
+ FileUtils.copy(FileDescriptor.in, fd.getFileDescriptor());
}
}
}
diff --git a/cmds/statsd/Android.mk b/cmds/statsd/Android.mk
index eabbb96..76dbd6a 100644
--- a/cmds/statsd/Android.mk
+++ b/cmds/statsd/Android.mk
@@ -165,6 +165,7 @@
LOCAL_SRC_FILES := \
$(statsd_common_src) \
+ tests/dimension_test.cpp \
tests/AnomalyMonitor_test.cpp \
tests/anomaly/AnomalyTracker_test.cpp \
tests/ConfigManager_test.cpp \
@@ -190,7 +191,8 @@
tests/e2e/WakelockDuration_e2e_test.cpp \
tests/e2e/MetricConditionLink_e2e_test.cpp \
tests/e2e/Attribution_e2e_test.cpp \
- tests/e2e/GaugeMetric_e2e_test.cpp
+ tests/e2e/GaugeMetric_e2e_test.cpp \
+ tests/e2e/DimensionInCondition_e2e_test.cpp
LOCAL_STATIC_LIBRARIES := \
$(statsd_common_static_libraries) \
diff --git a/cmds/statsd/src/HashableDimensionKey.cpp b/cmds/statsd/src/HashableDimensionKey.cpp
index 857a6dd..f0eaeff 100644
--- a/cmds/statsd/src/HashableDimensionKey.cpp
+++ b/cmds/statsd/src/HashableDimensionKey.cpp
@@ -67,12 +67,16 @@
return hashDimensionsValue(0, value);
}
+android::hash_t hashMetricDimensionKey(int64_t seed, const MetricDimensionKey& dimensionKey) {
+ android::hash_t hash = seed;
+ hash = android::JenkinsHashMix(hash, std::hash<MetricDimensionKey>{}(dimensionKey));
+ return JenkinsHashWhiten(hash);
+}
+
using std::string;
string HashableDimensionKey::toString() const {
- string flattened;
- DimensionsValueToString(getDimensionsValue(), &flattened);
- return flattened;
+ return DimensionsValueToString(getDimensionsValue());
}
bool EqualsTo(const DimensionsValue& s1, const DimensionsValue& s2) {
@@ -162,6 +166,22 @@
return LessThan(getDimensionsValue(), that.getDimensionsValue());
};
+string MetricDimensionKey::toString() const {
+ string flattened = mDimensionKeyInWhat.toString();
+ flattened += mDimensionKeyInCondition.toString();
+ return flattened;
+}
+
+bool MetricDimensionKey::operator==(const MetricDimensionKey& that) const {
+ return mDimensionKeyInWhat == that.getDimensionKeyInWhat() &&
+ mDimensionKeyInCondition == that.getDimensionKeyInCondition();
+};
+
+bool MetricDimensionKey::operator<(const MetricDimensionKey& that) const {
+ return toString().compare(that.toString()) < 0;
+};
+
+
} // namespace statsd
} // namespace os
} // namespace android
\ No newline at end of file
diff --git a/cmds/statsd/src/HashableDimensionKey.h b/cmds/statsd/src/HashableDimensionKey.h
index 85c317f..a31d7a6 100644
--- a/cmds/statsd/src/HashableDimensionKey.h
+++ b/cmds/statsd/src/HashableDimensionKey.h
@@ -41,6 +41,10 @@
return mDimensionsValue;
}
+ inline DimensionsValue* getMutableDimensionsValue() {
+ return &mDimensionsValue;
+ }
+
bool operator==(const HashableDimensionKey& that) const;
bool operator<(const HashableDimensionKey& that) const;
@@ -53,8 +57,52 @@
DimensionsValue mDimensionsValue;
};
+class MetricDimensionKey {
+ public:
+ explicit MetricDimensionKey(const HashableDimensionKey& dimensionKeyInWhat,
+ const HashableDimensionKey& dimensionKeyInCondition)
+ : mDimensionKeyInWhat(dimensionKeyInWhat),
+ mDimensionKeyInCondition(dimensionKeyInCondition) {};
+
+ MetricDimensionKey(){};
+
+ MetricDimensionKey(const MetricDimensionKey& that)
+ : mDimensionKeyInWhat(that.getDimensionKeyInWhat()),
+ mDimensionKeyInCondition(that.getDimensionKeyInCondition()) {};
+
+ MetricDimensionKey& operator=(const MetricDimensionKey& from) = default;
+
+ std::string toString() const;
+
+ inline const HashableDimensionKey& getDimensionKeyInWhat() const {
+ return mDimensionKeyInWhat;
+ }
+
+ inline const HashableDimensionKey& getDimensionKeyInCondition() const {
+ return mDimensionKeyInCondition;
+ }
+
+ bool hasDimensionKeyInCondition() const {
+ return mDimensionKeyInCondition.getDimensionsValue().has_field();
+ }
+
+ bool operator==(const MetricDimensionKey& that) const;
+
+ bool operator<(const MetricDimensionKey& that) const;
+
+ inline const char* c_str() const {
+ return toString().c_str();
+ }
+ private:
+ HashableDimensionKey mDimensionKeyInWhat;
+ HashableDimensionKey mDimensionKeyInCondition;
+};
+
+bool compareDimensionsValue(const DimensionsValue& s1, const DimensionsValue& s2);
+
android::hash_t hashDimensionsValue(int64_t seed, const DimensionsValue& value);
android::hash_t hashDimensionsValue(const DimensionsValue& value);
+android::hash_t hashMetricDimensionKey(int64_t see, const MetricDimensionKey& dimensionKey);
} // namespace statsd
} // namespace os
@@ -63,6 +111,7 @@
namespace std {
using android::os::statsd::HashableDimensionKey;
+using android::os::statsd::MetricDimensionKey;
template <>
struct hash<HashableDimensionKey> {
@@ -71,4 +120,14 @@
}
};
-} // namespace std
+template <>
+struct hash<MetricDimensionKey> {
+ std::size_t operator()(const MetricDimensionKey& key) const {
+ android::hash_t hash = hashDimensionsValue(
+ key.getDimensionKeyInWhat().getDimensionsValue());
+ hash = android::JenkinsHashMix(hash,
+ hashDimensionsValue(key.getDimensionKeyInCondition().getDimensionsValue()));
+ return android::JenkinsHashWhiten(hash);
+ }
+};
+} // namespace std
\ No newline at end of file
diff --git a/cmds/statsd/src/StatsLogProcessor.h b/cmds/statsd/src/StatsLogProcessor.h
index c19ff63..7642aafa 100644
--- a/cmds/statsd/src/StatsLogProcessor.h
+++ b/cmds/statsd/src/StatsLogProcessor.h
@@ -104,7 +104,10 @@
FRIEND_TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks);
FRIEND_TEST(AttributionE2eTest, TestAttributionMatchAndSlice);
FRIEND_TEST(GaugeMetricE2eTest, TestMultipleFieldsForPushedEvent);
-
+ FRIEND_TEST(DimensionInConditionE2eTest, TestCountMetricNoLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestCountMetricWithLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetricNoLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetricWithLink);
};
} // namespace statsd
diff --git a/cmds/statsd/src/anomaly/AnomalyTracker.cpp b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
index ded6c4c..c84a5b4 100644
--- a/cmds/statsd/src/anomaly/AnomalyTracker.cpp
+++ b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
@@ -96,7 +96,7 @@
}
}
-void AnomalyTracker::addPastBucket(const HashableDimensionKey& key, const int64_t& bucketValue,
+void AnomalyTracker::addPastBucket(const MetricDimensionKey& key, const int64_t& bucketValue,
const int64_t& bucketNum) {
flushPastBuckets(bucketNum);
@@ -147,7 +147,7 @@
}
}
-int64_t AnomalyTracker::getPastBucketValue(const HashableDimensionKey& key,
+int64_t AnomalyTracker::getPastBucketValue(const MetricDimensionKey& key,
const int64_t& bucketNum) const {
const auto& bucket = mPastBuckets[index(bucketNum)];
if (bucket == nullptr) {
@@ -157,7 +157,7 @@
return itr == bucket->end() ? 0 : itr->second;
}
-int64_t AnomalyTracker::getSumOverPastBuckets(const HashableDimensionKey& key) const {
+int64_t AnomalyTracker::getSumOverPastBuckets(const MetricDimensionKey& key) const {
const auto& itr = mSumOverPastBuckets.find(key);
if (itr != mSumOverPastBuckets.end()) {
return itr->second;
@@ -165,7 +165,7 @@
return 0;
}
-bool AnomalyTracker::detectAnomaly(const int64_t& currentBucketNum, const HashableDimensionKey& key,
+bool AnomalyTracker::detectAnomaly(const int64_t& currentBucketNum, const MetricDimensionKey& key,
const int64_t& currentBucketValue) {
if (currentBucketNum > mMostRecentBucketNum + 1) {
// TODO: This creates a needless 0 entry in mSumOverPastBuckets. Fix this.
@@ -175,7 +175,7 @@
&& getSumOverPastBuckets(key) + currentBucketValue > mAlert.trigger_if_sum_gt();
}
-void AnomalyTracker::declareAnomaly(const uint64_t& timestampNs, const HashableDimensionKey& key) {
+void AnomalyTracker::declareAnomaly(const uint64_t& timestampNs, const MetricDimensionKey& key) {
// TODO: Why receive timestamp? RefractoryPeriod should always be based on real time right now.
if (isInRefractoryPeriod(timestampNs, key)) {
VLOG("Skipping anomaly declaration since within refractory period");
@@ -199,14 +199,14 @@
StatsdStats::getInstance().noteAnomalyDeclared(mConfigKey, mAlert.id());
- // TODO: This should also take in the const HashableDimensionKey& key?
+ // TODO: This should also take in the const MetricDimensionKey& key?
android::util::stats_write(android::util::ANOMALY_DETECTED, mConfigKey.GetUid(),
mConfigKey.GetId(), mAlert.id());
}
void AnomalyTracker::detectAndDeclareAnomaly(const uint64_t& timestampNs,
const int64_t& currBucketNum,
- const HashableDimensionKey& key,
+ const MetricDimensionKey& key,
const int64_t& currentBucketValue) {
if (detectAnomaly(currBucketNum, key, currentBucketValue)) {
declareAnomaly(timestampNs, key);
@@ -214,7 +214,7 @@
}
bool AnomalyTracker::isInRefractoryPeriod(const uint64_t& timestampNs,
- const HashableDimensionKey& key) {
+ const MetricDimensionKey& key) {
const auto& it = mRefractoryPeriodEndsSec.find(key);
if (it != mRefractoryPeriodEndsSec.end()) {
if ((timestampNs / NS_PER_SEC) <= it->second) {
@@ -226,7 +226,7 @@
return false;
}
-void AnomalyTracker::informSubscribers(const HashableDimensionKey& key) {
+void AnomalyTracker::informSubscribers(const MetricDimensionKey& key) {
VLOG("informSubscribers called.");
if (mSubscriptions.empty()) {
ALOGE("Attempt to call with no subscribers.");
diff --git a/cmds/statsd/src/anomaly/AnomalyTracker.h b/cmds/statsd/src/anomaly/AnomalyTracker.h
index 472c02c..f01a97f 100644
--- a/cmds/statsd/src/anomaly/AnomalyTracker.h
+++ b/cmds/statsd/src/anomaly/AnomalyTracker.h
@@ -48,19 +48,19 @@
// Adds a bucket.
// Bucket index starts from 0.
void addPastBucket(std::shared_ptr<DimToValMap> bucketValues, const int64_t& bucketNum);
- void addPastBucket(const HashableDimensionKey& key, const int64_t& bucketValue,
+ void addPastBucket(const MetricDimensionKey& key, const int64_t& bucketValue,
const int64_t& bucketNum);
// Returns true if detected anomaly for the existing buckets on one or more dimension keys.
- bool detectAnomaly(const int64_t& currBucketNum, const HashableDimensionKey& key,
+ bool detectAnomaly(const int64_t& currBucketNum, const MetricDimensionKey& key,
const int64_t& currentBucketValue);
// Informs incidentd about the detected alert.
- void declareAnomaly(const uint64_t& timestampNs, const HashableDimensionKey& key);
+ void declareAnomaly(const uint64_t& timestampNs, const MetricDimensionKey& key);
// Detects the alert and informs the incidentd when applicable.
void detectAndDeclareAnomaly(const uint64_t& timestampNs, const int64_t& currBucketNum,
- const HashableDimensionKey& key,
+ const MetricDimensionKey& key,
const int64_t& currentBucketValue);
// Init the AnomalyMonitor which is shared across anomaly trackers.
@@ -69,10 +69,10 @@
}
// Helper function to return the sum value of past buckets at given dimension.
- int64_t getSumOverPastBuckets(const HashableDimensionKey& key) const;
+ int64_t getSumOverPastBuckets(const MetricDimensionKey& key) const;
// Helper function to return the value for a past bucket.
- int64_t getPastBucketValue(const HashableDimensionKey& key, const int64_t& bucketNum) const;
+ int64_t getPastBucketValue(const MetricDimensionKey& key, const int64_t& bucketNum) const;
// Returns the anomaly threshold.
inline int64_t getAnomalyThreshold() const {
@@ -81,7 +81,7 @@
// Returns the refractory period timestamp (in seconds) for the given key.
// If there is no stored refractory period ending timestamp, returns 0.
- uint32_t getRefractoryPeriodEndsSec(const HashableDimensionKey& key) const {
+ uint32_t getRefractoryPeriodEndsSec(const MetricDimensionKey& key) const {
const auto& it = mRefractoryPeriodEndsSec.find(key);
return it != mRefractoryPeriodEndsSec.end() ? it->second : 0;
}
@@ -124,7 +124,7 @@
// declared for that dimension) ends, in seconds. Only anomalies that occur after this period
// ends will be declared.
// Entries may be, but are not guaranteed to be, removed after the period is finished.
- unordered_map<HashableDimensionKey, uint32_t> mRefractoryPeriodEndsSec;
+ unordered_map<MetricDimensionKey, uint32_t> mRefractoryPeriodEndsSec;
void flushPastBuckets(const int64_t& currBucketNum);
@@ -135,7 +135,7 @@
// and remove any items with value 0.
void subtractBucketFromSum(const shared_ptr<DimToValMap>& bucket);
- bool isInRefractoryPeriod(const uint64_t& timestampNs, const HashableDimensionKey& key);
+ bool isInRefractoryPeriod(const uint64_t& timestampNs, const MetricDimensionKey& key);
// Calculates the corresponding bucket index within the circular array.
size_t index(int64_t bucketNum) const;
@@ -144,7 +144,7 @@
virtual void resetStorage();
// Informs the subscribers that an anomaly has occurred.
- void informSubscribers(const HashableDimensionKey& key);
+ void informSubscribers(const MetricDimensionKey& key);
FRIEND_TEST(AnomalyTrackerTest, TestConsecutiveBuckets);
FRIEND_TEST(AnomalyTrackerTest, TestSparseBuckets);
diff --git a/cmds/statsd/src/anomaly/DurationAnomalyTracker.cpp b/cmds/statsd/src/anomaly/DurationAnomalyTracker.cpp
index 7576a38..bbee9fa 100644
--- a/cmds/statsd/src/anomaly/DurationAnomalyTracker.cpp
+++ b/cmds/statsd/src/anomaly/DurationAnomalyTracker.cpp
@@ -37,8 +37,8 @@
if (!mAlarms.empty()) VLOG("AnomalyTracker.resetStorage() called but mAlarms is NOT empty!");
}
-void DurationAnomalyTracker::declareAnomalyIfAlarmExpired(const HashableDimensionKey& dimensionKey,
- const uint64_t& timestampNs) {
+void DurationAnomalyTracker::declareAnomalyIfAlarmExpired(const MetricDimensionKey& dimensionKey,
+ const uint64_t& timestampNs) {
auto itr = mAlarms.find(dimensionKey);
if (itr == mAlarms.end()) {
return;
@@ -51,7 +51,7 @@
}
}
-void DurationAnomalyTracker::startAlarm(const HashableDimensionKey& dimensionKey,
+void DurationAnomalyTracker::startAlarm(const MetricDimensionKey& dimensionKey,
const uint64_t& timestampNs) {
uint32_t timestampSec = static_cast<uint32_t>(timestampNs / NS_PER_SEC);
@@ -66,7 +66,7 @@
}
}
-void DurationAnomalyTracker::stopAlarm(const HashableDimensionKey& dimensionKey) {
+void DurationAnomalyTracker::stopAlarm(const MetricDimensionKey& dimensionKey) {
auto itr = mAlarms.find(dimensionKey);
if (itr != mAlarms.end()) {
mAlarms.erase(dimensionKey);
@@ -77,7 +77,7 @@
}
void DurationAnomalyTracker::stopAllAlarms() {
- std::set<HashableDimensionKey> keys;
+ std::set<MetricDimensionKey> keys;
for (auto itr = mAlarms.begin(); itr != mAlarms.end(); ++itr) {
keys.insert(itr->first);
}
@@ -95,7 +95,7 @@
// seldomly called. The alternative would be having AnomalyAlarms store information about the
// DurationAnomalyTracker and key, but that's a lot of data overhead to speed up something that is
// rarely ever called.
- unordered_map<HashableDimensionKey, sp<const AnomalyAlarm>> matchedAlarms;
+ unordered_map<MetricDimensionKey, sp<const AnomalyAlarm>> matchedAlarms;
for (const auto& kv : mAlarms) {
if (firedAlarms.count(kv.second) > 0) {
matchedAlarms.insert({kv.first, kv.second});
diff --git a/cmds/statsd/src/anomaly/DurationAnomalyTracker.h b/cmds/statsd/src/anomaly/DurationAnomalyTracker.h
index 33e55ab..052fdf57 100644
--- a/cmds/statsd/src/anomaly/DurationAnomalyTracker.h
+++ b/cmds/statsd/src/anomaly/DurationAnomalyTracker.h
@@ -32,10 +32,10 @@
virtual ~DurationAnomalyTracker();
// Starts the alarm at the given timestamp.
- void startAlarm(const HashableDimensionKey& dimensionKey, const uint64_t& eventTime);
+ void startAlarm(const MetricDimensionKey& dimensionKey, const uint64_t& eventTime);
// Stops the alarm.
- void stopAlarm(const HashableDimensionKey& dimensionKey);
+ void stopAlarm(const MetricDimensionKey& dimensionKey);
// Stop all the alarms owned by this tracker.
void stopAllAlarms();
@@ -46,7 +46,7 @@
}
// Declares the anomaly when the alarm expired given the current timestamp.
- void declareAnomalyIfAlarmExpired(const HashableDimensionKey& dimensionKey,
+ void declareAnomalyIfAlarmExpired(const MetricDimensionKey& dimensionKey,
const uint64_t& timestampNs);
// Declares an anomaly for each alarm in firedAlarms that belongs to this DurationAnomalyTracker
@@ -59,7 +59,7 @@
protected:
// The alarms owned by this tracker. The alarm monitor also shares the alarm pointers when they
// are still active.
- std::unordered_map<HashableDimensionKey, sp<const AnomalyAlarm>> mAlarms;
+ std::unordered_map<MetricDimensionKey, sp<const AnomalyAlarm>> mAlarms;
// Anomaly alarm monitor.
sp<AnomalyMonitor> mAnomalyMonitor;
diff --git a/cmds/statsd/src/atoms.proto b/cmds/statsd/src/atoms.proto
index 4e570a6..02c6c14 100644
--- a/cmds/statsd/src/atoms.proto
+++ b/cmds/statsd/src/atoms.proto
@@ -757,8 +757,8 @@
// The tag used with the is_default for resetting sets of settings. This is generally null.
optional string tag = 5;
- // 1 indicates that this setting with tag should be resettable.
- optional int32 is_default = 6;
+ // True if this setting with tag should be resettable.
+ optional bool is_default = 6;
// The user ID associated. Defined in android/os/UserHandle.java
optional int32 user = 7;
@@ -1105,9 +1105,12 @@
optional int32 isolated_uid = 2;
- // 1 denotes we're creating an isolated uid and 0 denotes removal. We expect an isolated uid to
- // be removed before if it's used for another parent uid.
- optional int32 is_create = 3;
+ // We expect an isolated uid to be removed before if it's used for another parent uid.
+ enum Event {
+ REMOVED = 0;
+ CREATED = 1;
+ }
+ optional Event event = 3;
}
/**
diff --git a/cmds/statsd/src/condition/CombinationConditionTracker.cpp b/cmds/statsd/src/condition/CombinationConditionTracker.cpp
index ea6586c..4c20ccb 100644
--- a/cmds/statsd/src/condition/CombinationConditionTracker.cpp
+++ b/cmds/statsd/src/condition/CombinationConditionTracker.cpp
@@ -78,6 +78,7 @@
return false;
}
+
bool initChildSucceeded = childTracker->init(allConditionConfig, allConditionTrackers,
conditionIdIndexMap, stack);
@@ -88,8 +89,10 @@
ALOGW("Child initialization success %lld ", (long long)child);
}
+ if (allConditionTrackers[childIndex]->isSliced()) {
+ setSliced(true);
+ }
mChildren.push_back(childIndex);
-
mTrackerIndex.insert(childTracker->getLogTrackerIndex().begin(),
childTracker->getLogTrackerIndex().end());
}
@@ -105,11 +108,15 @@
void CombinationConditionTracker::isConditionMet(
const ConditionKey& conditionParameters,
const vector<sp<ConditionTracker>>& allConditions,
- vector<ConditionState>& conditionCache) const {
+ const FieldMatcher& dimensionFields,
+ vector<ConditionState>& conditionCache,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const {
+ // So far, this is fine as there is at most one child having sliced output.
for (const int childIndex : mChildren) {
if (conditionCache[childIndex] == ConditionState::kNotEvaluated) {
allConditions[childIndex]->isConditionMet(conditionParameters, allConditions,
- conditionCache);
+ dimensionFields, conditionCache,
+ dimensionsKeySet);
}
}
conditionCache[mIndex] =
@@ -127,6 +134,7 @@
}
for (const int childIndex : mChildren) {
+ // So far, this is fine as there is at most one child having sliced output.
if (nonSlicedConditionCache[childIndex] == ConditionState::kNotEvaluated) {
const sp<ConditionTracker>& child = mAllConditions[childIndex];
child->evaluateCondition(event, eventMatcherValues, mAllConditions,
@@ -159,6 +167,24 @@
}
}
+ConditionState CombinationConditionTracker::getMetConditionDimension(
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const {
+ vector<ConditionState> conditionCache(allConditions.size(), ConditionState::kNotEvaluated);
+ // So far, this is fine as there is at most one child having sliced output.
+ for (const int childIndex : mChildren) {
+ conditionCache[childIndex] = conditionCache[childIndex] |
+ allConditions[childIndex]->getMetConditionDimension(
+ allConditions, dimensionFields, dimensionsKeySet);
+ }
+ evaluateCombinationCondition(mChildren, mLogicalOperation, conditionCache);
+ if (conditionCache[mIndex] == ConditionState::kTrue && dimensionsKeySet.empty()) {
+ dimensionsKeySet.insert(DEFAULT_DIMENSION_KEY);
+ }
+ return conditionCache[mIndex];
+}
+
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/condition/CombinationConditionTracker.h b/cmds/statsd/src/condition/CombinationConditionTracker.h
index dfd3837..0b7f949 100644
--- a/cmds/statsd/src/condition/CombinationConditionTracker.h
+++ b/cmds/statsd/src/condition/CombinationConditionTracker.h
@@ -41,12 +41,20 @@
std::vector<ConditionState>& conditionCache,
std::vector<bool>& changedCache) override;
- void isConditionMet(const ConditionKey& conditionParameters,
- const std::vector<sp<ConditionTracker>>& allConditions,
- std::vector<ConditionState>& conditionCache) const override;
+ void isConditionMet(
+ const ConditionKey& conditionParameters,
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::vector<ConditionState>& conditionCache,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const override;
+ ConditionState getMetConditionDimension(
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const override;
private:
LogicalOperation mLogicalOperation;
+
// Store index of the children Predicates.
// We don't store string name of the Children, because we want to get rid of the hash map to
// map the name to object. We don't want to store smart pointers to children, because it
diff --git a/cmds/statsd/src/condition/ConditionTracker.h b/cmds/statsd/src/condition/ConditionTracker.h
index 773860f..81abbdb 100644
--- a/cmds/statsd/src/condition/ConditionTracker.h
+++ b/cmds/statsd/src/condition/ConditionTracker.h
@@ -24,6 +24,7 @@
#include <log/logprint.h>
#include <utils/RefBase.h>
+#include <unordered_set>
#include <unordered_map>
namespace android {
@@ -84,10 +85,19 @@
// [allConditions]: all condition trackers. This is needed because the condition evaluation is
// done recursively
// [conditionCache]: the cache holding the condition evaluation values.
+ // [dimensionsKeySet]: the dimensions where the sliced condition is true. For combination
+ // condition, it assumes that only one child predicate is sliced.
virtual void isConditionMet(
const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- std::vector<ConditionState>& conditionCache) const = 0;
+ const FieldMatcher& dimensionFields,
+ std::vector<ConditionState>& conditionCache,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const = 0;
+
+ virtual ConditionState getMetConditionDimension(
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const = 0;
// return the list of LogMatchingTracker index that this ConditionTracker uses.
virtual const std::set<int>& getLogTrackerIndex() const {
@@ -98,6 +108,10 @@
mSliced = mSliced | sliced;
}
+ bool isSliced() const {
+ return mSliced;
+ }
+
protected:
const int64_t mConditionId;
diff --git a/cmds/statsd/src/condition/ConditionWizard.cpp b/cmds/statsd/src/condition/ConditionWizard.cpp
index d99c2cc..0427700 100644
--- a/cmds/statsd/src/condition/ConditionWizard.cpp
+++ b/cmds/statsd/src/condition/ConditionWizard.cpp
@@ -14,6 +14,7 @@
* limitations under the License.
*/
#include "ConditionWizard.h"
+#include <unordered_set>
namespace android {
namespace os {
@@ -23,14 +24,26 @@
using std::string;
using std::vector;
-ConditionState ConditionWizard::query(const int index,
- const ConditionKey& parameters) {
+ConditionState ConditionWizard::query(
+ const int index, const ConditionKey& parameters,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> *dimensionKeySet) {
+
vector<ConditionState> cache(mAllConditions.size(), ConditionState::kNotEvaluated);
- mAllConditions[index]->isConditionMet(parameters, mAllConditions, cache);
+ mAllConditions[index]->isConditionMet(
+ parameters, mAllConditions, dimensionFields, cache, *dimensionKeySet);
return cache[index];
}
+ConditionState ConditionWizard::getMetConditionDimension(
+ const int index, const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> *dimensionsKeySet) const {
+
+ return mAllConditions[index]->getMetConditionDimension(mAllConditions, dimensionFields,
+ *dimensionsKeySet);
+}
+
} // namespace statsd
} // namespace os
} // namespace android
\ No newline at end of file
diff --git a/cmds/statsd/src/condition/ConditionWizard.h b/cmds/statsd/src/condition/ConditionWizard.h
index 4ff5c07..b38b59f 100644
--- a/cmds/statsd/src/condition/ConditionWizard.h
+++ b/cmds/statsd/src/condition/ConditionWizard.h
@@ -41,7 +41,14 @@
// the conditionParameters contains the parameters for it's children SimpleConditionTrackers.
virtual ConditionState query(
const int conditionIndex,
- const ConditionKey& conditionParameters);
+ const ConditionKey& conditionParameters,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> *dimensionKeySet);
+
+ virtual ConditionState getMetConditionDimension(
+ const int index,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> *dimensionsKeySet) const;
private:
std::vector<sp<ConditionTracker>> mAllConditions;
diff --git a/cmds/statsd/src/condition/SimpleConditionTracker.cpp b/cmds/statsd/src/condition/SimpleConditionTracker.cpp
index 5cfc349..25265d5 100644
--- a/cmds/statsd/src/condition/SimpleConditionTracker.cpp
+++ b/cmds/statsd/src/condition/SimpleConditionTracker.cpp
@@ -104,6 +104,9 @@
vector<bool>& stack) {
// SimpleConditionTracker does not have dependency on other conditions, thus we just return
// if the initialization was successful.
+ if (mOutputDimensions.has_field() || mOutputDimensions.child_size() > 0) {
+ setSliced(true);
+ }
return mInitialized;
}
@@ -234,11 +237,12 @@
conditionChangedCache[mIndex] == true);
}
-void SimpleConditionTracker::evaluateCondition(const LogEvent& event,
- const vector<MatchingState>& eventMatcherValues,
- const vector<sp<ConditionTracker>>& mAllConditions,
- vector<ConditionState>& conditionCache,
- vector<bool>& conditionChangedCache) {
+void SimpleConditionTracker::evaluateCondition(
+ const LogEvent& event,
+ const vector<MatchingState>& eventMatcherValues,
+ const vector<sp<ConditionTracker>>& mAllConditions,
+ vector<ConditionState>& conditionCache,
+ vector<bool>& conditionChangedCache) {
if (conditionCache[mIndex] != ConditionState::kNotEvaluated) {
// it has been evaluated.
VLOG("Yes, already evaluated, %lld %d",
@@ -271,7 +275,7 @@
if (mSliced) {
// if the condition result is sliced. metrics won't directly get value from the
// cache, so just set any value other than kNotEvaluated.
- conditionCache[mIndex] = ConditionState::kUnknown;
+ conditionCache[mIndex] = mInitialValue;
} else {
const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
if (itr == mSlicedConditionState.end()) {
@@ -310,10 +314,8 @@
vector<ConditionState> dimensionalConditionCache(conditionCache.size(),
ConditionState::kNotEvaluated);
vector<bool> dimensionalConditionChangedCache(conditionChangedCache.size(), false);
-
handleConditionEvent(HashableDimensionKey(outputValue), matchedState == 1,
dimensionalConditionCache, dimensionalConditionChangedCache);
-
OrConditionState(dimensionalConditionCache, &conditionCache);
OrBooleanVector(dimensionalConditionChangedCache, &conditionChangedCache);
}
@@ -323,42 +325,73 @@
void SimpleConditionTracker::isConditionMet(
const ConditionKey& conditionParameters,
const vector<sp<ConditionTracker>>& allConditions,
- vector<ConditionState>& conditionCache) const {
- const auto pair = conditionParameters.find(mConditionId);
-
- if (pair == conditionParameters.end() && mOutputDimensions.child_size() > 0) {
- ALOGE("Predicate %lld output has dimension, but it's not specified in the query!",
- (long long)mConditionId);
- conditionCache[mIndex] = mInitialValue;
+ const FieldMatcher& dimensionFields,
+ vector<ConditionState>& conditionCache,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const {
+ if (conditionCache[mIndex] != ConditionState::kNotEvaluated) {
+ // it has been evaluated.
+ VLOG("Yes, already evaluated, %lld %d",
+ (long long)mConditionId, conditionCache[mIndex]);
return;
}
- std::vector<HashableDimensionKey> defaultKeys = {DEFAULT_DIMENSION_KEY};
+ const auto pair = conditionParameters.find(mConditionId);
+
+ if (pair == conditionParameters.end()) {
+ ConditionState conditionState = ConditionState::kNotEvaluated;
+ if (dimensionFields.has_field() && dimensionFields.child_size() > 0 &&
+ dimensionFields.field() == mOutputDimensions.field()) {
+ conditionState = conditionState | getMetConditionDimension(
+ allConditions, dimensionFields, dimensionsKeySet);
+ } else {
+ conditionState = conditionState | mInitialValue;
+ if (!mSliced) {
+ const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
+ if (itr != mSlicedConditionState.end()) {
+ ConditionState sliceState =
+ itr->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ conditionState = conditionState | sliceState;
+ }
+ }
+ }
+ conditionCache[mIndex] = conditionState;
+ return;
+ }
+ std::vector<HashableDimensionKey> defaultKeys = { DEFAULT_DIMENSION_KEY };
const std::vector<HashableDimensionKey> &keys =
(pair == conditionParameters.end()) ? defaultKeys : pair->second;
ConditionState conditionState = ConditionState::kNotEvaluated;
- for (const auto& key : keys) {
+ for (size_t i = 0; i < keys.size(); ++i) {
+ const HashableDimensionKey& key = keys[i];
auto startedCountIt = mSlicedConditionState.find(key);
if (startedCountIt != mSlicedConditionState.end()) {
- conditionState = conditionState |
- (startedCountIt->second > 0 ? ConditionState::kTrue : ConditionState::kFalse);
+ ConditionState sliceState =
+ startedCountIt->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ conditionState = conditionState | sliceState;
+ if (sliceState == ConditionState::kTrue && dimensionFields.has_field()) {
+ HashableDimensionKey dimensionKey;
+ if (getSubDimension(startedCountIt->first.getDimensionsValue(), dimensionFields,
+ dimensionKey.getMutableDimensionsValue())) {
+ dimensionsKeySet.insert(dimensionKey);
+ }
+ }
} else {
// For unseen key, check whether the require dimensions are subset of sliced condition
// output.
- bool seenDimension = false;
+ conditionState = conditionState | mInitialValue;
for (const auto& slice : mSlicedConditionState) {
- if (IsSubDimension(slice.first.getDimensionsValue(),
- key.getDimensionsValue())) {
- seenDimension = true;
- conditionState = conditionState |
- (slice.second > 0 ? ConditionState::kTrue : ConditionState::kFalse);
+ ConditionState sliceState =
+ slice.second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ if (IsSubDimension(slice.first.getDimensionsValue(), key.getDimensionsValue())) {
+ conditionState = conditionState | sliceState;
+ if (sliceState == ConditionState::kTrue && dimensionFields.has_field()) {
+ HashableDimensionKey dimensionKey;
+ if (getSubDimension(slice.first.getDimensionsValue(),
+ dimensionFields, dimensionKey.getMutableDimensionsValue())) {
+ dimensionsKeySet.insert(dimensionKey);
+ }
+ }
}
- if (conditionState == ConditionState::kTrue) {
- break;
- }
- }
- if (!seenDimension) {
- conditionState = conditionState | mInitialValue;
}
}
}
@@ -366,6 +399,38 @@
VLOG("Predicate %lld return %d", (long long)mConditionId, conditionCache[mIndex]);
}
+ConditionState SimpleConditionTracker::getMetConditionDimension(
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const {
+ ConditionState conditionState = mInitialValue;
+ if (!dimensionFields.has_field() ||
+ !mOutputDimensions.has_field() ||
+ dimensionFields.field() != mOutputDimensions.field()) {
+ const auto& itr = mSlicedConditionState.find(DEFAULT_DIMENSION_KEY);
+ if (itr != mSlicedConditionState.end()) {
+ ConditionState sliceState =
+ itr->second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ conditionState = conditionState | sliceState;
+ }
+ return conditionState;
+ }
+
+ for (const auto& slice : mSlicedConditionState) {
+ ConditionState sliceState =
+ slice.second > 0 ? ConditionState::kTrue : ConditionState::kFalse;
+ DimensionsValue dimensionsValue;
+ conditionState = conditionState | sliceState;
+ HashableDimensionKey dimensionKey;
+ if (sliceState == ConditionState::kTrue &&
+ getSubDimension(slice.first.getDimensionsValue(), dimensionFields,
+ dimensionKey.getMutableDimensionsValue())) {
+ dimensionsKeySet.insert(dimensionKey);
+ }
+ }
+ return conditionState;
+}
+
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/condition/SimpleConditionTracker.h b/cmds/statsd/src/condition/SimpleConditionTracker.h
index 815b445..ce9a02d 100644
--- a/cmds/statsd/src/condition/SimpleConditionTracker.h
+++ b/cmds/statsd/src/condition/SimpleConditionTracker.h
@@ -48,7 +48,14 @@
void isConditionMet(const ConditionKey& conditionParameters,
const std::vector<sp<ConditionTracker>>& allConditions,
- std::vector<ConditionState>& conditionCache) const override;
+ const FieldMatcher& dimensionFields,
+ std::vector<ConditionState>& conditionCache,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const override;
+
+ ConditionState getMetConditionDimension(
+ const std::vector<sp<ConditionTracker>>& allConditions,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> &dimensionsKeySet) const override;
private:
const ConfigKey mConfigKey;
@@ -73,7 +80,8 @@
void handleStopAll(std::vector<ConditionState>& conditionCache,
std::vector<bool>& changedCache);
- void handleConditionEvent(const HashableDimensionKey& outputKey, bool matchStart,
+ void handleConditionEvent(const HashableDimensionKey& outputKey,
+ bool matchStart,
std::vector<ConditionState>& conditionCache,
std::vector<bool>& changedCache);
diff --git a/cmds/statsd/src/condition/condition_util.cpp b/cmds/statsd/src/condition/condition_util.cpp
index 3b2d480..0ab33cf 100644
--- a/cmds/statsd/src/condition/condition_util.cpp
+++ b/cmds/statsd/src/condition/condition_util.cpp
@@ -118,6 +118,9 @@
void getFieldsFromFieldMatcher(const FieldMatcher& matcher, Field* rootField, Field* leafField,
std::vector<Field> *allFields) {
+ if (matcher.has_position()) {
+ leafField->set_position_index(0);
+ }
if (matcher.child_size() == 0) {
allFields->push_back(*rootField);
return;
diff --git a/cmds/statsd/src/dimension.cpp b/cmds/statsd/src/dimension.cpp
index 04445ca..8a2e871 100644
--- a/cmds/statsd/src/dimension.cpp
+++ b/cmds/statsd/src/dimension.cpp
@@ -253,6 +253,9 @@
}
void DimensionsValueToString(const DimensionsValue& value, std::string *flattened) {
+ if (!value.has_field()) {
+ return;
+ }
*flattened += std::to_string(value.field());
*flattened += ":";
switch (value.value_case()) {
@@ -352,6 +355,46 @@
}
}
+bool getSubDimension(const DimensionsValue& dimension, const FieldMatcher& matcher,
+ DimensionsValue* subDimension) {
+ if (!matcher.has_field()) {
+ return false;
+ }
+ if (matcher.field() != dimension.field()) {
+ return false;
+ }
+ if (matcher.child_size() <= 0) {
+ if (dimension.value_case() == DimensionsValue::ValueCase::kValueTuple ||
+ dimension.value_case() == DimensionsValue::ValueCase::VALUE_NOT_SET) {
+ return false;
+ }
+ *subDimension = dimension;
+ return true;
+ } else {
+ if (dimension.value_case() != DimensionsValue::ValueCase::kValueTuple) {
+ return false;
+ }
+ bool found_value = true;
+ auto value_tuple = dimension.value_tuple();
+ subDimension->set_field(dimension.field());
+ for (int i = 0; found_value && i < matcher.child_size(); ++i) {
+ int j = 0;
+ for (; j < value_tuple.dimensions_value_size(); ++j) {
+ if (value_tuple.dimensions_value(j).field() == matcher.child(i).field()) {
+ break;
+ }
+ }
+ if (j < value_tuple.dimensions_value_size()) {
+ found_value &= getSubDimension(value_tuple.dimensions_value(j), matcher.child(i),
+ subDimension->mutable_value_tuple()->add_dimensions_value());
+ } else {
+ found_value = false;
+ }
+ }
+ return found_value;
+ }
+}
+
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/dimension.h b/cmds/statsd/src/dimension.h
index e900c5e..138c6e9 100644
--- a/cmds/statsd/src/dimension.h
+++ b/cmds/statsd/src/dimension.h
@@ -63,6 +63,9 @@
// Helper function to get long value from the DimensionsValue proto.
long getLongFromDimenValue(const DimensionsValue& dimensionValue);
+
+bool getSubDimension(const DimensionsValue& dimension, const FieldMatcher& matcher,
+ DimensionsValue* subDimension);
} // namespace statsd
} // namespace os
} // namespace android
diff --git a/cmds/statsd/src/metrics/CountMetricProducer.cpp b/cmds/statsd/src/metrics/CountMetricProducer.cpp
index 0455f6a..ae4df3e 100644
--- a/cmds/statsd/src/metrics/CountMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/CountMetricProducer.cpp
@@ -21,6 +21,7 @@
#include "guardrail/StatsdStats.h"
#include "stats_util.h"
#include "stats_log_util.h"
+#include "dimension.h"
#include <limits.h>
#include <stdlib.h>
@@ -71,13 +72,15 @@
}
// TODO: use UidMap if uid->pkg_name is required
- mDimensions = metric.dimensions_in_what();
+ mDimensionsInWhat = metric.dimensions_in_what();
+ mDimensionsInCondition = metric.dimensions_in_condition();
if (metric.links().size() > 0) {
mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
metric.links().end());
- mConditionSliced = true;
}
+ mConditionSliced = (metric.links().size() > 0)||
+ (mDimensionsInCondition.has_field() && mDimensionsInCondition.child_size() > 0);
VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
(long long)mBucketSizeNs, (long long)mStartTimeNs);
@@ -99,7 +102,10 @@
auto count_metrics = report->mutable_count_metrics();
for (const auto& counter : mPastBuckets) {
CountMetricData* metricData = count_metrics->add_data();
- *metricData->mutable_dimensions_in_what() = counter.first.getDimensionsValue();
+ *metricData->mutable_dimensions_in_what() =
+ counter.first.getDimensionKeyInWhat().getDimensionsValue();
+ *metricData->mutable_dimensions_in_condition() =
+ counter.first.getDimensionKeyInCondition().getDimensionsValue();
for (const auto& bucket : counter.second) {
CountBucketInfo* bucketInfo = metricData->add_bucket_info();
bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
@@ -123,17 +129,26 @@
VLOG("metric %lld dump report now...",(long long)mMetricId);
for (const auto& counter : mPastBuckets) {
- const HashableDimensionKey& hashableKey = counter.first;
- VLOG(" dimension key %s", hashableKey.c_str());
+ const MetricDimensionKey& dimensionKey = counter.first;
+ VLOG(" dimension key %s", dimensionKey.c_str());
long long wrapperToken =
protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
// First fill dimension.
- long long dimensionToken = protoOutput->start(
+ long long dimensionInWhatToken = protoOutput->start(
FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
- writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
- protoOutput->end(dimensionToken);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInWhat().getDimensionsValue(), protoOutput);
+ protoOutput->end(dimensionInWhatToken);
+
+ if (dimensionKey.hasDimensionKeyInCondition()) {
+ long long dimensionInConditionToken = protoOutput->start(
+ FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInCondition().getDimensionsValue(), protoOutput);
+ protoOutput->end(dimensionInConditionToken);
+ }
// Then fill bucket_info (CountBucketInfo).
for (const auto& bucket : counter.second) {
@@ -166,7 +181,7 @@
mCondition = conditionMet;
}
-bool CountMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
+bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
return false;
}
@@ -187,7 +202,7 @@
}
void CountMetricProducer::onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) {
uint64_t eventTimeNs = event.GetTimestampNs();
diff --git a/cmds/statsd/src/metrics/CountMetricProducer.h b/cmds/statsd/src/metrics/CountMetricProducer.h
index 061b7a3..8659d47 100644
--- a/cmds/statsd/src/metrics/CountMetricProducer.h
+++ b/cmds/statsd/src/metrics/CountMetricProducer.h
@@ -50,7 +50,7 @@
protected:
void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) override;
@@ -74,14 +74,14 @@
void flushIfNeededLocked(const uint64_t& newEventTime);
// TODO: Add a lock to mPastBuckets.
- std::unordered_map<HashableDimensionKey, std::vector<CountBucket>> mPastBuckets;
+ std::unordered_map<MetricDimensionKey, std::vector<CountBucket>> mPastBuckets;
// The current bucket.
std::shared_ptr<DimToValMap> mCurrentSlicedCounter = std::make_shared<DimToValMap>();
static const size_t kBucketSize = sizeof(CountBucket{});
- bool hitGuardRailLocked(const HashableDimensionKey& newKey);
+ bool hitGuardRailLocked(const MetricDimensionKey& newKey);
FRIEND_TEST(CountMetricProducerTest, TestNonDimensionalEvents);
FRIEND_TEST(CountMetricProducerTest, TestEventsWithNonSlicedCondition);
diff --git a/cmds/statsd/src/metrics/DurationMetricProducer.cpp b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
index 000874c..efbdae1 100644
--- a/cmds/statsd/src/metrics/DurationMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/DurationMetricProducer.cpp
@@ -21,6 +21,7 @@
#include "guardrail/StatsdStats.h"
#include "stats_util.h"
#include "stats_log_util.h"
+#include "dimension.h"
#include <limits.h>
#include <stdlib.h>
@@ -81,13 +82,15 @@
}
// TODO: use UidMap if uid->pkg_name is required
- mDimensions = metric.dimensions_in_what();
+ mDimensionsInWhat = metric.dimensions_in_what();
+ mDimensionsInCondition = metric.dimensions_in_condition();
if (metric.links().size() > 0) {
mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
metric.links().end());
- mConditionSliced = true;
}
+ mConditionSliced = (metric.links().size() > 0)||
+ (mDimensionsInCondition.has_field() && mDimensionsInCondition.child_size() > 0);
VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
(long long)mBucketSizeNs, (long long)mStartTimeNs);
@@ -113,15 +116,17 @@
}
unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
- const HashableDimensionKey& eventKey) const {
+ const MetricDimensionKey& eventKey) const {
switch (mAggregationType) {
case DurationMetric_AggregationType_SUM:
return make_unique<OringDurationTracker>(
- mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex, mNested,
+ mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
+ mDimensionsInCondition, mNested,
mCurrentBucketStartTimeNs, mBucketSizeNs, mConditionSliced, mAnomalyTrackers);
case DurationMetric_AggregationType_MAX_SPARSE:
return make_unique<MaxDurationTracker>(
- mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex, mNested,
+ mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
+ mDimensionsInCondition, mNested,
mCurrentBucketStartTimeNs, mBucketSizeNs, mConditionSliced, mAnomalyTrackers);
}
}
@@ -129,10 +134,34 @@
void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
flushIfNeededLocked(eventTime);
+
// Now for each of the on-going event, check if the condition has changed for them.
- for (auto& pair : mCurrentSlicedDuration) {
+ for (auto& pair : mCurrentSlicedDurationTrackerMap) {
pair.second->onSlicedConditionMayChange(eventTime);
}
+
+
+ std::unordered_set<HashableDimensionKey> conditionDimensionsKeySet;
+ ConditionState conditionState = mWizard->getMetConditionDimension(
+ mConditionTrackerIndex, mDimensionsInCondition, &conditionDimensionsKeySet);
+
+ bool condition = (conditionState == ConditionState::kTrue);
+ for (auto& pair : mCurrentSlicedDurationTrackerMap) {
+ conditionDimensionsKeySet.erase(pair.first.getDimensionKeyInCondition());
+ }
+ std::unordered_set<MetricDimensionKey> newKeys;
+ for (const auto& conditionDimensionsKey : conditionDimensionsKeySet) {
+ for (auto& pair : mCurrentSlicedDurationTrackerMap) {
+ auto newKey =
+ MetricDimensionKey(pair.first.getDimensionKeyInWhat(), conditionDimensionsKey);
+ if (newKeys.find(newKey) == newKeys.end()) {
+ mCurrentSlicedDurationTrackerMap[newKey] = pair.second->clone(eventTime);
+ mCurrentSlicedDurationTrackerMap[newKey]->setEventKey(newKey);
+ mCurrentSlicedDurationTrackerMap[newKey]->onSlicedConditionMayChange(eventTime);
+ }
+ newKeys.insert(newKey);
+ }
+ }
}
void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
@@ -142,7 +171,7 @@
flushIfNeededLocked(eventTime);
// TODO: need to populate the condition change time from the event which triggers the condition
// change, instead of using current time.
- for (auto& pair : mCurrentSlicedDuration) {
+ for (auto& pair : mCurrentSlicedDurationTrackerMap) {
pair.second->onConditionChanged(conditionMet, eventTime);
}
}
@@ -155,7 +184,10 @@
auto duration_metrics = report->mutable_duration_metrics();
for (const auto& pair : mPastBuckets) {
DurationMetricData* metricData = duration_metrics->add_data();
- *metricData->mutable_dimensions_in_what() = pair.first.getDimensionsValue();
+ *metricData->mutable_dimensions_in_what() =
+ pair.first.getDimensionKeyInWhat().getDimensionsValue();
+ *metricData->mutable_dimensions_in_condition() =
+ pair.first.getDimensionKeyInCondition().getDimensionsValue();
for (const auto& bucket : pair.second) {
auto bucketInfo = metricData->add_bucket_info();
bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
@@ -179,8 +211,8 @@
VLOG("metric %lld dump report now...", (long long)mMetricId);
for (const auto& pair : mPastBuckets) {
- const HashableDimensionKey& hashableKey = pair.first;
- VLOG(" dimension key %s", hashableKey.c_str());
+ const MetricDimensionKey& dimensionKey = pair.first;
+ VLOG(" dimension key %s", dimensionKey.c_str());
long long wrapperToken =
protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
@@ -188,9 +220,18 @@
// First fill dimension.
long long dimensionToken = protoOutput->start(
FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
- writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInWhat().getDimensionsValue(), protoOutput);
protoOutput->end(dimensionToken);
+ if (dimensionKey.hasDimensionKeyInCondition()) {
+ long long dimensionInConditionToken = protoOutput->start(
+ FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInCondition().getDimensionsValue(), protoOutput);
+ protoOutput->end(dimensionInConditionToken);
+ }
+
// Then fill bucket_info (DurationBucketInfo).
for (const auto& bucket : pair.second) {
long long bucketInfoToken = protoOutput->start(
@@ -219,10 +260,11 @@
return;
}
VLOG("flushing...........");
- for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
+ for (auto it = mCurrentSlicedDurationTrackerMap.begin();
+ it != mCurrentSlicedDurationTrackerMap.end();) {
if (it->second->flushIfNeeded(eventTime, &mPastBuckets)) {
VLOG("erase bucket for key %s", it->first.c_str());
- it = mCurrentSlicedDuration.erase(it);
+ it = mCurrentSlicedDurationTrackerMap.erase(it);
} else {
++it;
}
@@ -234,28 +276,28 @@
}
void DurationMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
- if (mCurrentSlicedDuration.size() == 0) {
+ if (mCurrentSlicedDurationTrackerMap.size() == 0) {
return;
}
fprintf(out, "DurationMetric %lld dimension size %lu\n", (long long)mMetricId,
- (unsigned long)mCurrentSlicedDuration.size());
+ (unsigned long)mCurrentSlicedDurationTrackerMap.size());
if (verbose) {
- for (const auto& slice : mCurrentSlicedDuration) {
+ for (const auto& slice : mCurrentSlicedDurationTrackerMap) {
fprintf(out, "\t%s\n", slice.first.c_str());
slice.second->dumpStates(out, verbose);
}
}
}
-bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
+bool DurationMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
// the key is not new, we are good.
- if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
+ if (mCurrentSlicedDurationTrackerMap.find(newKey) != mCurrentSlicedDurationTrackerMap.end()) {
return false;
}
// 1. Report the tuple count if the tuple count > soft limit
- if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
- size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
+ if (mCurrentSlicedDurationTrackerMap.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
+ size_t newTupleCount = mCurrentSlicedDurationTrackerMap.size() + 1;
StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
// 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
@@ -268,27 +310,26 @@
}
void DurationMetricProducer::onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKeys, bool condition,
const LogEvent& event) {
flushIfNeededLocked(event.GetTimestampNs());
if (matcherIndex == mStopAllIndex) {
- for (auto& pair : mCurrentSlicedDuration) {
+ for (auto& pair : mCurrentSlicedDurationTrackerMap) {
pair.second->noteStopAll(event.GetTimestampNs());
}
return;
}
-
- if (mCurrentSlicedDuration.find(eventKey) == mCurrentSlicedDuration.end()) {
+ if (mCurrentSlicedDurationTrackerMap.find(eventKey) == mCurrentSlicedDurationTrackerMap.end()) {
if (hitGuardRailLocked(eventKey)) {
return;
}
- mCurrentSlicedDuration[eventKey] = createDurationTracker(eventKey);
+ mCurrentSlicedDurationTrackerMap[eventKey] = createDurationTracker(eventKey);
}
- auto it = mCurrentSlicedDuration.find(eventKey);
+ auto it = mCurrentSlicedDurationTrackerMap.find(eventKey);
std::vector<DimensionsValue> values;
getDimensionKeys(event, mInternalDimensions, &values);
@@ -302,10 +343,11 @@
} else {
for (const DimensionsValue& value : values) {
if (matcherIndex == mStartIndex) {
- it->second->noteStart(HashableDimensionKey(value), condition,
- event.GetTimestampNs(), conditionKeys);
+ it->second->noteStart(
+ HashableDimensionKey(value), condition, event.GetTimestampNs(), conditionKeys);
} else if (matcherIndex == mStopIndex) {
- it->second->noteStop(HashableDimensionKey(value), event.GetTimestampNs(), false);
+ it->second->noteStop(
+ HashableDimensionKey(value), event.GetTimestampNs(), false);
}
}
}
diff --git a/cmds/statsd/src/metrics/DurationMetricProducer.h b/cmds/statsd/src/metrics/DurationMetricProducer.h
index d8cab92..152e570 100644
--- a/cmds/statsd/src/metrics/DurationMetricProducer.h
+++ b/cmds/statsd/src/metrics/DurationMetricProducer.h
@@ -50,7 +50,7 @@
protected:
void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKeys, bool condition,
const LogEvent& event) override;
@@ -92,21 +92,21 @@
// Save the past buckets and we can clear when the StatsLogReport is dumped.
// TODO: Add a lock to mPastBuckets.
- std::unordered_map<HashableDimensionKey, std::vector<DurationBucket>> mPastBuckets;
+ std::unordered_map<MetricDimensionKey, std::vector<DurationBucket>> mPastBuckets;
// The current bucket.
- std::unordered_map<HashableDimensionKey, std::unique_ptr<DurationTracker>>
- mCurrentSlicedDuration;
+ std::unordered_map<MetricDimensionKey, std::unique_ptr<DurationTracker>>
+ mCurrentSlicedDurationTrackerMap;
// Helper function to create a duration tracker given the metric aggregation type.
std::unique_ptr<DurationTracker> createDurationTracker(
- const HashableDimensionKey& eventKey) const;
+ const MetricDimensionKey& eventKey) const;
// This hides the base class's std::vector<sp<AnomalyTracker>> mAnomalyTrackers
std::vector<sp<DurationAnomalyTracker>> mAnomalyTrackers;
// Util function to check whether the specified dimension hits the guardrail.
- bool hitGuardRailLocked(const HashableDimensionKey& newKey);
+ bool hitGuardRailLocked(const MetricDimensionKey& newKey);
static const size_t kBucketSize = sizeof(DurationBucket{});
diff --git a/cmds/statsd/src/metrics/EventMetricProducer.cpp b/cmds/statsd/src/metrics/EventMetricProducer.cpp
index 25c86d0..820d591 100644
--- a/cmds/statsd/src/metrics/EventMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/EventMetricProducer.cpp
@@ -128,7 +128,7 @@
}
void EventMetricProducer::onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) {
if (!condition) {
diff --git a/cmds/statsd/src/metrics/EventMetricProducer.h b/cmds/statsd/src/metrics/EventMetricProducer.h
index 9da0dd0..935f206 100644
--- a/cmds/statsd/src/metrics/EventMetricProducer.h
+++ b/cmds/statsd/src/metrics/EventMetricProducer.h
@@ -45,7 +45,7 @@
private:
void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) override;
diff --git a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
index 1072c5a..d6cb189 100644
--- a/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/GaugeMetricProducer.cpp
@@ -82,13 +82,15 @@
mFieldFilter = metric.gauge_fields_filter();
// TODO: use UidMap if uid->pkg_name is required
- mDimensions = metric.dimensions_in_what();
+ mDimensionsInWhat = metric.dimensions_in_what();
+ mDimensionsInCondition = metric.dimensions_in_condition();
if (metric.links().size() > 0) {
mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
metric.links().end());
- mConditionSliced = true;
}
+ mConditionSliced = (metric.links().size() > 0)||
+ (mDimensionsInCondition.has_field() && mDimensionsInCondition.child_size() > 0);
// Kicks off the puller immediately.
if (mPullTagId != -1 && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
@@ -136,18 +138,27 @@
long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_GAUGE_METRICS);
for (const auto& pair : mPastBuckets) {
- const HashableDimensionKey& hashableKey = pair.first;
+ const MetricDimensionKey& dimensionKey = pair.first;
- VLOG(" dimension key %s", hashableKey.c_str());
+ VLOG(" dimension key %s", dimensionKey.c_str());
long long wrapperToken =
protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
// First fill dimension.
long long dimensionToken = protoOutput->start(
FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
- writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInWhat().getDimensionsValue(), protoOutput);
protoOutput->end(dimensionToken);
+ if (dimensionKey.hasDimensionKeyInCondition()) {
+ long long dimensionInConditionToken = protoOutput->start(
+ FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInCondition().getDimensionsValue(), protoOutput);
+ protoOutput->end(dimensionInConditionToken);
+ }
+
// Then fill bucket_info (GaugeBucketInfo).
for (const auto& bucket : pair.second) {
long long bucketInfoToken = protoOutput->start(
@@ -248,7 +259,7 @@
}
}
-bool GaugeMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
+bool GaugeMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
if (mCurrentSlicedBucket->find(newKey) != mCurrentSlicedBucket->end()) {
return false;
}
@@ -268,7 +279,7 @@
}
void GaugeMetricProducer::onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) {
if (condition == false) {
diff --git a/cmds/statsd/src/metrics/GaugeMetricProducer.h b/cmds/statsd/src/metrics/GaugeMetricProducer.h
index 6c01347..86d0ccd 100644
--- a/cmds/statsd/src/metrics/GaugeMetricProducer.h
+++ b/cmds/statsd/src/metrics/GaugeMetricProducer.h
@@ -44,7 +44,7 @@
uint64_t mBucketNum;
};
-typedef std::unordered_map<HashableDimensionKey, std::vector<GaugeAtom>>
+typedef std::unordered_map<MetricDimensionKey, std::vector<GaugeAtom>>
DimToGaugeAtomsMap;
// This gauge metric producer first register the puller to automatically pull the gauge at the
@@ -64,7 +64,7 @@
protected:
void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) override;
@@ -99,7 +99,7 @@
// Save the past buckets and we can clear when the StatsLogReport is dumped.
// TODO: Add a lock to mPastBuckets.
- std::unordered_map<HashableDimensionKey, std::vector<GaugeBucket>> mPastBuckets;
+ std::unordered_map<MetricDimensionKey, std::vector<GaugeBucket>> mPastBuckets;
// The current bucket.
std::shared_ptr<DimToGaugeAtomsMap> mCurrentSlicedBucket;
@@ -119,7 +119,7 @@
std::shared_ptr<FieldValueMap> getGaugeFields(const LogEvent& event);
// Util function to check whether the specified dimension hits the guardrail.
- bool hitGuardRailLocked(const HashableDimensionKey& newKey);
+ bool hitGuardRailLocked(const MetricDimensionKey& newKey);
static const size_t kBucketSize = sizeof(GaugeBucket{});
diff --git a/cmds/statsd/src/metrics/MetricProducer.cpp b/cmds/statsd/src/metrics/MetricProducer.cpp
index e74924a..85e655b 100644
--- a/cmds/statsd/src/metrics/MetricProducer.cpp
+++ b/cmds/statsd/src/metrics/MetricProducer.cpp
@@ -15,6 +15,8 @@
*/
#include "MetricProducer.h"
+#include "dimension.h"
+
namespace android {
namespace os {
namespace statsd {
@@ -30,29 +32,51 @@
bool condition;
ConditionKey conditionKey;
+
+ std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
if (mConditionSliced) {
for (const auto& link : mConditionLinks) {
getDimensionKeysForCondition(event, link, &conditionKey[link.condition()]);
}
- if (mWizard->query(mConditionTrackerIndex, conditionKey) != ConditionState::kTrue) {
- condition = false;
- } else {
- condition = true;
- }
+ auto conditionState =
+ mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
+ &dimensionKeysInCondition);
+ condition = (conditionState == ConditionState::kTrue);
} else {
condition = mCondition;
}
- if (mDimensions.has_field() && mDimensions.child_size() > 0) {
- vector<DimensionsValue> dimensionValues;
- getDimensionKeys(event, mDimensions, &dimensionValues);
- for (const DimensionsValue& dimensionValue : dimensionValues) {
+ vector<DimensionsValue> dimensionInWhatValues;
+ if (mDimensionsInWhat.has_field() && mDimensionsInWhat.child_size() > 0) {
+ getDimensionKeys(event, mDimensionsInWhat, &dimensionInWhatValues);
+ }
+
+ if (dimensionInWhatValues.empty() && dimensionKeysInCondition.empty()) {
+ onMatchedLogEventInternalLocked(
+ matcherIndex, DEFAULT_METRIC_DIMENSION_KEY, conditionKey, condition, event);
+ } else if (dimensionKeysInCondition.empty()) {
+ for (const DimensionsValue& whatValue : dimensionInWhatValues) {
onMatchedLogEventInternalLocked(
- matcherIndex, HashableDimensionKey(dimensionValue), conditionKey, condition, event);
+ matcherIndex,
+ MetricDimensionKey(HashableDimensionKey(whatValue), DEFAULT_DIMENSION_KEY),
+ conditionKey, condition, event);
+ }
+ } else if (dimensionInWhatValues.empty()) {
+ for (const auto& conditionDimensionKey : dimensionKeysInCondition) {
+ onMatchedLogEventInternalLocked(
+ matcherIndex,
+ MetricDimensionKey(DEFAULT_DIMENSION_KEY, conditionDimensionKey),
+ conditionKey, condition, event);
}
} else {
- onMatchedLogEventInternalLocked(
- matcherIndex, DEFAULT_DIMENSION_KEY, conditionKey, condition, event);
+ for (const DimensionsValue& whatValue : dimensionInWhatValues) {
+ for (const auto& conditionDimensionKey : dimensionKeysInCondition) {
+ onMatchedLogEventInternalLocked(
+ matcherIndex,
+ MetricDimensionKey(HashableDimensionKey(whatValue), conditionDimensionKey),
+ conditionKey, condition, event);
+ }
+ }
}
}
diff --git a/cmds/statsd/src/metrics/MetricProducer.h b/cmds/statsd/src/metrics/MetricProducer.h
index 6f33073..3b1498f 100644
--- a/cmds/statsd/src/metrics/MetricProducer.h
+++ b/cmds/statsd/src/metrics/MetricProducer.h
@@ -91,6 +91,7 @@
std::lock_guard<std::mutex> lock(mMutex);
return onDumpReportLocked(dumpTimeNs, protoOutput);
}
+
void onDumpReport(const uint64_t dumpTimeNs, StatsLogReport* report) {
std::lock_guard<std::mutex> lock(mMutex);
return onDumpReportLocked(dumpTimeNs, report);
@@ -156,7 +157,8 @@
int mConditionTrackerIndex;
- FieldMatcher mDimensions; // The dimension defined in statsd_config
+ FieldMatcher mDimensionsInWhat; // The dimensions_in_what defined in statsd_config
+ FieldMatcher mDimensionsInCondition; // The dimensions_in_condition defined in statsd_config
std::vector<MetricConditionLink> mConditionLinks;
@@ -178,7 +180,7 @@
* [event]: the log event, just in case the metric needs its data, e.g., EventMetric.
*/
virtual void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) = 0;
diff --git a/cmds/statsd/src/metrics/MetricsManager.h b/cmds/statsd/src/metrics/MetricsManager.h
index 9cdbafc..d4b9102 100644
--- a/cmds/statsd/src/metrics/MetricsManager.h
+++ b/cmds/statsd/src/metrics/MetricsManager.h
@@ -143,6 +143,10 @@
FRIEND_TEST(MetricConditionLinkE2eTest, TestMultiplePredicatesAndLinks);
FRIEND_TEST(AttributionE2eTest, TestAttributionMatchAndSlice);
FRIEND_TEST(GaugeMetricE2eTest, TestMultipleFieldsForPushedEvent);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestCountMetricNoLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestCountMetricWithLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetricNoLink);
+ FRIEND_TEST(DimensionInConditionE2eTest, TestDurationMetricWithLink);
};
} // namespace statsd
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.cpp b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
index ae0c673..c9cc7bb 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.cpp
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.cpp
@@ -81,13 +81,15 @@
}
mBucketSizeNs = bucketSizeMills * 1000000;
- mDimensions = metric.dimensions_in_what();
+ mDimensionsInWhat = metric.dimensions_in_what();
+ mDimensionsInCondition = metric.dimensions_in_condition();
if (metric.links().size() > 0) {
mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
metric.links().end());
- mConditionSliced = true;
}
+ mConditionSliced = (metric.links().size() > 0)||
+ (mDimensionsInCondition.has_field() && mDimensionsInCondition.child_size() > 0);
if (!metric.has_condition() && mPullTagId != -1) {
VLOG("Setting up periodic pulling for %d", mPullTagId);
@@ -124,7 +126,10 @@
auto value_metrics = report->mutable_value_metrics();
for (const auto& pair : mPastBuckets) {
ValueMetricData* metricData = value_metrics->add_data();
- *metricData->mutable_dimensions_in_what() = pair.first.getDimensionsValue();
+ *metricData->mutable_dimensions_in_what() =
+ pair.first.getDimensionKeyInWhat().getDimensionsValue();
+ *metricData->mutable_dimensions_in_condition() =
+ pair.first.getDimensionKeyInCondition().getDimensionsValue();
for (const auto& bucket : pair.second) {
ValueBucketInfo* bucketInfo = metricData->add_bucket_info();
bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
@@ -146,16 +151,24 @@
long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
for (const auto& pair : mPastBuckets) {
- const HashableDimensionKey& hashableKey = pair.first;
- VLOG(" dimension key %s", hashableKey.c_str());
+ const MetricDimensionKey& dimensionKey = pair.first;
+ VLOG(" dimension key %s", dimensionKey.c_str());
long long wrapperToken =
protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
// First fill dimension.
long long dimensionToken = protoOutput->start(
FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
- writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInWhat().getDimensionsValue(), protoOutput);
protoOutput->end(dimensionToken);
+ if (dimensionKey.hasDimensionKeyInCondition()) {
+ long long dimensionInConditionToken = protoOutput->start(
+ FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
+ writeDimensionsValueProtoToStream(
+ dimensionKey.getDimensionKeyInCondition().getDimensionsValue(), protoOutput);
+ protoOutput->end(dimensionInConditionToken);
+ }
// Then fill bucket_info (ValueBucketInfo).
for (const auto& bucket : pair.second) {
@@ -239,7 +252,7 @@
}
}
-bool ValueMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
+bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
// ===========GuardRail==============
// 1. Report the tuple count if the tuple count > soft limit
if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
@@ -260,7 +273,7 @@
}
void ValueMetricProducer::onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) {
uint64_t eventTimeNs = event.GetTimestampNs();
diff --git a/cmds/statsd/src/metrics/ValueMetricProducer.h b/cmds/statsd/src/metrics/ValueMetricProducer.h
index 9f750cf..121ec7d 100644
--- a/cmds/statsd/src/metrics/ValueMetricProducer.h
+++ b/cmds/statsd/src/metrics/ValueMetricProducer.h
@@ -49,7 +49,7 @@
protected:
void onMatchedLogEventInternalLocked(
- const size_t matcherIndex, const HashableDimensionKey& eventKey,
+ const size_t matcherIndex, const MetricDimensionKey& eventKey,
const ConditionKey& conditionKey, bool condition,
const LogEvent& event) override;
@@ -99,16 +99,16 @@
long sum;
} Interval;
- std::unordered_map<HashableDimensionKey, Interval> mCurrentSlicedBucket;
+ std::unordered_map<MetricDimensionKey, Interval> mCurrentSlicedBucket;
// Save the past buckets and we can clear when the StatsLogReport is dumped.
// TODO: Add a lock to mPastBuckets.
- std::unordered_map<HashableDimensionKey, std::vector<ValueBucket>> mPastBuckets;
+ std::unordered_map<MetricDimensionKey, std::vector<ValueBucket>> mPastBuckets;
std::shared_ptr<FieldValueMap> getValueFields(const LogEvent& event);
// Util function to check whether the specified dimension hits the guardrail.
- bool hitGuardRailLocked(const HashableDimensionKey& newKey);
+ bool hitGuardRailLocked(const MetricDimensionKey& newKey);
static const size_t kBucketSize = sizeof(ValueBucket{});
diff --git a/cmds/statsd/src/metrics/duration_helper/DurationTracker.h b/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
index c2d2cea..45735a8 100644
--- a/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/DurationTracker.h
@@ -60,8 +60,9 @@
class DurationTracker {
public:
- DurationTracker(const ConfigKey& key, const int64_t& id, const HashableDimensionKey& eventKey,
- sp<ConditionWizard> wizard, int conditionIndex, bool nesting,
+ DurationTracker(const ConfigKey& key, const int64_t& id, const MetricDimensionKey& eventKey,
+ sp<ConditionWizard> wizard, int conditionIndex,
+ const FieldMatcher& dimensionInCondition, bool nesting,
uint64_t currentBucketStartNs, uint64_t bucketSizeNs, bool conditionSliced,
const std::vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
: mConfigKey(key),
@@ -70,6 +71,7 @@
mWizard(wizard),
mConditionTrackerIndex(conditionIndex),
mBucketSizeNs(bucketSizeNs),
+ mDimensionInCondition(dimensionInCondition),
mNested(nesting),
mCurrentBucketStartTimeNs(currentBucketStartNs),
mDuration(0),
@@ -79,6 +81,8 @@
virtual ~DurationTracker(){};
+ virtual unique_ptr<DurationTracker> clone(const uint64_t eventTime) = 0;
+
virtual void noteStart(const HashableDimensionKey& key, bool condition,
const uint64_t eventTime, const ConditionKey& conditionKey) = 0;
virtual void noteStop(const HashableDimensionKey& key, const uint64_t eventTime,
@@ -92,7 +96,7 @@
// events, so that the owner can safely remove the tracker.
virtual bool flushIfNeeded(
uint64_t timestampNs,
- std::unordered_map<HashableDimensionKey, std::vector<DurationBucket>>* output) = 0;
+ std::unordered_map<MetricDimensionKey, std::vector<DurationBucket>>* output) = 0;
// Predict the anomaly timestamp given the current status.
virtual int64_t predictAnomalyTimestampNs(const DurationAnomalyTracker& anomalyTracker,
@@ -100,6 +104,10 @@
// Dump internal states for debugging
virtual void dumpStates(FILE* out, bool verbose) const = 0;
+ void setEventKey(const MetricDimensionKey& eventKey) {
+ mEventKey = eventKey;
+ }
+
protected:
// Starts the anomaly alarm.
void startAnomalyAlarm(const uint64_t eventTime) {
@@ -150,7 +158,7 @@
const int64_t mTrackerId;
- HashableDimensionKey mEventKey;
+ MetricDimensionKey mEventKey;
sp<ConditionWizard> mWizard;
@@ -158,6 +166,8 @@
const int64_t mBucketSizeNs;
+ const FieldMatcher mDimensionInCondition;
+
const bool mNested;
uint64_t mCurrentBucketStartTimeNs;
diff --git a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
index 412a0c9..db7dea4 100644
--- a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
+++ b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.cpp
@@ -25,13 +25,23 @@
namespace statsd {
MaxDurationTracker::MaxDurationTracker(const ConfigKey& key, const int64_t& id,
- const HashableDimensionKey& eventKey,
- sp<ConditionWizard> wizard, int conditionIndex, bool nesting,
+ const MetricDimensionKey& eventKey,
+ sp<ConditionWizard> wizard, int conditionIndex,
+ const FieldMatcher& dimensionInCondition, bool nesting,
uint64_t currentBucketStartNs, uint64_t bucketSizeNs,
bool conditionSliced,
const vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
- : DurationTracker(key, id, eventKey, wizard, conditionIndex, nesting, currentBucketStartNs,
- bucketSizeNs, conditionSliced, anomalyTrackers) {
+ : DurationTracker(key, id, eventKey, wizard, conditionIndex, dimensionInCondition, nesting,
+ currentBucketStartNs, bucketSizeNs, conditionSliced, anomalyTrackers) {
+}
+
+unique_ptr<DurationTracker> MaxDurationTracker::clone(const uint64_t eventTime) {
+ auto clonedTracker = make_unique<MaxDurationTracker>(*this);
+ for (auto it = clonedTracker->mInfos.begin(); it != clonedTracker->mInfos.end(); ++it) {
+ it->second.lastStartTime = eventTime;
+ it->second.lastDuration = 0;
+ }
+ return clonedTracker;
}
bool MaxDurationTracker::hitGuardRail(const HashableDimensionKey& newKey) {
@@ -44,7 +54,7 @@
if (mInfos.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
size_t newTupleCount = mInfos.size() + 1;
StatsdStats::getInstance().noteMetricDimensionSize(
- mConfigKey, hashDimensionsValue(mTrackerId, mEventKey.getDimensionsValue()),
+ mConfigKey, hashMetricDimensionKey(mTrackerId, mEventKey),
newTupleCount);
// 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
@@ -149,7 +159,7 @@
}
bool MaxDurationTracker::flushIfNeeded(
- uint64_t eventTime, unordered_map<HashableDimensionKey, vector<DurationBucket>>* output) {
+ uint64_t eventTime, unordered_map<MetricDimensionKey, vector<DurationBucket>>* output) {
if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
return false;
}
@@ -236,8 +246,14 @@
if (pair.second.state == kStopped) {
continue;
}
- bool conditionMet = mWizard->query(mConditionTrackerIndex, pair.second.conditionKeys) ==
- ConditionState::kTrue;
+ std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
+ ConditionState conditionState = mWizard->query(
+ mConditionTrackerIndex, pair.second.conditionKeys, mDimensionInCondition,
+ &conditionDimensionKeySet);
+ bool conditionMet = (conditionState == ConditionState::kTrue) &&
+ (!mDimensionInCondition.has_field() ||
+ conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition()) !=
+ conditionDimensionKeySet.end());
VLOG("key: %s, condition: %d", pair.first.c_str(), conditionMet);
noteConditionChanged(pair.first, conditionMet, timestamp);
}
diff --git a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
index 661d131..4d32a06 100644
--- a/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/MaxDurationTracker.h
@@ -29,10 +29,15 @@
class MaxDurationTracker : public DurationTracker {
public:
MaxDurationTracker(const ConfigKey& key, const int64_t& id,
- const HashableDimensionKey& eventKey, sp<ConditionWizard> wizard,
- int conditionIndex, bool nesting, uint64_t currentBucketStartNs,
- uint64_t bucketSizeNs, bool conditionSliced,
+ const MetricDimensionKey& eventKey, sp<ConditionWizard> wizard,
+ int conditionIndex, const FieldMatcher& dimensionInCondition, bool nesting,
+ uint64_t currentBucketStartNs, uint64_t bucketSizeNs, bool conditionSliced,
const std::vector<sp<DurationAnomalyTracker>>& anomalyTrackers);
+
+ MaxDurationTracker(const MaxDurationTracker& tracker) = default;
+
+ unique_ptr<DurationTracker> clone(const uint64_t eventTime) override;
+
void noteStart(const HashableDimensionKey& key, bool condition, const uint64_t eventTime,
const ConditionKey& conditionKey) override;
void noteStop(const HashableDimensionKey& key, const uint64_t eventTime,
@@ -41,7 +46,7 @@
bool flushIfNeeded(
uint64_t timestampNs,
- std::unordered_map<HashableDimensionKey, std::vector<DurationBucket>>* output) override;
+ std::unordered_map<MetricDimensionKey, std::vector<DurationBucket>>* output) override;
void onSlicedConditionMayChange(const uint64_t timestamp) override;
void onConditionChanged(bool condition, const uint64_t timestamp) override;
diff --git a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
index 75d7c08..0feae36 100644
--- a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
+++ b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.cpp
@@ -25,17 +25,25 @@
using std::pair;
OringDurationTracker::OringDurationTracker(
- const ConfigKey& key, const int64_t& id, const HashableDimensionKey& eventKey,
- sp<ConditionWizard> wizard, int conditionIndex, bool nesting, uint64_t currentBucketStartNs,
+ const ConfigKey& key, const int64_t& id, const MetricDimensionKey& eventKey,
+ sp<ConditionWizard> wizard, int conditionIndex,
+ const FieldMatcher& dimensionInCondition, bool nesting, uint64_t currentBucketStartNs,
uint64_t bucketSizeNs, bool conditionSliced,
const vector<sp<DurationAnomalyTracker>>& anomalyTrackers)
- : DurationTracker(key, id, eventKey, wizard, conditionIndex, nesting, currentBucketStartNs,
- bucketSizeNs, conditionSliced, anomalyTrackers),
+ : DurationTracker(key, id, eventKey, wizard, conditionIndex, dimensionInCondition, nesting,
+ currentBucketStartNs, bucketSizeNs, conditionSliced, anomalyTrackers),
mStarted(),
mPaused() {
mLastStartTime = 0;
}
+unique_ptr<DurationTracker> OringDurationTracker::clone(const uint64_t eventTime) {
+ auto clonedTracker = make_unique<OringDurationTracker>(*this);
+ clonedTracker->mLastStartTime = eventTime;
+ clonedTracker->mDuration = 0;
+ return clonedTracker;
+}
+
bool OringDurationTracker::hitGuardRail(const HashableDimensionKey& newKey) {
// ===========GuardRail==============
// 1. Report the tuple count if the tuple count > soft limit
@@ -45,7 +53,7 @@
if (mConditionKeyMap.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
size_t newTupleCount = mConditionKeyMap.size() + 1;
StatsdStats::getInstance().noteMetricDimensionSize(
- mConfigKey, hashDimensionsValue(mTrackerId, mEventKey.getDimensionsValue()),
+ mConfigKey, hashMetricDimensionKey(mTrackerId, mEventKey),
newTupleCount);
// 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
@@ -76,7 +84,6 @@
if (mConditionSliced && mConditionKeyMap.find(key) == mConditionKeyMap.end()) {
mConditionKeyMap[key] = conditionKey;
}
-
VLOG("Oring: %s start, condition %d", key.c_str(), condition);
}
@@ -128,7 +135,7 @@
}
bool OringDurationTracker::flushIfNeeded(
- uint64_t eventTime, unordered_map<HashableDimensionKey, vector<DurationBucket>>* output) {
+ uint64_t eventTime, unordered_map<MetricDimensionKey, vector<DurationBucket>>* output) {
if (eventTime < mCurrentBucketStartTimeNs + mBucketSizeNs) {
return false;
}
@@ -184,8 +191,14 @@
++it;
continue;
}
- if (mWizard->query(mConditionTrackerIndex, mConditionKeyMap[key]) !=
- ConditionState::kTrue) {
+ std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
+ ConditionState conditionState =
+ mWizard->query(mConditionTrackerIndex, mConditionKeyMap[key],
+ mDimensionInCondition, &conditionDimensionKeySet);
+ if (conditionState != ConditionState::kTrue ||
+ (mDimensionInCondition.has_field() &&
+ conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition()) ==
+ conditionDimensionKeySet.end())) {
startedToPaused.push_back(*it);
it = mStarted.erase(it);
VLOG("Key %s started -> paused", key.c_str());
@@ -210,8 +223,14 @@
++it;
continue;
}
- if (mWizard->query(mConditionTrackerIndex, mConditionKeyMap[key]) ==
- ConditionState::kTrue) {
+ std::unordered_set<HashableDimensionKey> conditionDimensionKeySet;
+ ConditionState conditionState =
+ mWizard->query(mConditionTrackerIndex, mConditionKeyMap[key],
+ mDimensionInCondition, &conditionDimensionKeySet);
+ if (conditionState == ConditionState::kTrue &&
+ (!mDimensionInCondition.has_field() ||
+ conditionDimensionKeySet.find(mEventKey.getDimensionKeyInCondition())
+ != conditionDimensionKeySet.end())) {
pausedToStarted.push_back(*it);
it = mPaused.erase(it);
VLOG("Key %s paused -> started", key.c_str());
diff --git a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
index 43469ca..75b5a81 100644
--- a/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
+++ b/cmds/statsd/src/metrics/duration_helper/OringDurationTracker.h
@@ -28,11 +28,15 @@
class OringDurationTracker : public DurationTracker {
public:
OringDurationTracker(const ConfigKey& key, const int64_t& id,
- const HashableDimensionKey& eventKey, sp<ConditionWizard> wizard,
- int conditionIndex, bool nesting, uint64_t currentBucketStartNs,
- uint64_t bucketSizeNs, bool conditionSliced,
+ const MetricDimensionKey& eventKey, sp<ConditionWizard> wizard,
+ int conditionIndex, const FieldMatcher& dimensionInCondition, bool nesting,
+ uint64_t currentBucketStartNs, uint64_t bucketSizeNs, bool conditionSliced,
const std::vector<sp<DurationAnomalyTracker>>& anomalyTrackers);
+ OringDurationTracker(const OringDurationTracker& tracker) = default;
+
+ unique_ptr<DurationTracker> clone(const uint64_t eventTime) override;
+
void noteStart(const HashableDimensionKey& key, bool condition, const uint64_t eventTime,
const ConditionKey& conditionKey) override;
void noteStop(const HashableDimensionKey& key, const uint64_t eventTime,
@@ -44,7 +48,7 @@
bool flushIfNeeded(
uint64_t timestampNs,
- std::unordered_map<HashableDimensionKey, std::vector<DurationBucket>>* output) override;
+ std::unordered_map<MetricDimensionKey, std::vector<DurationBucket>>* output) override;
int64_t predictAnomalyTimestampNs(const DurationAnomalyTracker& anomalyTracker,
const uint64_t currentTimestamp) const override;
diff --git a/cmds/statsd/src/stats_log_util.cpp b/cmds/statsd/src/stats_log_util.cpp
index a41f30c..6c61400 100644
--- a/cmds/statsd/src/stats_log_util.cpp
+++ b/cmds/statsd/src/stats_log_util.cpp
@@ -54,6 +54,9 @@
void writeDimensionsValueProtoToStream(const DimensionsValue& dimensionsValue,
ProtoOutputStream* protoOutput) {
+ if (!dimensionsValue.has_field()) {
+ return;
+ }
protoOutput->write(FIELD_TYPE_INT32 | DIMENSIONS_VALUE_FIELD, dimensionsValue.field());
switch (dimensionsValue.value_case()) {
case DimensionsValue::ValueCase::kValueStr:
@@ -103,6 +106,9 @@
void writeFieldProtoToStream(
const Field& field, util::ProtoOutputStream* protoOutput) {
+ if (!field.has_field()) {
+ return;
+ }
protoOutput->write(FIELD_TYPE_INT32 | FIELD_FIELD, field.field());
if (field.has_position_index()) {
protoOutput->write(FIELD_TYPE_INT32 | FIELD_POSITION_INDEX, field.position_index());
diff --git a/cmds/statsd/src/stats_util.h b/cmds/statsd/src/stats_util.h
index 160b1f4..31f51a7 100644
--- a/cmds/statsd/src/stats_util.h
+++ b/cmds/statsd/src/stats_util.h
@@ -28,13 +28,14 @@
namespace statsd {
const HashableDimensionKey DEFAULT_DIMENSION_KEY = HashableDimensionKey();
+const MetricDimensionKey DEFAULT_METRIC_DIMENSION_KEY = MetricDimensionKey();
// Minimum bucket size in seconds
const long kMinBucketSizeSec = 5 * 60;
typedef std::map<int64_t, std::vector<HashableDimensionKey>> ConditionKey;
-typedef std::unordered_map<HashableDimensionKey, int64_t> DimToValMap;
+typedef std::unordered_map<MetricDimensionKey, int64_t> DimToValMap;
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/src/subscriber/SubscriberReporter.cpp b/cmds/statsd/src/subscriber/SubscriberReporter.cpp
index f912e4b..3af684f 100644
--- a/cmds/statsd/src/subscriber/SubscriberReporter.cpp
+++ b/cmds/statsd/src/subscriber/SubscriberReporter.cpp
@@ -56,7 +56,7 @@
void SubscriberReporter::alertBroadcastSubscriber(const ConfigKey& configKey,
const Subscription& subscription,
- const HashableDimensionKey& dimKey) const {
+ const MetricDimensionKey& dimKey) const {
// Reminder about ids:
// subscription id - name of the Subscription (that ties the Alert to the broadcast)
// subscription rule_id - the name of the Alert (that triggers the broadcast)
@@ -92,7 +92,7 @@
void SubscriberReporter::sendBroadcastLocked(const sp<IBinder>& intentSender,
const ConfigKey& configKey,
const Subscription& subscription,
- const HashableDimensionKey& dimKey) const {
+ const MetricDimensionKey& dimKey) const {
VLOG("SubscriberReporter::sendBroadcastLocked called.");
if (mStatsCompanionService == nullptr) {
ALOGW("Failed to send subscriber broadcast: could not access StatsCompanionService.");
@@ -107,8 +107,8 @@
}
StatsDimensionsValue SubscriberReporter::protoToStatsDimensionsValue(
- const HashableDimensionKey& dimKey) {
- return protoToStatsDimensionsValue(dimKey.getDimensionsValue());
+ const MetricDimensionKey& dimKey) {
+ return protoToStatsDimensionsValue(dimKey.getDimensionKeyInWhat().getDimensionsValue());
}
StatsDimensionsValue SubscriberReporter::protoToStatsDimensionsValue(
diff --git a/cmds/statsd/src/subscriber/SubscriberReporter.h b/cmds/statsd/src/subscriber/SubscriberReporter.h
index 5bb458a..13fc7fd 100644
--- a/cmds/statsd/src/subscriber/SubscriberReporter.h
+++ b/cmds/statsd/src/subscriber/SubscriberReporter.h
@@ -80,7 +80,7 @@
*/
void alertBroadcastSubscriber(const ConfigKey& configKey,
const Subscription& subscription,
- const HashableDimensionKey& dimKey) const;
+ const MetricDimensionKey& dimKey) const;
private:
SubscriberReporter() {};
@@ -101,7 +101,7 @@
void sendBroadcastLocked(const sp<android::IBinder>& intentSender,
const ConfigKey& configKey,
const Subscription& subscription,
- const HashableDimensionKey& dimKey) const;
+ const MetricDimensionKey& dimKey) const;
/** Converts a stats_log.proto DimensionsValue to a StatsDimensionsValue. */
static StatsDimensionsValue protoToStatsDimensionsValue(
@@ -109,7 +109,7 @@
/** Converts a HashableDimensionKey to a StatsDimensionsValue. */
static StatsDimensionsValue protoToStatsDimensionsValue(
- const HashableDimensionKey& dimKey);
+ const MetricDimensionKey& dimKey);
};
} // namespace statsd
diff --git a/cmds/statsd/tests/anomaly/AnomalyTracker_test.cpp b/cmds/statsd/tests/anomaly/AnomalyTracker_test.cpp
index 66bfa68..a415ea1 100644
--- a/cmds/statsd/tests/anomaly/AnomalyTracker_test.cpp
+++ b/cmds/statsd/tests/anomaly/AnomalyTracker_test.cpp
@@ -33,14 +33,14 @@
const ConfigKey kConfigKey(0, 12345);
-HashableDimensionKey getMockDimensionKey(int key, string value) {
+MetricDimensionKey getMockMetricDimensionKey(int key, string value) {
DimensionsValue dimensionsValue;
dimensionsValue.set_field(key);
dimensionsValue.set_value_str(value);
- return HashableDimensionKey(dimensionsValue);
+ return MetricDimensionKey(HashableDimensionKey(dimensionsValue), DEFAULT_DIMENSION_KEY);
}
-void AddValueToBucket(const std::vector<std::pair<HashableDimensionKey, long>>& key_value_pair_list,
+void AddValueToBucket(const std::vector<std::pair<MetricDimensionKey, long>>& key_value_pair_list,
std::shared_ptr<DimToValMap> bucket) {
for (auto itr = key_value_pair_list.begin(); itr != key_value_pair_list.end(); itr++) {
(*bucket)[itr->first] += itr->second;
@@ -48,7 +48,7 @@
}
std::shared_ptr<DimToValMap> MockBucket(
- const std::vector<std::pair<HashableDimensionKey, long>>& key_value_pair_list) {
+ const std::vector<std::pair<MetricDimensionKey, long>>& key_value_pair_list) {
std::shared_ptr<DimToValMap> bucket = std::make_shared<DimToValMap>();
AddValueToBucket(key_value_pair_list, bucket);
return bucket;
@@ -56,7 +56,7 @@
// Returns the value, for the given key, in that bucket, or 0 if not present.
int64_t getBucketValue(const std::shared_ptr<DimToValMap>& bucket,
- const HashableDimensionKey& key) {
+ const MetricDimensionKey& key) {
const auto& itr = bucket->find(key);
if (itr != bucket->end()) {
return itr->second;
@@ -68,14 +68,14 @@
bool detectAnomaliesPass(AnomalyTracker& tracker,
const int64_t& bucketNum,
const std::shared_ptr<DimToValMap>& currentBucket,
- const std::set<const HashableDimensionKey>& trueList,
- const std::set<const HashableDimensionKey>& falseList) {
- for (HashableDimensionKey key : trueList) {
+ const std::set<const MetricDimensionKey>& trueList,
+ const std::set<const MetricDimensionKey>& falseList) {
+ for (MetricDimensionKey key : trueList) {
if (!tracker.detectAnomaly(bucketNum, key, getBucketValue(currentBucket, key))) {
return false;
}
}
- for (HashableDimensionKey key : falseList) {
+ for (MetricDimensionKey key : falseList) {
if (tracker.detectAnomaly(bucketNum, key, getBucketValue(currentBucket, key))) {
return false;
}
@@ -100,7 +100,7 @@
void checkRefractoryTimes(AnomalyTracker& tracker,
const int64_t& currTimestampNs,
const int32_t& refractoryPeriodSec,
- const std::unordered_map<HashableDimensionKey, int64_t>& timestamps) {
+ const std::unordered_map<MetricDimensionKey, int64_t>& timestamps) {
for (const auto& kv : timestamps) {
if (kv.second < 0) {
// Make sure that, if there is a refractory period, it is already past.
@@ -124,9 +124,9 @@
alert.set_trigger_if_sum_gt(2);
AnomalyTracker anomalyTracker(alert, kConfigKey);
- HashableDimensionKey keyA = getMockDimensionKey(1, "a");
- HashableDimensionKey keyB = getMockDimensionKey(1, "b");
- HashableDimensionKey keyC = getMockDimensionKey(1, "c");
+ MetricDimensionKey keyA = getMockMetricDimensionKey(1, "a");
+ MetricDimensionKey keyB = getMockMetricDimensionKey(1, "b");
+ MetricDimensionKey keyC = getMockMetricDimensionKey(1, "c");
int64_t eventTimestamp0 = 10 * NS_PER_SEC;
int64_t eventTimestamp1 = bucketSizeNs + 11 * NS_PER_SEC;
@@ -269,11 +269,11 @@
alert.set_trigger_if_sum_gt(2);
AnomalyTracker anomalyTracker(alert, kConfigKey);
- HashableDimensionKey keyA = getMockDimensionKey(1, "a");
- HashableDimensionKey keyB = getMockDimensionKey(1, "b");
- HashableDimensionKey keyC = getMockDimensionKey(1, "c");
- HashableDimensionKey keyD = getMockDimensionKey(1, "d");
- HashableDimensionKey keyE = getMockDimensionKey(1, "e");
+ MetricDimensionKey keyA = getMockMetricDimensionKey(1, "a");
+ MetricDimensionKey keyB = getMockMetricDimensionKey(1, "b");
+ MetricDimensionKey keyC = getMockMetricDimensionKey(1, "c");
+ MetricDimensionKey keyD = getMockMetricDimensionKey(1, "d");
+ MetricDimensionKey keyE = getMockMetricDimensionKey(1, "e");
std::shared_ptr<DimToValMap> bucket9 = MockBucket({{keyA, 1}, {keyB, 2}, {keyC, 1}});
std::shared_ptr<DimToValMap> bucket16 = MockBucket({{keyB, 4}});
diff --git a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
index 819f2be..d1b7b28 100644
--- a/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
+++ b/cmds/statsd/tests/condition/SimpleConditionTracker_test.cpp
@@ -78,7 +78,7 @@
std::map<int64_t, std::vector<HashableDimensionKey>> getWakeLockQueryKey(
const Position position,
const std::vector<int> &uids, const string& conditionName) {
- std::map<int64_t, std::vector<HashableDimensionKey>> outputKeyMap;
+ std::map<int64_t, std::vector<HashableDimensionKey>> outputKeyMap;
std::vector<int> uid_indexes;
switch(position) {
case Position::FIRST:
@@ -265,6 +265,9 @@
TEST(SimpleConditionTrackerTest, TestSlicedCondition) {
for (Position position :
{ Position::ANY, Position::FIRST, Position::LAST}) {
+ FieldMatcher dimensionInCondition;
+ std::unordered_set<HashableDimensionKey> dimensionKeys;
+
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, true /*output slice by uid*/,
position);
@@ -307,7 +310,8 @@
const auto queryKey = getWakeLockQueryKey(position, uids, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by this uid
@@ -361,7 +365,8 @@
// query again
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
@@ -369,6 +374,9 @@
}
TEST(SimpleConditionTrackerTest, TestSlicedWithNoOutputDim) {
+ FieldMatcher dimensionInCondition;
+ std::unordered_set<HashableDimensionKey> dimensionKeys;
+
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, false /*slice output by uid*/,
Position::ANY /* position */);
@@ -410,7 +418,8 @@
ConditionKey queryKey;
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by this uid
@@ -452,13 +461,17 @@
// query again
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ dimensionKeys.clear();
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
TEST(SimpleConditionTrackerTest, TestStopAll) {
for (Position position :
{Position::ANY, Position::FIRST, Position::LAST}) {
+ FieldMatcher dimensionInCondition;
+ std::unordered_set<HashableDimensionKey> dimensionKeys;
SimplePredicate simplePredicate = getWakeLockHeldCondition(
true /*nesting*/, true /*default to false*/, true /*output slice by uid*/,
position);
@@ -502,7 +515,8 @@
const auto queryKey = getWakeLockQueryKey(position, uid_list1, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
// another wake lock acquired by uid2
@@ -528,8 +542,9 @@
// TEST QUERY
const auto queryKey2 = getWakeLockQueryKey(position, uid_list2, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
EXPECT_EQ(ConditionState::kTrue, conditionCache[0]);
@@ -550,15 +565,15 @@
// TEST QUERY
const auto queryKey3 = getWakeLockQueryKey(position, uid_list1, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
-
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
// TEST QUERY
const auto queryKey4 = getWakeLockQueryKey(position, uid_list2, conditionName);
conditionCache[0] = ConditionState::kNotEvaluated;
-
- conditionTracker.isConditionMet(queryKey, allPredicates, conditionCache);
+ conditionTracker.isConditionMet(queryKey, allPredicates, dimensionInCondition,
+ conditionCache, dimensionKeys);
EXPECT_EQ(ConditionState::kFalse, conditionCache[0]);
}
diff --git a/cmds/statsd/tests/dimension_test.cpp b/cmds/statsd/tests/dimension_test.cpp
new file mode 100644
index 0000000..678abae
--- /dev/null
+++ b/cmds/statsd/tests/dimension_test.cpp
@@ -0,0 +1,149 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "dimension.h"
+
+#include <gtest/gtest.h>
+
+using namespace android::os::statsd;
+
+#ifdef __ANDROID__
+
+TEST(DimensionTest, subLeafNodes) {
+ DimensionsValue dimension;
+ int tagId = 100;
+ dimension.set_field(tagId);
+ auto child = dimension.mutable_value_tuple()->add_dimensions_value();
+ child->set_field(1);
+ child->set_value_int(2000);
+
+ child = dimension.mutable_value_tuple()->add_dimensions_value();
+ child->set_field(3);
+ child->set_value_str("test");
+
+ child = dimension.mutable_value_tuple()->add_dimensions_value();
+ child->set_field(4);
+ auto grandChild = child->mutable_value_tuple()->add_dimensions_value();
+ grandChild->set_field(1);
+ grandChild->set_value_float(1.3f);
+ grandChild = child->mutable_value_tuple()->add_dimensions_value();
+ grandChild->set_field(3);
+ grandChild->set_value_str("tag");
+
+ child = dimension.mutable_value_tuple()->add_dimensions_value();
+ child->set_field(6);
+ child->set_value_bool(false);
+
+ DimensionsValue sub_dimension;
+ FieldMatcher matcher;
+
+ // Tag id not matched.
+ matcher.set_field(tagId + 1);
+ EXPECT_FALSE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Field not exist.
+ matcher.Clear();
+ matcher.set_field(tagId);
+ matcher.add_child()->set_field(5);
+ EXPECT_FALSE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Field exists.
+ matcher.Clear();
+ matcher.set_field(tagId);
+ matcher.add_child()->set_field(3);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Field exists.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ matcher.add_child()->set_field(6);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Field exists.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ matcher.add_child()->set_field(1);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Not leaf field.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ matcher.add_child()->set_field(4);
+ EXPECT_FALSE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Grand-child leaf field not exist.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ auto childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(2);
+ EXPECT_FALSE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Grand-child leaf field.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(1);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(3);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Multiple grand-child fields.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(3);
+ childMatcher->add_child()->set_field(1);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Multiple fields.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(3);
+ childMatcher->add_child()->set_field(1);
+ matcher.add_child()->set_field(3);
+ EXPECT_TRUE(getSubDimension(dimension, matcher, &sub_dimension));
+
+ // Subset of the fields not exist.
+ matcher.Clear();
+ sub_dimension.Clear();
+ matcher.set_field(tagId);
+ childMatcher = matcher.add_child();
+ childMatcher->set_field(4);
+ childMatcher->add_child()->set_field(3);
+ childMatcher->add_child()->set_field(1);
+ matcher.add_child()->set_field(2);
+ EXPECT_FALSE(getSubDimension(dimension, matcher, &sub_dimension));
+}
+
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
diff --git a/cmds/statsd/tests/e2e/DimensionInCondition_e2e_test.cpp b/cmds/statsd/tests/e2e/DimensionInCondition_e2e_test.cpp
new file mode 100644
index 0000000..b5d48ef
--- /dev/null
+++ b/cmds/statsd/tests/e2e/DimensionInCondition_e2e_test.cpp
@@ -0,0 +1,725 @@
+// Copyright (C) 2017 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include <gtest/gtest.h>
+
+#include "src/StatsLogProcessor.h"
+#include "src/stats_log_util.h"
+#include "tests/statsd_test_util.h"
+
+#include <vector>
+
+namespace android {
+namespace os {
+namespace statsd {
+
+#ifdef __ANDROID__
+
+namespace {
+
+StatsdConfig CreateCountMetricWithNoLinkConfig() {
+ StatsdConfig config;
+ auto screenBrightnessChangeAtomMatcher = CreateScreenBrightnessChangedAtomMatcher();
+ *config.add_atom_matcher() = screenBrightnessChangeAtomMatcher;
+ *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = CreateAcquireWakelockAtomMatcher();
+ *config.add_atom_matcher() = CreateReleaseWakelockAtomMatcher();
+
+ auto screenIsOffPredicate = CreateScreenIsOffPredicate();
+ *config.add_predicate() = screenIsOffPredicate;
+
+ auto holdingWakelockPredicate = CreateHoldingWakelockPredicate();
+ // The predicate is dimensioning by any attribution node and both by uid and tag.
+ *holdingWakelockPredicate.mutable_simple_predicate()->mutable_dimensions() =
+ CreateAttributionUidAndTagDimensions(
+ android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
+ *config.add_predicate() = holdingWakelockPredicate;
+
+ auto combinationPredicate = config.add_predicate();
+ combinationPredicate->set_id(987654);
+ combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
+ addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
+ addPredicateToPredicateCombination(holdingWakelockPredicate, combinationPredicate);
+
+ auto metric = config.add_count_metric();
+ metric->set_id(StringToId("ScreenBrightnessChangeMetric"));
+ metric->set_what(screenBrightnessChangeAtomMatcher.id());
+ metric->set_condition(combinationPredicate->id());
+ *metric->mutable_dimensions_in_what() = CreateDimensions(
+ android::util::SCREEN_BRIGHTNESS_CHANGED, {1 /* level */});
+ *metric->mutable_dimensions_in_condition() = CreateAttributionUidDimensions(
+ android::util::WAKELOCK_STATE_CHANGED, {Position::FIRST});
+ metric->set_bucket(ONE_MINUTE);
+ return config;
+}
+
+} // namespace
+
+TEST(DimensionInConditionE2eTest, TestCountMetricNoLink) {
+ ConfigKey cfgKey;
+ auto config = CreateCountMetricWithNoLinkConfig();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs / NS_PER_SEC, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ std::vector<AttributionNode> attributions1 =
+ {CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(222, "GMSCoreModule2")};
+
+ std::vector<AttributionNode> attributions2 =
+ {CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(555, "GMSCoreModule2")};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 100));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + bucketSizeNs + 1));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 2 * bucketSizeNs - 10));
+
+ events.push_back(CreateAcquireWakelockEvent(
+ attributions1, "wl1", bucketStartTimeNs + 200));
+ events.push_back(CreateReleaseWakelockEvent(
+ attributions1, "wl1", bucketStartTimeNs + bucketSizeNs + 1));
+
+ events.push_back(CreateAcquireWakelockEvent(
+ attributions2, "wl2", bucketStartTimeNs + bucketSizeNs - 100));
+ events.push_back(CreateReleaseWakelockEvent(
+ attributions2, "wl2", bucketStartTimeNs + 2 * bucketSizeNs - 50));
+
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 123, bucketStartTimeNs + 11));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 123, bucketStartTimeNs + 101));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 123, bucketStartTimeNs + 201));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 456, bucketStartTimeNs + 203));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 456, bucketStartTimeNs + bucketSizeNs - 99));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 456, bucketStartTimeNs + bucketSizeNs - 2));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 789, bucketStartTimeNs + bucketSizeNs - 1));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 456, bucketStartTimeNs + bucketSizeNs + 2));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 789, bucketStartTimeNs + 2 * bucketSizeNs - 11));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 789, bucketStartTimeNs + 2 * bucketSizeNs - 9));
+ events.push_back(CreateScreenBrightnessChangedEvent(
+ 789, bucketStartTimeNs + 2 * bucketSizeNs - 1));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, &reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+
+ EXPECT_EQ(countMetrics.data_size(), 7);
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs );
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 123);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 123);
+ ValidateAttributionUidDimension(data.dimensions_in_condition(), android::util::WAKELOCK_STATE_CHANGED, 111);
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 3);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 456);
+ ValidateAttributionUidDimension(data.dimensions_in_condition(), android::util::WAKELOCK_STATE_CHANGED, 111);
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).count(), 2);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).count(), 1);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 456);
+ ValidateAttributionUidDimension(data.dimensions_in_condition(), android::util::WAKELOCK_STATE_CHANGED, 333);
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 2);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+
+ data = countMetrics.data(5);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
+ ValidateAttributionUidDimension(data.dimensions_in_condition(), android::util::WAKELOCK_STATE_CHANGED, 111);
+
+ data = countMetrics.data(6);
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::SCREEN_BRIGHTNESS_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 789);
+ ValidateAttributionUidDimension(data.dimensions_in_condition(), android::util::WAKELOCK_STATE_CHANGED, 333);
+}
+
+namespace {
+
+StatsdConfig CreateCountMetricWithLinkConfig() {
+ StatsdConfig config;
+ auto appCrashMatcher = CreateProcessCrashAtomMatcher();
+ *config.add_atom_matcher() = appCrashMatcher;
+ *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
+
+ auto screenIsOffPredicate = CreateScreenIsOffPredicate();
+ auto isSyncingPredicate = CreateIsSyncingPredicate();
+ auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
+ *syncDimension = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ syncDimension->add_child()->set_field(2 /* name field*/);
+
+ *config.add_predicate() = screenIsOffPredicate;
+ *config.add_predicate() = isSyncingPredicate;
+ auto combinationPredicate = config.add_predicate();
+ combinationPredicate->set_id(987654);
+ combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
+ addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
+ addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
+
+ auto metric = config.add_count_metric();
+ metric->set_bucket(ONE_MINUTE);
+ metric->set_id(StringToId("AppCrashMetric"));
+ metric->set_what(appCrashMatcher.id());
+ metric->set_condition(combinationPredicate->id());
+ *metric->mutable_dimensions_in_what() = CreateDimensions(
+ android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED, {1 /* uid */});
+ *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+
+ // Links between crash atom and condition of app is in syncing.
+ auto links = metric->add_links();
+ links->set_condition(isSyncingPredicate.id());
+ auto dimensionWhat = links->mutable_fields_in_what();
+ dimensionWhat->set_field(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ dimensionWhat->add_child()->set_field(1); // uid field.
+ *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ return config;
+}
+
+} // namespace
+
+TEST(DimensionInConditionE2eTest, TestCountMetricWithLink) {
+ ConfigKey cfgKey;
+ auto config = CreateCountMetricWithLinkConfig();
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.count_metric(0).bucket()) * 1000000LL;
+
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs / NS_PER_SEC, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+ std::vector<AttributionNode> attributions1 =
+ {CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(222, "GMSCoreModule2")};
+
+ std::vector<AttributionNode> attributions2 =
+ {CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(555, "GMSCoreModule2")};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+
+ events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 11));
+ events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 101));
+ events.push_back(CreateAppCrashEvent(222, bucketStartTimeNs + 101));
+
+ events.push_back(CreateAppCrashEvent(222, bucketStartTimeNs + 201));
+ events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 211));
+ events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + 211));
+
+ events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + 401));
+ events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + 401));
+ events.push_back(CreateAppCrashEvent(555, bucketStartTimeNs + 401));
+
+ events.push_back(CreateAppCrashEvent(111, bucketStartTimeNs + bucketSizeNs + 301));
+ events.push_back(CreateAppCrashEvent(333, bucketStartTimeNs + bucketSizeNs + 301));
+
+ events.push_back(CreateAppCrashEvent(777, bucketStartTimeNs + bucketSizeNs + 701));
+
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 100));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 202));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + bucketSizeNs + 700));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 300));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadDoc",
+ bucketStartTimeNs + bucketSizeNs - 1));
+
+ events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 400));
+ events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 600));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, &reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ StatsLogReport::CountMetricDataWrapper countMetrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).count_metrics(), &countMetrics);
+
+ EXPECT_EQ(countMetrics.data_size(), 5);
+ auto data = countMetrics.data(0);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+
+ data = countMetrics.data(1);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111, "App1");
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 2);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+
+ data = countMetrics.data(2);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 222);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 2);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+
+ data = countMetrics.data(3);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 333);
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333, "App2");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).count(), 1);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+
+ data = countMetrics.data(4);
+ EXPECT_EQ(data.dimensions_in_what().field(), android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value_size(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 777);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).count(), 1);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+}
+
+namespace {
+
+StatsdConfig CreateDurationMetricConfigNoLink(DurationMetric::AggregationType aggregationType) {
+ StatsdConfig config;
+ *config.add_atom_matcher() = CreateBatterySaverModeStartAtomMatcher();
+ *config.add_atom_matcher() = CreateBatterySaverModeStopAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
+
+ auto inBatterySaverModePredicate = CreateBatterySaverModePredicate();
+
+ auto screenIsOffPredicate = CreateScreenIsOffPredicate();
+ auto isSyncingPredicate = CreateIsSyncingPredicate();
+ auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
+ *syncDimension = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ syncDimension->add_child()->set_field(2 /* name field */);
+
+ *config.add_predicate() = inBatterySaverModePredicate;
+ *config.add_predicate() = screenIsOffPredicate;
+ *config.add_predicate() = isSyncingPredicate;
+ auto combinationPredicate = config.add_predicate();
+ combinationPredicate->set_id(987654);
+ combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
+ addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
+ addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
+
+ auto metric = config.add_duration_metric();
+ metric->set_bucket(ONE_MINUTE);
+ metric->set_id(StringToId("BatterySaverModeDurationMetric"));
+ metric->set_what(inBatterySaverModePredicate.id());
+ metric->set_condition(combinationPredicate->id());
+ *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ return config;
+}
+
+} // namespace
+
+
+TEST(DimensionInConditionE2eTest, TestDurationMetricNoLink) {
+ for (auto aggregationType : { DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
+ ConfigKey cfgKey;
+ auto config = CreateDurationMetricConfigNoLink(aggregationType);
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs / NS_PER_SEC, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ std::vector<AttributionNode> attributions1 =
+ {CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(222, "GMSCoreModule2")};
+
+ std::vector<AttributionNode> attributions2 =
+ {CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(555, "GMSCoreModule2")};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+
+ events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 1));
+ events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 101));
+ events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 110));
+
+ events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 201));
+ events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + 500));
+
+ events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + 600));
+ events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + bucketSizeNs + 850));
+
+ events.push_back(CreateBatterySaverOnEvent(bucketStartTimeNs + bucketSizeNs + 870));
+ events.push_back(CreateBatterySaverOffEvent(bucketStartTimeNs + bucketSizeNs + 900));
+
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 100));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 202));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + bucketSizeNs + 800));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 300));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadDoc",
+ bucketStartTimeNs + bucketSizeNs - 1));
+
+ events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 401));
+ events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 700));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, &reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ StatsLogReport::DurationMetricDataWrapper metrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).duration_metrics(), &metrics);
+
+ EXPECT_EQ(metrics.data_size(), 3);
+ auto data = metrics.data(0);
+ EXPECT_FALSE(data.dimensions_in_what().has_field());
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), 9);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).duration_nanos(), 30);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+
+ data = metrics.data(1);
+ EXPECT_FALSE(data.dimensions_in_what().has_field());
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111, "App1");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 201 + bucketSizeNs - 600);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).duration_nanos(), 300);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+
+ data = metrics.data(2);
+ EXPECT_FALSE(data.dimensions_in_what().has_field());
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333, "App2");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), 500 - 401 + bucketSizeNs - 600);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+ }
+}
+
+namespace {
+
+StatsdConfig CreateDurationMetricConfigWithLink(DurationMetric::AggregationType aggregationType) {
+ StatsdConfig config;
+ *config.add_atom_matcher() = CreateMoveToBackgroundAtomMatcher();
+ *config.add_atom_matcher() = CreateMoveToForegroundAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOnAtomMatcher();
+ *config.add_atom_matcher() = CreateScreenTurnedOffAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncStartAtomMatcher();
+ *config.add_atom_matcher() = CreateSyncEndAtomMatcher();
+
+ auto screenIsOffPredicate = CreateScreenIsOffPredicate();
+ auto isSyncingPredicate = CreateIsSyncingPredicate();
+ auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
+ *syncDimension = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ syncDimension->add_child()->set_field(2 /* name field */);
+
+ auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
+ *isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
+ CreateDimensions(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {1 /* uid field */ });
+
+ *config.add_predicate() = screenIsOffPredicate;
+ *config.add_predicate() = isSyncingPredicate;
+ *config.add_predicate() = isInBackgroundPredicate;
+ auto combinationPredicate = config.add_predicate();
+ combinationPredicate->set_id(987654);
+ combinationPredicate->mutable_combination()->set_operation(LogicalOperation::OR);
+ addPredicateToPredicateCombination(screenIsOffPredicate, combinationPredicate);
+ addPredicateToPredicateCombination(isSyncingPredicate, combinationPredicate);
+
+ auto metric = config.add_duration_metric();
+ metric->set_bucket(ONE_MINUTE);
+ metric->set_id(StringToId("AppInBackgroundMetric"));
+ metric->set_what(isInBackgroundPredicate.id());
+ metric->set_condition(combinationPredicate->id());
+ *metric->mutable_dimensions_in_what() = CreateDimensions(
+ android::util::ACTIVITY_FOREGROUND_STATE_CHANGED, {1 /* uid field */ });
+ *metric->mutable_dimensions_in_condition() = CreateAttributionUidAndTagDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+
+ // Links between crash atom and condition of app is in syncing.
+ auto links = metric->add_links();
+ links->set_condition(isSyncingPredicate.id());
+ auto dimensionWhat = links->mutable_fields_in_what();
+ dimensionWhat->set_field(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED);
+ dimensionWhat->add_child()->set_field(1); // uid field.
+ *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ return config;
+}
+
+} // namespace
+
+TEST(DimensionInConditionE2eTest, TestDurationMetricWithLink) {
+ for (auto aggregationType : { DurationMetric::SUM, DurationMetric::MAX_SPARSE}) {
+ ConfigKey cfgKey;
+ auto config = CreateDurationMetricConfigWithLink(aggregationType);
+ int64_t bucketStartTimeNs = 10000000000;
+ int64_t bucketSizeNs =
+ TimeUnitToBucketSizeInMillis(config.duration_metric(0).bucket()) * 1000000LL;
+
+ auto processor = CreateStatsLogProcessor(bucketStartTimeNs / NS_PER_SEC, config, cfgKey);
+ EXPECT_EQ(processor->mMetricsManagers.size(), 1u);
+ EXPECT_TRUE(processor->mMetricsManagers.begin()->second->isConfigValid());
+
+ std::vector<AttributionNode> attributions1 =
+ {CreateAttribution(111, "App1"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(222, "GMSCoreModule2")};
+
+ std::vector<AttributionNode> attributions2 =
+ {CreateAttribution(333, "App2"), CreateAttribution(222, "GMSCoreModule1"),
+ CreateAttribution(555, "GMSCoreModule2")};
+
+ std::vector<std::unique_ptr<LogEvent>> events;
+
+ events.push_back(CreateMoveToBackgroundEvent(111, bucketStartTimeNs + 101));
+ events.push_back(CreateMoveToForegroundEvent(111, bucketStartTimeNs + 110));
+
+ events.push_back(CreateMoveToBackgroundEvent(111, bucketStartTimeNs + 201));
+ events.push_back(CreateMoveToForegroundEvent(111, bucketStartTimeNs + bucketSizeNs + 100));
+
+ events.push_back(CreateMoveToBackgroundEvent(333, bucketStartTimeNs + 399));
+ events.push_back(CreateMoveToForegroundEvent(333, bucketStartTimeNs + bucketSizeNs + 800));
+
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 10));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + 100));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_ON, bucketStartTimeNs + 202));
+ events.push_back(CreateScreenStateChangedEvent(
+ android::view::DISPLAY_STATE_OFF, bucketStartTimeNs + bucketSizeNs + 801));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadEmail", bucketStartTimeNs + 200));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 300));
+
+ events.push_back(CreateSyncStartEvent(attributions1, "ReadDoc", bucketStartTimeNs + 400));
+ events.push_back(CreateSyncEndEvent(attributions1, "ReadDoc",
+ bucketStartTimeNs + bucketSizeNs - 1));
+
+ events.push_back(CreateSyncStartEvent(attributions2, "ReadEmail", bucketStartTimeNs + 401));
+ events.push_back(CreateSyncEndEvent(attributions2, "ReadEmail",
+ bucketStartTimeNs + bucketSizeNs + 700));
+
+ sortLogEventsByTimestamp(&events);
+
+ for (const auto& event : events) {
+ processor->OnLogEvent(event.get());
+ }
+
+ ConfigMetricsReportList reports;
+ processor->onDumpReport(cfgKey, bucketStartTimeNs + 2 * bucketSizeNs + 1, &reports);
+
+ EXPECT_EQ(reports.reports_size(), 1);
+ EXPECT_EQ(reports.reports(0).metrics_size(), 1);
+ StatsLogReport::DurationMetricDataWrapper metrics;
+ sortMetricDataByDimensionsValue(reports.reports(0).metrics(0).duration_metrics(), &metrics);
+
+ EXPECT_EQ(metrics.data_size(), 3);
+ auto data = metrics.data(0);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
+ EXPECT_FALSE(data.dimensions_in_condition().has_field());
+ EXPECT_EQ(data.bucket_info_size(), 1);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), 9);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+
+ data = metrics.data(1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 111);
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 111, "App1");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 201);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).duration_nanos(), 100);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+
+ data = metrics.data(2);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).field(), 1);
+ EXPECT_EQ(data.dimensions_in_what().value_tuple().dimensions_value(0).value_int(), 333);
+ ValidateAttributionUidAndTagDimension(
+ data.dimensions_in_condition(), android::util::SYNC_STATE_CHANGED, 333, "App2");
+ EXPECT_EQ(data.bucket_info_size(), 2);
+ EXPECT_EQ(data.bucket_info(0).duration_nanos(), bucketSizeNs - 401);
+ EXPECT_EQ(data.bucket_info(0).start_bucket_nanos(), bucketStartTimeNs);
+ EXPECT_EQ(data.bucket_info(0).end_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).duration_nanos(), 700);
+ EXPECT_EQ(data.bucket_info(1).start_bucket_nanos(), bucketStartTimeNs + bucketSizeNs);
+ EXPECT_EQ(data.bucket_info(1).end_bucket_nanos(), bucketStartTimeNs + 2 * bucketSizeNs);
+ }
+}
+
+#else
+GTEST_LOG_(INFO) << "This test does nothing.\n";
+#endif
+
+} // namespace statsd
+} // namespace os
+} // namespace android
\ No newline at end of file
diff --git a/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp b/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
index 4504a95..233031c 100644
--- a/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
+++ b/cmds/statsd/tests/e2e/MetricConditionLink_e2e_test.cpp
@@ -44,9 +44,10 @@
auto screenIsOffPredicate = CreateScreenIsOffPredicate();
auto isSyncingPredicate = CreateIsSyncingPredicate();
- *isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions() =
- CreateDimensions(
- android::util::SYNC_STATE_CHANGED, {1 /* uid field */, 2 /* name field*/});
+ auto syncDimension = isSyncingPredicate.mutable_simple_predicate()->mutable_dimensions();
+ *syncDimension = CreateAttributionUidDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
+ syncDimension->add_child()->set_field(2 /* name field*/);
auto isInBackgroundPredicate = CreateIsInBackgroundPredicate();
*isInBackgroundPredicate.mutable_simple_predicate()->mutable_dimensions() =
@@ -78,9 +79,8 @@
auto dimensionWhat = links->mutable_fields_in_what();
dimensionWhat->set_field(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
dimensionWhat->add_child()->set_field(1); // uid field.
- auto dimensionCondition = links->mutable_fields_in_condition();
- dimensionCondition->set_field(android::util::SYNC_STATE_CHANGED);
- dimensionCondition->add_child()->set_field(1); // uid field.
+ *links->mutable_fields_in_condition() = CreateAttributionUidDimensions(
+ android::util::SYNC_STATE_CHANGED, {Position::FIRST});
// Links between crash atom and condition of app is in background.
links = countMetric->add_links();
@@ -88,7 +88,7 @@
dimensionWhat = links->mutable_fields_in_what();
dimensionWhat->set_field(android::util::PROCESS_LIFE_CYCLE_STATE_CHANGED);
dimensionWhat->add_child()->set_field(1); // uid field.
- dimensionCondition = links->mutable_fields_in_condition();
+ auto dimensionCondition = links->mutable_fields_in_condition();
dimensionCondition->set_field(android::util::ACTIVITY_FOREGROUND_STATE_CHANGED);
dimensionCondition->add_child()->set_field(1); // uid field.
return config;
@@ -132,12 +132,14 @@
CreateScreenStateChangedEvent(android::view::DisplayStateEnum::DISPLAY_STATE_ON,
bucketStartTimeNs + 2 * bucketSizeNs - 100);
+ std::vector<AttributionNode> attributions =
+ {CreateAttribution(appUid, "App1"), CreateAttribution(appUid + 1, "GMSCoreModule1")};
auto syncOnEvent1 =
- CreateSyncStartEvent(appUid, "ReadEmail", bucketStartTimeNs + 50);
+ CreateSyncStartEvent(attributions, "ReadEmail", bucketStartTimeNs + 50);
auto syncOffEvent1 =
- CreateSyncEndEvent(appUid, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 300);
+ CreateSyncEndEvent(attributions, "ReadEmail", bucketStartTimeNs + bucketSizeNs + 300);
auto syncOnEvent2 =
- CreateSyncStartEvent(appUid, "ReadDoc", bucketStartTimeNs + bucketSizeNs + 2000);
+ CreateSyncStartEvent(attributions, "ReadDoc", bucketStartTimeNs + bucketSizeNs + 2000);
auto moveToBackgroundEvent1 =
CreateMoveToBackgroundEvent(appUid, bucketStartTimeNs + 15);
diff --git a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
index 4ad2097..50b3532 100644
--- a/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/CountMetricProducer_test.cpp
@@ -67,9 +67,9 @@
// Flushes.
countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
- EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
countProducer.mPastBuckets.end());
- const auto& buckets = countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(1UL, buckets.size());
EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
@@ -80,10 +80,10 @@
countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
countProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
- EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
countProducer.mPastBuckets.end());
- EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY].size());
- const auto& bucketInfo2 = countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY][1];
+ EXPECT_EQ(2UL, countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY].size());
+ const auto& bucketInfo2 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY][1];
EXPECT_EQ(bucket2StartTimeNs, bucketInfo2.mBucketStartNs);
EXPECT_EQ(bucket2StartTimeNs + bucketSizeNs, bucketInfo2.mBucketEndNs);
EXPECT_EQ(1LL, bucketInfo2.mCount);
@@ -91,9 +91,9 @@
// nothing happens in bucket 3. we should not record anything for bucket 3.
countProducer.flushIfNeededLocked(bucketStartTimeNs + 3 * bucketSizeNs + 1);
EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
- EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
countProducer.mPastBuckets.end());
- const auto& buckets3 = countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets3 = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(2UL, buckets3.size());
}
@@ -124,10 +124,10 @@
countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
- EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
countProducer.mPastBuckets.end());
{
- const auto& buckets = countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(1UL, buckets.size());
const auto& bucketInfo = buckets[0];
EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
@@ -167,9 +167,9 @@
{getMockedDimensionKey(conditionTagId, 2, "222")};
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- EXPECT_CALL(*wizard, query(_, key1)).WillOnce(Return(ConditionState::kFalse));
+ EXPECT_CALL(*wizard, query(_, key1, _, _)).WillOnce(Return(ConditionState::kFalse));
- EXPECT_CALL(*wizard, query(_, key2)).WillOnce(Return(ConditionState::kTrue));
+ EXPECT_CALL(*wizard, query(_, key2, _, _)).WillOnce(Return(ConditionState::kTrue));
CountMetricProducer countProducer(kConfigKey, metric, 1 /*condition tracker index*/, wizard,
bucketStartTimeNs);
@@ -181,9 +181,9 @@
countProducer.onMatchedLogEvent(1 /*log matcher index*/, event2);
countProducer.flushIfNeededLocked(bucketStartTimeNs + bucketSizeNs + 1);
EXPECT_EQ(1UL, countProducer.mPastBuckets.size());
- EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(countProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
countProducer.mPastBuckets.end());
- const auto& buckets = countProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets = countProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(1UL, buckets.size());
const auto& bucketInfo = buckets[0];
EXPECT_EQ(bucketStartTimeNs, bucketInfo.mBucketStartNs);
@@ -229,13 +229,13 @@
EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
EXPECT_EQ(2L, countProducer.mCurrentSlicedCounter->begin()->second);
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY), 0U);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
// One event in bucket #2. No alarm as bucket #0 is trashed out.
countProducer.onMatchedLogEvent(1 /*log matcher index*/, event3);
EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
EXPECT_EQ(1L, countProducer.mCurrentSlicedCounter->begin()->second);
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY), 0U);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
// Two events in bucket #3.
countProducer.onMatchedLogEvent(1 /*log matcher index*/, event4);
@@ -244,13 +244,13 @@
EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
EXPECT_EQ(3L, countProducer.mCurrentSlicedCounter->begin()->second);
// Anomaly at event 6 is within refractory period. The alarm is at event 5 timestamp not event 6
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event5.GetTimestampNs() / NS_PER_SEC + refPeriodSec);
countProducer.onMatchedLogEvent(1 /*log matcher index*/, event7);
EXPECT_EQ(1UL, countProducer.mCurrentSlicedCounter->size());
EXPECT_EQ(4L, countProducer.mCurrentSlicedCounter->begin()->second);
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event7.GetTimestampNs() / NS_PER_SEC + refPeriodSec);
}
diff --git a/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp b/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
index a59f1fe..c9fe252 100644
--- a/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/DurationMetricProducer_test.cpp
@@ -62,9 +62,9 @@
durationProducer.onMatchedLogEvent(2 /* stop index*/, event2);
durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
- EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
durationProducer.mPastBuckets.end());
- const auto& buckets = durationProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(2UL, buckets.size());
EXPECT_EQ(bucketStartTimeNs, buckets[0].mBucketStartNs);
EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[0].mBucketEndNs);
@@ -107,9 +107,9 @@
durationProducer.onMatchedLogEvent(2 /* stop index*/, event4);
durationProducer.flushIfNeededLocked(bucketStartTimeNs + 2 * bucketSizeNs + 1);
EXPECT_EQ(1UL, durationProducer.mPastBuckets.size());
- EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_DIMENSION_KEY) !=
+ EXPECT_TRUE(durationProducer.mPastBuckets.find(DEFAULT_METRIC_DIMENSION_KEY) !=
durationProducer.mPastBuckets.end());
- const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_DIMENSION_KEY];
+ const auto& buckets2 = durationProducer.mPastBuckets[DEFAULT_METRIC_DIMENSION_KEY];
EXPECT_EQ(1UL, buckets2.size());
EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets2[0].mBucketStartNs);
EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets2[0].mBucketEndNs);
diff --git a/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp b/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
index da00cae..3deab37 100644
--- a/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/EventMetricProducer_test.cpp
@@ -114,9 +114,9 @@
key2[StringToId("APP_IN_BACKGROUND_PER_UID")] = {getMockedDimensionKey(conditionTagId, 2, "222")};
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- EXPECT_CALL(*wizard, query(_, key1)).WillOnce(Return(ConditionState::kFalse));
+ EXPECT_CALL(*wizard, query(_, key1, _, _)).WillOnce(Return(ConditionState::kFalse));
- EXPECT_CALL(*wizard, query(_, key2)).WillOnce(Return(ConditionState::kTrue));
+ EXPECT_CALL(*wizard, query(_, key2, _, _)).WillOnce(Return(ConditionState::kTrue));
EventMetricProducer eventProducer(kConfigKey, metric, 1, wizard, bucketStartTimeNs);
diff --git a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
index 4533ac6..58be5b0 100644
--- a/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/GaugeMetricProducer_test.cpp
@@ -218,7 +218,7 @@
EXPECT_EQ(13L,
gaugeProducer.mCurrentSlicedBucket->begin()->
second.front().mFields->begin()->second.value_int());
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY), 0U);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
std::shared_ptr<LogEvent> event2 =
std::make_shared<LogEvent>(tagId, bucketStartTimeNs + bucketSizeNs + 20);
@@ -231,7 +231,7 @@
EXPECT_EQ(15L,
gaugeProducer.mCurrentSlicedBucket->begin()->
second.front().mFields->begin()->second.value_int());
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event2->GetTimestampNs() / NS_PER_SEC + refPeriodSec);
std::shared_ptr<LogEvent> event3 =
@@ -245,7 +245,7 @@
EXPECT_EQ(26L,
gaugeProducer.mCurrentSlicedBucket->begin()->
second.front().mFields->begin()->second.value_int());
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event2->GetTimestampNs() / NS_PER_SEC + refPeriodSec);
// The event4 does not have the gauge field. Thus the current bucket value is 0.
diff --git a/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp b/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
index 0772b0d40..203f028 100644
--- a/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
+++ b/cmds/statsd/tests/metrics/MaxDurationTracker_test.cpp
@@ -41,22 +41,24 @@
const int TagId = 1;
-const HashableDimensionKey eventKey = getMockedDimensionKey(TagId, 0, "1");
-const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
-const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
-const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
TEST(MaxDurationTrackerTest, TestSimpleMaxDuration) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
+ const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+ const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
+
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(key1, true, bucketStartTimeNs, ConditionKey());
// Event starts again. This would not change anything as it already starts.
@@ -75,16 +77,22 @@
}
TEST(MaxDurationTrackerTest, TestStopAll) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
+ const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+ const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
+
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(key1, true, bucketStartTimeNs + 1, ConditionKey());
@@ -105,21 +113,26 @@
}
TEST(MaxDurationTrackerTest, TestCrossBucketBoundary) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
+ const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+ const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, false, {});
// The event starts.
tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey());
- // Starts again. Does not change anything.
+ // Starts again. Does not DEFAULT_DIMENSION_KEY anything.
tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + bucketSizeNs + 1,
ConditionKey());
@@ -135,16 +148,21 @@
}
TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
+ const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+ const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, true, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, false, {});
// 2 starts
tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey());
@@ -160,7 +178,8 @@
EXPECT_EQ(bucketSizeNs, buckets[eventKey][1].mDuration);
// real stop now.
- tracker.noteStop(DEFAULT_DIMENSION_KEY, bucketStartTimeNs + (2 * bucketSizeNs) + 5, false);
+ tracker.noteStop(DEFAULT_DIMENSION_KEY,
+ bucketStartTimeNs + (2 * bucketSizeNs) + 5, false);
tracker.flushIfNeeded(bucketStartTimeNs + (3 * bucketSizeNs) + 1, &buckets);
EXPECT_EQ(3u, buckets[eventKey].size());
@@ -170,16 +189,20 @@
}
TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
+ const std::vector<HashableDimensionKey> conditionKey = {getMockedDimensionKey(TagId, 4, "1")};
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conditionKey1;
- HashableDimensionKey eventKey = getMockedDimensionKey(TagId, 2, "maps");
+ MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
- EXPECT_CALL(*wizard, query(_, conditionKey1)) // #4
+ EXPECT_CALL(*wizard, query(_, conditionKey1, _, _)) // #4
.WillOnce(Return(ConditionState::kFalse));
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
@@ -187,8 +210,8 @@
int64_t durationTimeNs = 2 * 1000;
int64_t metricId = 1;
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
- bucketSizeNs, true, {});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, true, {});
EXPECT_TRUE(tracker.mAnomalyTrackers.empty());
tracker.noteStart(key1, true, eventStartTimeNs, conditionKey1);
@@ -204,6 +227,10 @@
}
TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
+ const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
+ const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
+ FieldMatcher dimensionInCondition;
int64_t metricId = 1;
Alert alert;
alert.set_id(101);
@@ -213,7 +240,7 @@
const int32_t refPeriodSec = 1;
alert.set_refractory_period_secs(refPeriodSec);
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
uint64_t bucketStartTimeNs = 10 * NS_PER_SEC;
@@ -221,8 +248,8 @@
uint64_t bucketSizeNs = 30 * NS_PER_SEC;
sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, kConfigKey);
- MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, true, bucketStartTimeNs,
- bucketSizeNs, false, {anomalyTracker});
+ MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, false, {anomalyTracker});
tracker.noteStart(key1, true, eventStartTimeNs, ConditionKey());
tracker.noteStop(key1, eventStartTimeNs + 10, false);
diff --git a/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp b/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
index 6b8893e..80e16a1 100644
--- a/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
+++ b/cmds/statsd/tests/metrics/OringDurationTracker_test.cpp
@@ -38,24 +38,26 @@
const ConfigKey kConfigKey(0, 12345);
const int TagId = 1;
const int64_t metricId = 123;
-const HashableDimensionKey eventKey = getMockedDimensionKey(TagId, 0, "event");
-
-const std::vector<HashableDimensionKey> kConditionKey1 = {getMockedDimensionKey(TagId, 1, "maps")};
-const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
-const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
TEST(OringDurationTrackerTest, TestDurationOverlap) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
uint64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false,
- bucketStartTimeNs, bucketSizeNs, false, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, ConditionKey());
EXPECT_EQ((long long)eventStartTimeNs, tracker.mLastStartTime);
@@ -71,16 +73,23 @@
}
TEST(OringDurationTrackerTest, TestDurationNested) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, ConditionKey());
tracker.noteStart(kEventKey1, true, eventStartTimeNs + 10, ConditionKey()); // overlapping wl
@@ -95,16 +104,23 @@
}
TEST(OringDurationTrackerTest, TestStopAll) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, ConditionKey());
tracker.noteStart(kEventKey2, true, eventStartTimeNs + 10, ConditionKey()); // overlapping wl
@@ -118,17 +134,24 @@
}
TEST(OringDurationTrackerTest, TestCrossBucketBoundary) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
uint64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true, bucketStartTimeNs,
- bucketSizeNs, false, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, false, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, ConditionKey());
EXPECT_EQ((long long)eventStartTimeNs, tracker.mLastStartTime);
@@ -150,23 +173,30 @@
}
TEST(OringDurationTrackerTest, TestDurationConditionChange) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1)) // #4
+ EXPECT_CALL(*wizard, query(_, key1, _, _)) // #4
.WillOnce(Return(ConditionState::kFalse));
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
uint64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false,
- bucketStartTimeNs, bucketSizeNs, true, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, true, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, key1);
@@ -181,25 +211,32 @@
}
TEST(OringDurationTrackerTest, TestDurationConditionChange2) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1))
+ EXPECT_CALL(*wizard, query(_, key1, _, _))
.Times(2)
.WillOnce(Return(ConditionState::kFalse))
.WillOnce(Return(ConditionState::kTrue));
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
uint64_t durationTimeNs = 2 * 1000;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false,
- bucketStartTimeNs, bucketSizeNs, true, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ false, bucketStartTimeNs, bucketSizeNs, true, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, key1);
// condition to false; record duration 5n
@@ -216,22 +253,29 @@
}
TEST(OringDurationTrackerTest, TestDurationConditionChangeNested) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey key1;
key1[StringToId("APP_BACKGROUND")] = kConditionKey1;
- EXPECT_CALL(*wizard, query(_, key1)) // #4
+ EXPECT_CALL(*wizard, query(_, key1, _, _)) // #4
.WillOnce(Return(ConditionState::kFalse));
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
uint64_t bucketStartTimeNs = 10000000000;
uint64_t eventStartTimeNs = bucketStartTimeNs + 1;
uint64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true, bucketStartTimeNs,
- bucketSizeNs, true, {});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, true, {});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, key1);
tracker.noteStart(kEventKey1, true, eventStartTimeNs + 2, key1);
@@ -249,6 +293,13 @@
}
TEST(OringDurationTrackerTest, TestPredictAnomalyTimestamp) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -256,7 +307,7 @@
alert.set_num_buckets(2);
alert.set_refractory_period_secs(1);
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
uint64_t bucketStartTimeNs = 10 * NS_PER_SEC;
@@ -264,8 +315,8 @@
uint64_t bucketSizeNs = 30 * NS_PER_SEC;
sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, kConfigKey);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true, bucketStartTimeNs,
- bucketSizeNs, true, {anomalyTracker});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true, bucketStartTimeNs, bucketSizeNs, true, {anomalyTracker});
// Nothing in the past bucket.
tracker.noteStart(DEFAULT_DIMENSION_KEY, true, eventStartTimeNs, ConditionKey());
@@ -310,6 +361,12 @@
}
TEST(OringDurationTrackerTest, TestAnomalyDetectionExpiredAlarm) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 = {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -318,7 +375,7 @@
const int32_t refPeriodSec = 45;
alert.set_refractory_period_secs(refPeriodSec);
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
uint64_t bucketStartTimeNs = 10 * NS_PER_SEC;
@@ -326,8 +383,8 @@
uint64_t bucketSizeNs = 30 * NS_PER_SEC;
sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, kConfigKey);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true /*nesting*/,
- bucketStartTimeNs, bucketSizeNs, false, {anomalyTracker});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true /*nesting*/, bucketStartTimeNs, bucketSizeNs, false, {anomalyTracker});
tracker.noteStart(kEventKey1, true, eventStartTimeNs, ConditionKey());
tracker.noteStop(kEventKey1, eventStartTimeNs + 10, false);
@@ -352,6 +409,13 @@
}
TEST(OringDurationTrackerTest, TestAnomalyDetectionFiredAlarm) {
+ const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "event");
+
+ const std::vector<HashableDimensionKey> kConditionKey1 =
+ {getMockedDimensionKey(TagId, 1, "maps")};
+ const HashableDimensionKey kEventKey1 = getMockedDimensionKey(TagId, 2, "maps");
+ const HashableDimensionKey kEventKey2 = getMockedDimensionKey(TagId, 3, "maps");
+ FieldMatcher dimensionInCondition;
Alert alert;
alert.set_id(101);
alert.set_metric_id(1);
@@ -360,7 +424,7 @@
const int32_t refPeriodSec = 45;
alert.set_refractory_period_secs(refPeriodSec);
- unordered_map<HashableDimensionKey, vector<DurationBucket>> buckets;
+ unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
ConditionKey conkey;
conkey[StringToId("APP_BACKGROUND")] = kConditionKey1;
@@ -369,8 +433,9 @@
uint64_t bucketSizeNs = 30 * NS_PER_SEC;
sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, kConfigKey);
- OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, true /*nesting*/,
- bucketStartTimeNs, bucketSizeNs, false, {anomalyTracker});
+ OringDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, dimensionInCondition,
+ true /*nesting*/, bucketStartTimeNs, bucketSizeNs, false,
+ {anomalyTracker});
tracker.noteStart(kEventKey1, true, 15 * NS_PER_SEC, conkey); // start key1
EXPECT_EQ(1u, anomalyTracker->mAlarms.size());
diff --git a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
index fff3dbf..55c078d 100644
--- a/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
+++ b/cmds/statsd/tests/metrics/ValueMetricProducer_test.cpp
@@ -299,26 +299,26 @@
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event1);
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event2);
// Value sum == 30 <= 130.
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY), 0U);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
// One event in bucket #2. No alarm as bucket #0 is trashed out.
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event3);
// Value sum == 130 <= 130.
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY), 0U);
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY), 0U);
// Three events in bucket #3.
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event4);
// Anomaly at event 4 since Value sum == 131 > 130!
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event4->GetTimestampNs() / NS_PER_SEC + refPeriodSec);
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event5);
// Event 5 is within 3 sec refractory period. Thus last alarm timestamp is still event4.
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event4->GetTimestampNs() / NS_PER_SEC + refPeriodSec);
valueProducer.onMatchedLogEvent(1 /*log matcher index*/, *event6);
// Anomaly at event 6 since Value sum == 160 > 130 and after refractory period.
- EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_DIMENSION_KEY),
+ EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(DEFAULT_METRIC_DIMENSION_KEY),
event6->GetTimestampNs() / NS_PER_SEC + refPeriodSec);
}
diff --git a/cmds/statsd/tests/metrics/metrics_test_helper.cpp b/cmds/statsd/tests/metrics/metrics_test_helper.cpp
index fc7245c..ab9345a 100644
--- a/cmds/statsd/tests/metrics/metrics_test_helper.cpp
+++ b/cmds/statsd/tests/metrics/metrics_test_helper.cpp
@@ -26,6 +26,13 @@
return HashableDimensionKey(dimensionsValue);
}
+MetricDimensionKey getMockedMetricDimensionKey(int tagId, int key, string value) {
+ DimensionsValue dimensionsValue;
+ dimensionsValue.set_field(tagId);
+ dimensionsValue.mutable_value_tuple()->add_dimensions_value()->set_field(key);
+ dimensionsValue.mutable_value_tuple()->mutable_dimensions_value(0)->set_value_str(value);
+ return MetricDimensionKey(HashableDimensionKey(dimensionsValue), DEFAULT_DIMENSION_KEY);
+}
} // namespace statsd
} // namespace os
} // namespace android
\ No newline at end of file
diff --git a/cmds/statsd/tests/metrics/metrics_test_helper.h b/cmds/statsd/tests/metrics/metrics_test_helper.h
index 23e86f9..0a97456 100644
--- a/cmds/statsd/tests/metrics/metrics_test_helper.h
+++ b/cmds/statsd/tests/metrics/metrics_test_helper.h
@@ -25,10 +25,12 @@
class MockConditionWizard : public ConditionWizard {
public:
- MOCK_METHOD2(
+ MOCK_METHOD4(
query,
ConditionState(const int conditionIndex,
- const ConditionKey& conditionParameters));
+ const ConditionKey& conditionParameters,
+ const FieldMatcher& dimensionFields,
+ std::unordered_set<HashableDimensionKey> *dimensionKeySet));
};
class MockStatsPullerManager : public StatsPullerManager {
@@ -39,6 +41,7 @@
};
HashableDimensionKey getMockedDimensionKey(int tagId, int key, std::string value);
+MetricDimensionKey getMockedMetricDimensionKey(int tagId, int key, std::string value);
} // namespace statsd
} // namespace os
diff --git a/cmds/statsd/tests/statsd_test_util.cpp b/cmds/statsd/tests/statsd_test_util.cpp
index 9f4582d..13055cb 100644
--- a/cmds/statsd/tests/statsd_test_util.cpp
+++ b/cmds/statsd/tests/statsd_test_util.cpp
@@ -12,7 +12,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-#include <gtest/gtest.h>
#include "statsd_test_util.h"
namespace android {
@@ -27,6 +26,22 @@
return atom_matcher;
}
+AtomMatcher CreateScreenBrightnessChangedAtomMatcher() {
+ AtomMatcher atom_matcher;
+ atom_matcher.set_id(StringToId("ScreenBrightnessChanged"));
+ auto simple_atom_matcher = atom_matcher.mutable_simple_atom_matcher();
+ simple_atom_matcher->set_atom_id(android::util::SCREEN_BRIGHTNESS_CHANGED);
+ return atom_matcher;
+}
+
+AtomMatcher CreateUidProcessStateChangedAtomMatcher() {
+ AtomMatcher atom_matcher;
+ atom_matcher.set_id(StringToId("UidProcessStateChanged"));
+ auto simple_atom_matcher = atom_matcher.mutable_simple_atom_matcher();
+ simple_atom_matcher->set_atom_id(android::util::UID_PROCESS_STATE_CHANGED);
+ return atom_matcher;
+}
+
AtomMatcher CreateWakelockStateChangedAtomMatcher(const string& name,
WakelockStateChanged::State state) {
AtomMatcher atom_matcher;
@@ -47,6 +62,30 @@
return CreateWakelockStateChangedAtomMatcher("ReleaseWakelock", WakelockStateChanged::RELEASE);
}
+AtomMatcher CreateBatterySaverModeStateChangedAtomMatcher(
+ const string& name, BatterySaverModeStateChanged::State state) {
+ AtomMatcher atom_matcher;
+ atom_matcher.set_id(StringToId(name));
+ auto simple_atom_matcher = atom_matcher.mutable_simple_atom_matcher();
+ simple_atom_matcher->set_atom_id(android::util::BATTERY_SAVER_MODE_STATE_CHANGED);
+ auto field_value_matcher = simple_atom_matcher->add_field_value_matcher();
+ field_value_matcher->set_field(1); // State field.
+ field_value_matcher->set_eq_int(state);
+ return atom_matcher;
+}
+
+AtomMatcher CreateBatterySaverModeStartAtomMatcher() {
+ return CreateBatterySaverModeStateChangedAtomMatcher(
+ "BatterySaverModeStart", BatterySaverModeStateChanged::ON);
+}
+
+
+AtomMatcher CreateBatterySaverModeStopAtomMatcher() {
+ return CreateBatterySaverModeStateChangedAtomMatcher(
+ "BatterySaverModeStop", BatterySaverModeStateChanged::OFF);
+}
+
+
AtomMatcher CreateScreenStateChangedAtomMatcher(
const string& name, android::view::DisplayStateEnum state) {
AtomMatcher atom_matcher;
@@ -59,6 +98,7 @@
return atom_matcher;
}
+
AtomMatcher CreateScreenTurnedOnAtomMatcher() {
return CreateScreenStateChangedAtomMatcher("ScreenTurnedOn",
android::view::DisplayStateEnum::DISPLAY_STATE_ON);
@@ -128,6 +168,13 @@
"ProcessCrashed", ProcessLifeCycleStateChanged::PROCESS_CRASHED);
}
+Predicate CreateBatterySaverModePredicate() {
+ Predicate predicate;
+ predicate.set_id(StringToId("BatterySaverIsOn"));
+ predicate.mutable_simple_predicate()->set_start(StringToId("BatterySaverModeStart"));
+ predicate.mutable_simple_predicate()->set_stop(StringToId("BatterySaverModeStop"));
+ return predicate;
+}
Predicate CreateScreenIsOnPredicate() {
Predicate predicate;
@@ -218,6 +265,31 @@
return event;
}
+std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs) {
+ auto event = std::make_unique<LogEvent>(
+ android::util::BATTERY_SAVER_MODE_STATE_CHANGED, timestampNs);
+ EXPECT_TRUE(event->write(BatterySaverModeStateChanged::ON));
+ event->init();
+ return event;
+}
+
+std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs) {
+ auto event = std::make_unique<LogEvent>(
+ android::util::BATTERY_SAVER_MODE_STATE_CHANGED, timestampNs);
+ EXPECT_TRUE(event->write(BatterySaverModeStateChanged::OFF));
+ event->init();
+ return event;
+}
+
+std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(
+ int level, uint64_t timestampNs) {
+ auto event = std::make_unique<LogEvent>(android::util::SCREEN_BRIGHTNESS_CHANGED, timestampNs);
+ EXPECT_TRUE(event->write(level));
+ event->init();
+ return event;
+
+}
+
std::unique_ptr<LogEvent> CreateWakelockStateChangedEvent(
const std::vector<AttributionNode>& attributions, const string& wakelockName,
const WakelockStateChanged::State state, uint64_t timestampNs) {
@@ -267,9 +339,10 @@
}
std::unique_ptr<LogEvent> CreateSyncStateChangedEvent(
- const int uid, const string& name, const SyncStateChanged::State state, uint64_t timestampNs) {
+ const std::vector<AttributionNode>& attributions,
+ const string& name, const SyncStateChanged::State state, uint64_t timestampNs) {
auto event = std::make_unique<LogEvent>(android::util::SYNC_STATE_CHANGED, timestampNs);
- event->write(uid);
+ event->write(attributions);
event->write(name);
event->write(state);
event->init();
@@ -277,13 +350,13 @@
}
std::unique_ptr<LogEvent> CreateSyncStartEvent(
- const int uid, const string& name, uint64_t timestampNs){
- return CreateSyncStateChangedEvent(uid, name, SyncStateChanged::ON, timestampNs);
+ const std::vector<AttributionNode>& attributions, const string& name, uint64_t timestampNs){
+ return CreateSyncStateChangedEvent(attributions, name, SyncStateChanged::ON, timestampNs);
}
std::unique_ptr<LogEvent> CreateSyncEndEvent(
- const int uid, const string& name, uint64_t timestampNs) {
- return CreateSyncStateChangedEvent(uid, name, SyncStateChanged::OFF, timestampNs);
+ const std::vector<AttributionNode>& attributions, const string& name, uint64_t timestampNs) {
+ return CreateSyncStateChangedEvent(attributions, name, SyncStateChanged::OFF, timestampNs);
}
std::unique_ptr<LogEvent> CreateProcessLifeCycleStateChangedEvent(
diff --git a/cmds/statsd/tests/statsd_test_util.h b/cmds/statsd/tests/statsd_test_util.h
index ff8fef0c..6638893 100644
--- a/cmds/statsd/tests/statsd_test_util.h
+++ b/cmds/statsd/tests/statsd_test_util.h
@@ -14,6 +14,7 @@
#pragma once
+#include <gtest/gtest.h>
#include "frameworks/base/cmds/statsd/src/statsd_config.pb.h"
#include "statslog.h"
#include "src/logd/LogEvent.h"
@@ -26,6 +27,18 @@
// Create AtomMatcher proto to simply match a specific atom type.
AtomMatcher CreateSimpleAtomMatcher(const string& name, int atomId);
+// Create AtomMatcher proto for screen brightness state changed.
+AtomMatcher CreateScreenBrightnessChangedAtomMatcher();
+
+// Create AtomMatcher proto for starting battery save mode.
+AtomMatcher CreateBatterySaverModeStartAtomMatcher();
+
+// Create AtomMatcher proto for stopping battery save mode.
+AtomMatcher CreateBatterySaverModeStopAtomMatcher();
+
+// Create AtomMatcher proto for process state changed.
+AtomMatcher CreateUidProcessStateChangedAtomMatcher();
+
// Create AtomMatcher proto for acquiring wakelock.
AtomMatcher CreateAcquireWakelockAtomMatcher();
@@ -59,6 +72,9 @@
// Create Predicate proto for screen is off.
Predicate CreateScreenIsOffPredicate();
+// Create Predicate proto for battery saver mode.
+Predicate CreateBatterySaverModePredicate();
+
// Create Predicate proto for holding wakelock.
Predicate CreateHoldingWakelockPredicate();
@@ -86,6 +102,15 @@
std::unique_ptr<LogEvent> CreateScreenStateChangedEvent(
const android::view::DisplayStateEnum state, uint64_t timestampNs);
+// Create log event for screen brightness state changed.
+std::unique_ptr<LogEvent> CreateScreenBrightnessChangedEvent(
+ int level, uint64_t timestampNs);
+
+// Create log event when battery saver starts.
+std::unique_ptr<LogEvent> CreateBatterySaverOnEvent(uint64_t timestampNs);
+// Create log event when battery saver stops.
+std::unique_ptr<LogEvent> CreateBatterySaverOffEvent(uint64_t timestampNs);
+
// Create log event for app moving to background.
std::unique_ptr<LogEvent> CreateMoveToBackgroundEvent(const int uid, uint64_t timestampNs);
@@ -94,11 +119,11 @@
// Create log event when the app sync starts.
std::unique_ptr<LogEvent> CreateSyncStartEvent(
- const int uid, const string& name, uint64_t timestampNs);
+ const std::vector<AttributionNode>& attributions, const string& name, uint64_t timestampNs);
// Create log event when the app sync ends.
std::unique_ptr<LogEvent> CreateSyncEndEvent(
- const int uid, const string& name, uint64_t timestampNs);
+ const std::vector<AttributionNode>& attributions, const string& name, uint64_t timestampNs);
// Create log event when the app sync ends.
std::unique_ptr<LogEvent> CreateAppCrashEvent(
@@ -136,9 +161,12 @@
template <typename T>
void sortMetricDataByDimensionsValue(const T& metricData, T* sortedMetricData) {
- std::map<HashableDimensionKey, int> dimensionIndexMap;
+ std::map<MetricDimensionKey, int> dimensionIndexMap;
for (int i = 0; i < metricData.data_size(); ++i) {
- dimensionIndexMap.insert(std::make_pair(metricData.data(i).dimensions_in_what(), i));
+ dimensionIndexMap.insert(std::make_pair(
+ MetricDimensionKey(HashableDimensionKey(metricData.data(i).dimensions_in_what()),
+ HashableDimensionKey(metricData.data(i).dimensions_in_condition())),
+ i));
}
for (const auto& itr : dimensionIndexMap) {
*sortedMetricData->add_data() = metricData.data(itr.second);
diff --git a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java b/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java
index d39aa1d..57575ae 100644
--- a/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java
+++ b/cmds/statsd/tools/dogfood/src/com/android/statsd/dogfood/MainActivity.java
@@ -116,28 +116,32 @@
findViewById(R.id.plug).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
- StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, 1);
+ StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED,
+ StatsLog.PLUGGED_STATE_CHANGED__STATE__BATTERY_PLUGGED_AC);
}
});
findViewById(R.id.unplug).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
- StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED, 0);
+ StatsLog.write(StatsLog.PLUGGED_STATE_CHANGED,
+ StatsLog.PLUGGED_STATE_CHANGED__STATE__BATTERY_PLUGGED_NONE);
}
});
findViewById(R.id.screen_on).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED, 2);
+ StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
+ StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_ON);
}
});
findViewById(R.id.screen_off).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
- StatsLog.write(StatsLog.SCREEN_STATE_CHANGED, 1);
+ StatsLog.write(StatsLog.SCREEN_STATE_CHANGED,
+ StatsLog.SCREEN_STATE_CHANGED__STATE__DISPLAY_STATE_OFF);
}
});
@@ -255,7 +259,9 @@
}
int[] uids = new int[] {mUids[id]};
String[] tags = new String[] {"acquire"};
- StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, uids, tags, 0, name, 1);
+ StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, uids, tags,
+ StatsLog.WAKELOCK_STATE_CHANGED__LEVEL__PARTIAL_WAKE_LOCK, name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
StringBuilder sb = new StringBuilder();
sb.append("StagsLog.write(10, ").append(mUids[id]).append(", ").append(0)
.append(", ").append(name).append(", 1);");
@@ -269,7 +275,9 @@
}
int[] uids = new int[] {mUids[id]};
String[] tags = new String[] {"release"};
- StatsLog.write(10, uids, tags, 0, name, 0);
+ StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, uids, tags,
+ StatsLog.WAKELOCK_STATE_CHANGED__LEVEL__PARTIAL_WAKE_LOCK, name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
StringBuilder sb = new StringBuilder();
sb.append("StagsLog.write(10, ").append(mUids[id]).append(", ").append(0)
.append(", ").append(name).append(", 0);");
diff --git a/cmds/svc/src/com/android/commands/svc/UsbCommand.java b/cmds/svc/src/com/android/commands/svc/UsbCommand.java
index 34f6d7d..3893be4 100644
--- a/cmds/svc/src/com/android/commands/svc/UsbCommand.java
+++ b/cmds/svc/src/com/android/commands/svc/UsbCommand.java
@@ -21,7 +21,6 @@
import android.hardware.usb.UsbManager;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.os.SystemProperties;
public class UsbCommand extends Svc.Command {
public UsbCommand() {
@@ -37,41 +36,41 @@
public String longHelp() {
return shortHelp() + "\n"
+ "\n"
- + "usage: svc usb setFunction [function] [usbDataUnlocked=false]\n"
- + " Set the current usb function and optionally the data lock state.\n\n"
+ + "usage: svc usb setFunctions [function]\n"
+ + " Set the current usb function. If function is blank, sets to charging.\n"
+ " svc usb setScreenUnlockedFunctions [function]\n"
- + " Sets the functions which, if the device was charging,"
- + " become current on screen unlock.\n"
- + " svc usb getFunction\n"
- + " Gets the list of currently enabled functions\n";
+ + " Sets the functions which, if the device was charging, become current on"
+ + "screen unlock. If function is blank, turn off this feature.\n"
+ + " svc usb getFunctions\n"
+ + " Gets the list of currently enabled functions\n\n"
+ + "possible values of [function] are any of 'mtp', 'ptp', 'rndis', 'midi'\n";
}
@Override
public void run(String[] args) {
- boolean validCommand = false;
if (args.length >= 2) {
- if ("setFunction".equals(args[1])) {
- IUsbManager usbMgr = IUsbManager.Stub.asInterface(ServiceManager.getService(
- Context.USB_SERVICE));
- boolean unlockData = false;
- if (args.length >= 4) {
- unlockData = Boolean.valueOf(args[3]);
- }
+ IUsbManager usbMgr = IUsbManager.Stub.asInterface(ServiceManager.getService(
+ Context.USB_SERVICE));
+ if ("setFunctions".equals(args[1])) {
try {
- usbMgr.setCurrentFunction((args.length >=3 ? args[2] : null), unlockData);
+ usbMgr.setCurrentFunctions(UsbManager.usbFunctionsFromString(
+ args.length >= 3 ? args[2] : ""));
} catch (RemoteException e) {
System.err.println("Error communicating with UsbManager: " + e);
}
return;
- } else if ("getFunction".equals(args[1])) {
- System.err.println(SystemProperties.get("sys.usb.config"));
+ } else if ("getFunctions".equals(args[1])) {
+ try {
+ System.err.println(
+ UsbManager.usbFunctionsToString(usbMgr.getCurrentFunctions()));
+ } catch (RemoteException e) {
+ System.err.println("Error communicating with UsbManager: " + e);
+ }
return;
} else if ("setScreenUnlockedFunctions".equals(args[1])) {
- IUsbManager usbMgr = IUsbManager.Stub.asInterface(ServiceManager.getService(
- Context.USB_SERVICE));
try {
- usbMgr.setScreenUnlockedFunctions((args.length >= 3 ? args[2] :
- UsbManager.USB_FUNCTION_NONE));
+ usbMgr.setScreenUnlockedFunctions(UsbManager.usbFunctionsFromString(
+ args.length >= 3 ? args[2] : ""));
} catch (RemoteException e) {
System.err.println("Error communicating with UsbManager: " + e);
}
diff --git a/config/hiddenapi-light-greylist.txt b/config/hiddenapi-light-greylist.txt
new file mode 100644
index 0000000..05e51a4
--- /dev/null
+++ b/config/hiddenapi-light-greylist.txt
@@ -0,0 +1,1105 @@
+Landroid/accounts/AccountManager;->mContext:Landroid/content/Context;
+Landroid/animation/ValueAnimator;->animateValue(F)V
+Landroid/animation/ValueAnimator;->getDurationScale()F
+Landroid/animation/ValueAnimator;->sDurationScale:F
+Landroid/app/Activity;->convertFromTranslucent()V
+Landroid/app/Activity;->convertToTranslucent(Landroid/app/Activity$TranslucentConversionListener;Landroid/app/ActivityOptions;)Z
+Landroid/app/Activity;->getActivityOptions()Landroid/app/ActivityOptions;
+Landroid/app/Activity;->getActivityToken()Landroid/os/IBinder;
+Landroid/app/Activity;->mActivityInfo:Landroid/content/pm/ActivityInfo;
+Landroid/app/ActivityManager;->clearApplicationUserData(Ljava/lang/String;Landroid/content/pm/IPackageDataObserver;)Z
+Landroid/app/ActivityManager;->forceStopPackage(Ljava/lang/String;)V
+Landroid/app/ActivityManager;->getCurrentUser()I
+Landroid/app/ActivityManager;->isLowRamDeviceStatic()Z
+Landroid/app/ActivityManager;->isUserRunning(I)Z
+Landroid/app/ActivityManager;->mContext:Landroid/content/Context;
+Landroid/app/ActivityManagerNative;->getDefault()Landroid/app/IActivityManager;
+Landroid/app/ActivityManager;->PROCESS_STATE_TOP:I
+Landroid/app/ActivityManager$RunningAppProcessInfo;->flags:I
+Landroid/app/ActivityManager$RunningAppProcessInfo;->processState:I
+Landroid/app/Activity;->mApplication:Landroid/app/Application;
+Landroid/app/Activity;->mHandler:Landroid/os/Handler;
+Landroid/app/Activity;->mResultCode:I
+Landroid/app/Activity;->mResultData:Landroid/content/Intent;
+Landroid/app/Activity;->mToken:Landroid/os/IBinder;
+Landroid/app/Activity;->mWindow:Landroid/view/Window;
+Landroid/app/Activity;->mWindowManager:Landroid/view/WindowManager;
+Landroid/app/ActivityThread$ActivityClientRecord;->activityInfo:Landroid/content/pm/ActivityInfo;
+Landroid/app/ActivityThread$ActivityClientRecord;->token:Landroid/os/IBinder;
+Landroid/app/ActivityThread$AppBindData;->info:Landroid/app/LoadedApk;
+Landroid/app/ActivityThread$AppBindData;->instrumentationArgs:Landroid/os/Bundle;
+Landroid/app/ActivityThread;->currentActivityThread()Landroid/app/ActivityThread;
+Landroid/app/ActivityThread;->currentApplication()Landroid/app/Application;
+Landroid/app/ActivityThread;->currentPackageName()Ljava/lang/String;
+Landroid/app/ActivityThread;->getApplication()Landroid/app/Application;
+Landroid/app/ActivityThread;->getApplicationThread()Landroid/app/ActivityThread$ApplicationThread;
+Landroid/app/ActivityThread;->getHandler()Landroid/os/Handler;
+Landroid/app/ActivityThread;->getPackageManager()Landroid/content/pm/IPackageManager;
+Landroid/app/ActivityThread;->getProcessName()Ljava/lang/String;
+Landroid/app/ActivityThread$H;->BIND_SERVICE:I
+Landroid/app/ActivityThread$H;->CREATE_SERVICE:I
+Landroid/app/ActivityThread$H;->EXIT_APPLICATION:I
+Landroid/app/ActivityThread$H;->RECEIVER:I
+Landroid/app/ActivityThread$H;->RELAUNCH_ACTIVITY:I
+Landroid/app/ActivityThread$H;->REMOVE_PROVIDER:I
+Landroid/app/ActivityThread$H;->SERVICE_ARGS:I
+Landroid/app/ActivityThread$H;->STOP_SERVICE:I
+Landroid/app/ActivityThread$H;->UNBIND_SERVICE:I
+Landroid/app/ActivityThread;->installContentProviders(Landroid/content/Context;Ljava/util/List;)V
+Landroid/app/ActivityThread;->mActivities:Landroid/util/ArrayMap;
+Landroid/app/ActivityThread;->mAllApplications:Ljava/util/ArrayList;
+Landroid/app/ActivityThread;->mBoundApplication:Landroid/app/ActivityThread$AppBindData;
+Landroid/app/ActivityThread;->mInitialApplication:Landroid/app/Application;
+Landroid/app/ActivityThread;->mInstrumentation:Landroid/app/Instrumentation;
+Landroid/app/ActivityThread;->mNumVisibleActivities:I
+Landroid/app/ActivityThread;->mPackages:Landroid/util/ArrayMap;
+Landroid/app/ActivityThread;->performStopActivity(Landroid/os/IBinder;ZLjava/lang/String;)V
+Landroid/app/ActivityThread;->sPackageManager:Landroid/content/pm/IPackageManager;
+Landroid/app/admin/DevicePolicyManager;->getTrustAgentConfiguration(Landroid/content/ComponentName;Landroid/content/ComponentName;I)Ljava/util/List;
+Landroid/app/admin/DevicePolicyManager;->notifyPendingSystemUpdate(J)V
+Landroid/app/admin/DevicePolicyManager;->notifyPendingSystemUpdate(JZ)V
+Landroid/app/admin/DevicePolicyManager;->packageHasActiveAdmins(Ljava/lang/String;I)Z
+Landroid/app/admin/DevicePolicyManager;->packageHasActiveAdmins(Ljava/lang/String;)Z
+Landroid/app/admin/DevicePolicyManager;->setActiveAdmin(Landroid/content/ComponentName;ZI)V
+Landroid/app/admin/DevicePolicyManager;->setActiveAdmin(Landroid/content/ComponentName;Z)V
+Landroid/app/AlertDialog$Builder;->P:Lcom/android/internal/app/AlertController$AlertParams;
+Landroid/app/AlertDialog;->mAlert:Lcom/android/internal/app/AlertController;
+Landroid/app/AppGlobals;->getInitialApplication()Landroid/app/Application;
+Landroid/app/AppGlobals;->getPackageManager()Landroid/content/pm/IPackageManager;
+Landroid/app/Application;->attach(Landroid/content/Context;)V
+Landroid/app/ApplicationLoaders;->getDefault()Landroid/app/ApplicationLoaders;
+Landroid/app/ApplicationLoaders;->mLoaders:Landroid/util/ArrayMap;
+Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;
+Landroid/app/Application;->mLoadedApk:Landroid/app/LoadedApk;
+Landroid/app/AppOpsManager;->checkOp(IILjava/lang/String;)I
+Landroid/app/AppOpsManager;->checkOpNoThrow(IILjava/lang/String;)I
+Landroid/app/AppOpsManager;->noteOp(I)I
+Landroid/app/AppOpsManager;->noteOp(IILjava/lang/String;)I
+Landroid/app/AppOpsManager;->OP_POST_NOTIFICATION:I
+Landroid/app/AppOpsManager;->OP_WIFI_SCAN:I
+Landroid/app/AppOpsManager;->OP_WRITE_SMS:I
+Landroid/app/AppOpsManager;->setMode(IILjava/lang/String;I)V
+Landroid/app/AppOpsManager;->strOpToOp(Ljava/lang/String;)I
+Landroid/app/backup/BackupDataInputStream;->dataSize:I
+Landroid/app/backup/BackupDataInputStream;->key:Ljava/lang/String;
+Landroid/app/backup/FullBackup;->backupToTar(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/backup/FullBackupDataOutput;)I
+Landroid/app/ContextImpl;->createActivityContext(Landroid/app/ActivityThread;Landroid/app/LoadedApk;Landroid/content/pm/ActivityInfo;Landroid/os/IBinder;ILandroid/content/res/Configuration;)Landroid/app/ContextImpl;
+Landroid/app/ContextImpl;->getActivityToken()Landroid/os/IBinder;
+Landroid/app/ContextImpl;->mMainThread:Landroid/app/ActivityThread;
+Landroid/app/ContextImpl;->mPackageInfo:Landroid/app/LoadedApk;
+Landroid/app/ContextImpl;->setOuterContext(Landroid/content/Context;)V
+Landroid/app/DatePickerDialog;->mDatePicker:Landroid/widget/DatePicker;
+Landroid/app/Dialog;->CANCEL:I
+Landroid/app/Dialog;->mCancelMessage:Landroid/os/Message;
+Landroid/app/Dialog;->mDismissMessage:Landroid/os/Message;
+Landroid/app/Dialog;->mListenersHandler:Landroid/os/Handler;
+Landroid/app/Dialog;->mOwnerActivity:Landroid/app/Activity;
+Landroid/app/Dialog;->mShowMessage:Landroid/os/Message;
+Landroid/app/DownloadManager$Request;->mUri:Landroid/net/Uri;
+Landroid/app/Fragment;->mChildFragmentManager:Landroid/app/FragmentManagerImpl;
+Landroid/app/IActivityManager;->forceStopPackage(Ljava/lang/String;I)V
+Landroid/app/IActivityManager;->getLaunchedFromPackage(Landroid/os/IBinder;)Ljava/lang/String;
+Landroid/app/IActivityManager;->resumeAppSwitches()V
+Landroid/app/IApplicationThread;->scheduleTrimMemory(I)V
+Landroid/app/IntentService;->mServiceHandler:Landroid/app/IntentService$ServiceHandler;
+Landroid/app/IWallpaperManager;->getWallpaper(Ljava/lang/String;Landroid/app/IWallpaperManagerCallback;ILandroid/os/Bundle;I)Landroid/os/ParcelFileDescriptor;
+Landroid/app/LoadedApk;->mApplication:Landroid/app/Application;
+Landroid/app/LoadedApk;->mReceivers:Landroid/util/ArrayMap;
+Landroid/app/LoadedApk;->mResDir:Ljava/lang/String;
+Landroid/app/LoadedApk;->mResources:Landroid/content/res/Resources;
+Landroid/app/LocalActivityManager;->mActivities:Ljava/util/Map;
+Landroid/app/LocalActivityManager;->mActivityArray:Ljava/util/ArrayList;
+Landroid/app/Notification$Builder;->mActions:Ljava/util/ArrayList;
+Landroid/app/Notification;->EXTRA_SUBSTITUTE_APP_NAME:Ljava/lang/String;
+Landroid/app/Notification;->isGroupSummary()Z
+Landroid/app/NotificationManager;->getService()Landroid/app/INotificationManager;
+Landroid/app/NotificationManager;->notifyAsUser(Ljava/lang/String;ILandroid/app/Notification;Landroid/os/UserHandle;)V
+Landroid/app/Notification;->setLatestEventInfo(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/app/PendingIntent;)V
+Landroid/app/PendingIntent;->getActivityAsUser(Landroid/content/Context;ILandroid/content/Intent;ILandroid/os/Bundle;Landroid/os/UserHandle;)Landroid/app/PendingIntent;
+Landroid/app/PendingIntent;->getIntent()Landroid/content/Intent;
+Landroid/app/PendingIntent;->isActivity()Z
+Landroid/app/Presentation;->createPresentationContext(Landroid/content/Context;Landroid/view/Display;I)Landroid/content/Context;
+Landroid/app/ProgressDialog;->mProgressNumber:Landroid/widget/TextView;
+Landroid/app/Service;->setForeground(Z)V
+Landroid/app/StatusBarManager;->collapsePanels()V
+Landroid/app/StatusBarManager;->disable(I)V
+Landroid/app/StatusBarManager;->expandNotificationsPanel()V
+Landroid/app/StatusBarManager;->expandSettingsPanel(Ljava/lang/String;)V
+Landroid/app/StatusBarManager;->expandSettingsPanel()V
+Landroid/app/TimePickerDialog;->mTimePicker:Landroid/widget/TimePicker;
+Landroid/app/WallpaperManager;->getBitmap()Landroid/graphics/Bitmap;
+Landroid/app/WallpaperManager;->getBitmap(Z)Landroid/graphics/Bitmap;
+Landroid/app/WallpaperManager;->getIWallpaperManager()Landroid/app/IWallpaperManager;
+Landroid/app/WallpaperManager;->openDefaultWallpaper(Landroid/content/Context;I)Ljava/io/InputStream;
+Landroid/app/WallpaperManager;->setBitmap(Landroid/graphics/Bitmap;Landroid/graphics/Rect;ZII)I
+Landroid/app/WallpaperManager;->sGlobals:Landroid/app/WallpaperManager$Globals;
+Landroid/appwidget/AppWidgetManager;->bindAppWidgetIdIfAllowed(IILandroid/content/ComponentName;Landroid/os/Bundle;)Z
+Landroid/appwidget/AppWidgetManager;->bindAppWidgetId(ILandroid/content/ComponentName;Landroid/os/Bundle;)V
+Landroid/appwidget/AppWidgetManager;->bindAppWidgetId(ILandroid/content/ComponentName;)V
+Landroid/bluetooth/BluetoothA2dp;->connect(Landroid/bluetooth/BluetoothDevice;)Z
+Landroid/bluetooth/BluetoothAdapter;->disable(Z)Z
+Landroid/bluetooth/BluetoothAdapter;->enableNoAutoConnect()Z
+Landroid/bluetooth/BluetoothAdapter;->getDiscoverableTimeout()I
+Landroid/bluetooth/BluetoothAdapter;->setScanMode(II)Z
+Landroid/bluetooth/BluetoothAdapter;->setScanMode(I)Z
+Landroid/bluetooth/BluetoothDevice;->cancelBondProcess()Z
+Landroid/bluetooth/BluetoothDevice;->createBond(I)Z
+Landroid/bluetooth/BluetoothDevice;->getAliasName()Ljava/lang/String;
+Landroid/bluetooth/BluetoothDevice;->isConnected()Z
+Landroid/bluetooth/BluetoothDevice;->isEncrypted()Z
+Landroid/bluetooth/BluetoothDevice;->removeBond()Z
+Landroid/bluetooth/BluetoothDevice;->setPhonebookAccessPermission(I)Z
+Landroid/bluetooth/BluetoothGattCharacteristic;->mInstance:I
+Landroid/bluetooth/BluetoothGattCharacteristic;->mService:Landroid/bluetooth/BluetoothGattService;
+Landroid/bluetooth/BluetoothGattDescriptor;->mCharacteristic:Landroid/bluetooth/BluetoothGattCharacteristic;
+Landroid/bluetooth/BluetoothGattDescriptor;->mInstance:I
+Landroid/bluetooth/BluetoothGatt;->refresh()Z
+Landroid/bluetooth/BluetoothHeadset;->close()V
+Landroid/bluetooth/BluetoothHeadset;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z
+Landroid/bluetooth/BluetoothUuid;->RESERVED_UUIDS:[Landroid/os/ParcelUuid;
+Landroid/bluetooth/IBluetooth$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetooth;
+Landroid/content/AsyncTaskLoader;->mExecutor:Ljava/util/concurrent/Executor;
+Landroid/content/ContentProviderOperation;->mSelection:Ljava/lang/String;
+Landroid/content/ContentProviderOperation;->mType:I
+Landroid/content/ContentResolver;->getContentService()Landroid/content/IContentService;
+Landroid/content/ContentResolver;->getSyncStatus(Landroid/accounts/Account;Ljava/lang/String;)Landroid/content/SyncStatusInfo;
+Landroid/content/ContentResolver;->mContext:Landroid/content/Context;
+Landroid/content/ContentValues;->mValues:Ljava/util/HashMap;
+Landroid/content/Context;->createPackageContextAsUser(Ljava/lang/String;ILandroid/os/UserHandle;)Landroid/content/Context;
+Landroid/content/Context;->getSharedPrefsFile(Ljava/lang/String;)Ljava/io/File;
+Landroid/content/Context;->getThemeResId()I
+Landroid/content/Context;->sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;I)V
+Landroid/content/Context;->sendBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;Landroid/os/Bundle;)V
+Landroid/content/Context;->sendOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;ILandroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V
+Landroid/content/Context;->sendOrderedBroadcastAsUser(Landroid/content/Intent;Landroid/os/UserHandle;Ljava/lang/String;ILandroid/os/Bundle;Landroid/content/BroadcastReceiver;Landroid/os/Handler;ILjava/lang/String;Landroid/os/Bundle;)V
+Landroid/content/ContextWrapper;->mBase:Landroid/content/Context;
+Landroid/content/CursorLoader;->mCancellationSignal:Landroid/os/CancellationSignal;
+Landroid/content/CursorLoader;->mObserver:Landroid/content/Loader$ForceLoadContentObserver;
+Landroid/content/IContentService;->cancelSync(Landroid/accounts/Account;Ljava/lang/String;Landroid/content/ComponentName;)V
+Landroid/content/IContentService;->getMasterSyncAutomatically()Z
+Landroid/content/IContentService;->setMasterSyncAutomatically(Z)V
+Landroid/content/Intent;->ACTION_ALARM_CHANGED:Ljava/lang/String;
+Landroid/content/Intent;->putExtra(Ljava/lang/String;Landroid/os/IBinder;)Landroid/content/Intent;
+Landroid/content/pm/ApplicationInfo;->installLocation:I
+Landroid/content/pm/ApplicationInfo;->isForwardLocked()Z
+Landroid/content/pm/ApplicationInfo;->isPrivilegedApp()Z
+Landroid/content/pm/ApplicationInfo;->primaryCpuAbi:Ljava/lang/String;
+Landroid/content/pm/ApplicationInfo;->privateFlags:I
+Landroid/content/pm/IPackageManager;->getLastChosenActivity(Landroid/content/Intent;Ljava/lang/String;I)Landroid/content/pm/ResolveInfo;
+Landroid/content/pm/IPackageManager;->setLastChosenActivity(Landroid/content/Intent;Ljava/lang/String;ILandroid/content/IntentFilter;ILandroid/content/ComponentName;)V
+Landroid/content/pm/LauncherApps;->mPm:Landroid/content/pm/PackageManager;
+Landroid/content/pm/LauncherApps;->startShortcut(Ljava/lang/String;Ljava/lang/String;Landroid/graphics/Rect;Landroid/os/Bundle;I)V
+Landroid/content/pm/PackageManager;->freeStorageAndNotify(JLandroid/content/pm/IPackageDataObserver;)V
+Landroid/content/pm/PackageManager;->freeStorageAndNotify(Ljava/lang/String;JLandroid/content/pm/IPackageDataObserver;)V
+Landroid/content/pm/PackageManager;->freeStorage(JLandroid/content/IntentSender;)V
+Landroid/content/pm/PackageManager;->freeStorage(Ljava/lang/String;JLandroid/content/IntentSender;)V
+Landroid/content/pm/PackageManager;->getPackageCandidateVolumes(Landroid/content/pm/ApplicationInfo;)Ljava/util/List;
+Landroid/content/pm/PackageManager;->getPackageSizeInfo(Ljava/lang/String;Landroid/content/pm/IPackageStatsObserver;)V
+Landroid/content/pm/PackageManager;->getResourcesForApplicationAsUser(Ljava/lang/String;I)Landroid/content/res/Resources;
+Landroid/content/pm/PackageManager;->movePackage(Ljava/lang/String;Landroid/os/storage/VolumeInfo;)I
+Landroid/content/pm/PackageManager;->queryBroadcastReceivers(Landroid/content/Intent;II)Ljava/util/List;
+Landroid/content/pm/PackageParser;->collectCertificates(Landroid/content/pm/PackageParser$Package;Ljava/io/File;Z)V
+Landroid/content/pm/PackageParser;->collectCertificates(Landroid/content/pm/PackageParser$Package;Z)V
+Landroid/content/pm/PackageParser;->generatePackageInfo(Landroid/content/pm/PackageParser$Package;[IIJJLjava/util/Set;Landroid/content/pm/PackageUserState;I)Landroid/content/pm/PackageInfo;
+Landroid/content/pm/PackageParser;->generatePackageInfo(Landroid/content/pm/PackageParser$Package;[IIJJLjava/util/Set;Landroid/content/pm/PackageUserState;)Landroid/content/pm/PackageInfo;
+Landroid/content/pm/PackageParser;->parseMonolithicPackage(Ljava/io/File;I)Landroid/content/pm/PackageParser$Package;
+Landroid/content/pm/PackageParser;->parsePackage(Ljava/io/File;I)Landroid/content/pm/PackageParser$Package;
+Landroid/content/pm/PackageParser;->parsePackage(Ljava/io/File;IZ)Landroid/content/pm/PackageParser$Package;
+Landroid/content/pm/UserInfo;->id:I
+Landroid/content/pm/UserInfo;->isPrimary()Z
+Landroid/content/res/AssetManager;->addAssetPath(Ljava/lang/String;)I
+Landroid/content/res/AssetManager;->addAssetPaths([Ljava/lang/String;)[I
+Landroid/content/res/AssetManager;->applyStyle(JIIJ[IIJJ)V
+Landroid/content/res/AssetManager;->getArraySize(I)I
+Landroid/content/res/AssetManager;->getAssignedPackageIdentifiers()Landroid/util/SparseArray;
+Landroid/content/res/AssetManager;->getCookieName(I)Ljava/lang/String;
+Landroid/content/res/AssetManager;->getResourceBagText(II)Ljava/lang/CharSequence;
+Landroid/content/res/AssetManager;->loadResourceBagValue(IILandroid/util/TypedValue;Z)I
+Landroid/content/res/AssetManager;->loadResourceValue(ISLandroid/util/TypedValue;Z)I
+Landroid/content/res/AssetManager;->loadThemeAttributeValue(JILandroid/util/TypedValue;Z)I
+Landroid/content/res/AssetManager;->openNonAssetFdNative(ILjava/lang/String;[J)Landroid/os/ParcelFileDescriptor;
+Landroid/content/res/AssetManager;->openNonAsset(ILjava/lang/String;I)Ljava/io/InputStream;
+Landroid/content/res/AssetManager;->openNonAsset(ILjava/lang/String;)Ljava/io/InputStream;
+Landroid/content/res/AssetManager;->openNonAsset(Ljava/lang/String;I)Ljava/io/InputStream;
+Landroid/content/res/AssetManager;->openNonAsset(Ljava/lang/String;)Ljava/io/InputStream;
+Landroid/content/res/AssetManager;->openNonAssetNative(ILjava/lang/String;I)J
+Landroid/content/res/AssetManager;->openXmlAssetNative(ILjava/lang/String;)J
+Landroid/content/res/AssetManager;->resolveAttrs(JII[I[I[I[I)Z
+Landroid/content/res/AssetManager;->retrieveArray(I[I)I
+Landroid/content/res/AssetManager;->retrieveAttributes(J[I[I[I)Z
+Landroid/content/res/AssetManager;->STYLE_NUM_ENTRIES:I
+Landroid/content/res/AssetManager;->STYLE_RESOURCE_ID:I
+Landroid/content/res/DrawableCache;->getInstance(JLandroid/content/res/Resources;Landroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
+Landroid/content/res/Resources;->getCompatibilityInfo()Landroid/content/res/CompatibilityInfo;
+Landroid/content/res/ResourcesImpl;->mAccessLock:Ljava/lang/Object;
+Landroid/content/res/ResourcesImpl;->mAssets:Landroid/content/res/AssetManager;
+Landroid/content/res/ResourcesImpl;->mColorDrawableCache:Landroid/content/res/DrawableCache;
+Landroid/content/res/ResourcesImpl;->mConfiguration:Landroid/content/res/Configuration;
+Landroid/content/res/ResourcesImpl;->mDrawableCache:Landroid/content/res/DrawableCache;
+Landroid/content/res/ResourcesImpl;->mPreloading:Z
+Landroid/content/res/ResourcesImpl;->sPreloadedColorDrawables:Landroid/util/LongSparseArray;
+Landroid/content/res/ResourcesImpl;->sPreloadedDrawables:[Landroid/util/LongSparseArray;
+Landroid/content/res/ResourcesImpl;->TRACE_FOR_MISS_PRELOAD:Z
+Landroid/content/res/ResourcesImpl;->TRACE_FOR_PRELOAD:Z
+Landroid/content/res/Resources;->loadXmlResourceParser(ILjava/lang/String;)Landroid/content/res/XmlResourceParser;
+Landroid/content/res/Resources;->loadXmlResourceParser(Ljava/lang/String;IILjava/lang/String;)Landroid/content/res/XmlResourceParser;
+Landroid/content/res/Resources;->mResourcesImpl:Landroid/content/res/ResourcesImpl;
+Landroid/content/res/Resources;->mTmpValue:Landroid/util/TypedValue;
+Landroid/content/res/Resources;->mTypedArrayPool:Landroid/util/Pools$SynchronizedPool;
+Landroid/content/res/Resources;->setCompatibilityInfo(Landroid/content/res/CompatibilityInfo;)V
+Landroid/content/res/TypedArray;->getValueAt(ILandroid/util/TypedValue;)Z
+Landroid/content/res/TypedArray;->mAssets:Landroid/content/res/AssetManager;
+Landroid/content/res/TypedArray;->mData:[I
+Landroid/content/res/TypedArray;->mIndices:[I
+Landroid/content/res/TypedArray;->mLength:I
+Landroid/content/res/TypedArray;->mMetrics:Landroid/util/DisplayMetrics;
+Landroid/content/res/TypedArray;->mRecycled:Z
+Landroid/content/res/TypedArray;->mResources:Landroid/content/res/Resources;
+Landroid/content/res/TypedArray;->mTheme:Landroid/content/res/Resources$Theme;
+Landroid/content/res/TypedArray;->mValue:Landroid/util/TypedValue;
+Landroid/content/res/TypedArray;->mXml:Landroid/content/res/XmlBlock$Parser;
+Landroid/content/res/XmlBlock;->close()V
+Landroid/content/res/XmlBlock;->newParser()Landroid/content/res/XmlResourceParser;
+Landroid/content/res/XmlBlock$Parser;->mParseState:J
+Landroid/content/SyncStatusInfo;->lastSuccessTime:J
+Landroid/database/AbstractCursor;->mNotifyUri:Landroid/net/Uri;
+Landroid/database/CursorWindow;->mWindowPtr:J
+Landroid/database/CursorWindow;->sCursorWindowSize:I
+Landroid/database/CursorWindow;->sWindowToPidMap:Landroid/util/LongSparseArray;
+Landroid/database/CursorWrapper;->mCursor:Landroid/database/Cursor;
+Landroid/graphics/Bitmap$Config;->nativeInt:I
+Landroid/graphics/Bitmap;->createAshmemBitmap()Landroid/graphics/Bitmap;
+Landroid/graphics/Bitmap;->createAshmemBitmap(Landroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;
+Landroid/graphics/Bitmap;->getDefaultDensity()I
+Landroid/graphics/drawable/AnimationDrawable;->mCurFrame:I
+Landroid/graphics/drawable/BitmapDrawable;->getTint()Landroid/content/res/ColorStateList;
+Landroid/graphics/drawable/BitmapDrawable;->getTintMode()Landroid/graphics/PorterDuff$Mode;
+Landroid/graphics/drawable/BitmapDrawable;->setBitmap(Landroid/graphics/Bitmap;)V
+Landroid/graphics/drawable/DrawableContainer$DrawableContainerState;->mConstantPadding:Landroid/graphics/Rect;
+Landroid/graphics/drawable/DrawableContainer;->mDrawableContainerState:Landroid/graphics/drawable/DrawableContainer$DrawableContainerState;
+Landroid/graphics/drawable/Drawable;->inflateWithAttributes(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/content/res/TypedArray;I)V
+Landroid/graphics/drawable/Drawable;->mCallback:Ljava/lang/ref/WeakReference;
+Landroid/graphics/drawable/NinePatchDrawable;->mNinePatchState:Landroid/graphics/drawable/NinePatchDrawable$NinePatchState;
+Landroid/graphics/drawable/NinePatchDrawable$NinePatchState;->mNinePatch:Landroid/graphics/NinePatch;
+Landroid/graphics/drawable/StateListDrawable;->extractStateSet(Landroid/util/AttributeSet;)[I
+Landroid/graphics/drawable/StateListDrawable;->getStateCount()I
+Landroid/graphics/drawable/StateListDrawable;->getStateDrawable(I)Landroid/graphics/drawable/Drawable;
+Landroid/graphics/drawable/StateListDrawable;->getStateSet(I)[I
+Landroid/graphics/drawable/StateListDrawable;->mStateListState:Landroid/graphics/drawable/StateListDrawable$StateListState;
+Landroid/graphics/drawable/StateListDrawable;->updateStateFromTypedArray(Landroid/content/res/TypedArray;)V
+Landroid/graphics/LinearGradient;->mColors:[I
+Landroid/graphics/NinePatch;->mBitmap:Landroid/graphics/Bitmap;
+Landroid/graphics/SurfaceTexture;->nativeDetachFromGLContext()I
+Landroid/graphics/Typeface;->mStyle:I
+Landroid/graphics/Typeface;->sDefaults:[Landroid/graphics/Typeface;
+Landroid/graphics/Typeface;->setDefault(Landroid/graphics/Typeface;)V
+Landroid/graphics/Typeface;->sSystemFontMap:Ljava/util/Map;
+Landroid/hardware/Camera;->addCallbackBuffer([BI)V
+Landroid/hardware/Camera;->openLegacy(II)Landroid/hardware/Camera;
+Landroid/hardware/display/WifiDisplayStatus;->mActiveDisplay:Landroid/hardware/display/WifiDisplay;
+Landroid/hardware/display/WifiDisplayStatus;->mDisplays:[Landroid/hardware/display/WifiDisplay;
+Landroid/hardware/input/IInputManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/hardware/input/IInputManager;
+Landroid/hardware/input/InputManager;->getInstance()Landroid/hardware/input/InputManager;
+Landroid/hardware/input/InputManager;->mIm:Landroid/hardware/input/IInputManager;
+Landroid/hardware/usb/UsbManager;->setCurrentFunction(Ljava/lang/String;Z)V
+Landroid/location/LocationRequest;->createFromDeprecatedProvider(Ljava/lang/String;JFZ)Landroid/location/LocationRequest;
+Landroid/location/LocationRequest;->setWorkSource(Landroid/os/WorkSource;)V
+Landroid/location/Location;->setIsFromMockProvider(Z)V
+Landroid/media/AudioAttributes$Builder;->setInternalCapturePreset(I)Landroid/media/AudioAttributes$Builder;
+Landroid/media/AudioManager;->abandonAudioFocus(Landroid/media/AudioManager$OnAudioFocusChangeListener;Landroid/media/AudioAttributes;)I
+Landroid/media/AudioManager;->mAudioFocusIdListenerMap:Ljava/util/concurrent/ConcurrentHashMap;
+Landroid/media/AudioManager;->requestAudioFocus(Landroid/media/AudioFocusRequest;Landroid/media/audiopolicy/AudioPolicy;)I
+Landroid/media/AudioManager;->requestAudioFocus(Landroid/media/AudioManager$OnAudioFocusChangeListener;Landroid/media/AudioAttributes;II)I
+Landroid/media/AudioManager;->requestAudioFocus(Landroid/media/AudioManager$OnAudioFocusChangeListener;Landroid/media/AudioAttributes;IILandroid/media/audiopolicy/AudioPolicy;)I
+Landroid/media/AudioManager;->setMasterMute(ZI)V
+Landroid/media/AudioManager;->STREAM_BLUETOOTH_SCO:I
+Landroid/media/AudioManager;->STREAM_SYSTEM_ENFORCED:I
+Landroid/media/AudioManager;->STREAM_TTS:I
+Landroid/media/AudioSystem;->setDeviceConnectionState(IILjava/lang/String;Ljava/lang/String;)I
+Landroid/media/AudioTrack;->getLatency()I
+Landroid/media/IAudioService$Stub;->asInterface(Landroid/os/IBinder;)Landroid/media/IAudioService;
+Landroid/media/MediaCodec;->releaseOutputBuffer(IZZJ)V
+Landroid/media/MediaFile;->getFileType(Ljava/lang/String;)Landroid/media/MediaFile$MediaFileType;
+Landroid/media/MediaFile;->getMimeTypeForFile(Ljava/lang/String;)Ljava/lang/String;
+Landroid/media/MediaFile;->isVideoFileType(I)Z
+Landroid/media/MediaFile$MediaFileType;->fileType:I
+Landroid/media/MediaFile;->sFileTypeMap:Ljava/util/HashMap;
+Landroid/media/MediaMetadataRetriever;->getEmbeddedPicture(I)[B
+Landroid/media/MediaPlayer;->getMetadata(ZZ)Landroid/media/Metadata;
+Landroid/media/MediaPlayer;->invoke(Landroid/os/Parcel;Landroid/os/Parcel;)V
+Landroid/media/MediaPlayer;->newRequest()Landroid/os/Parcel;
+Landroid/media/MediaPlayer;->setDataSource(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;Ljava/util/List;)V
+Landroid/media/MediaPlayer;->setDataSource(Ljava/lang/String;Ljava/util/Map;Ljava/util/List;)V
+Landroid/media/MediaPlayer;->setDataSource(Ljava/lang/String;Ljava/util/Map;)V
+Landroid/media/MediaPlayer;->setRetransmitEndpoint(Ljava/net/InetSocketAddress;)V
+Landroid/media/MediaRecorder$AudioSource;->RADIO_TUNER:I
+Landroid/media/MediaRouter$RouteInfo;->getStatusCode()I
+Landroid/media/MediaRouter$RouteInfo;->STATUS_CONNECTING:I
+Landroid/media/MediaRouter;->selectRouteInt(ILandroid/media/MediaRouter$RouteInfo;Z)V
+Landroid/media/MediaScanner;->mClient:Landroid/media/MediaScanner$MyMediaScannerClient;
+Landroid/media/MediaScanner;->scanSingleFile(Ljava/lang/String;Ljava/lang/String;)Landroid/net/Uri;
+Landroid/media/MiniThumbFile;->reset()V
+Landroid/media/RingtoneManager;->getRingtone(Landroid/content/Context;Landroid/net/Uri;I)Landroid/media/Ringtone;
+Landroid/media/Ringtone;->setLooping(Z)V
+Landroid/media/Ringtone;->setVolume(F)V
+Landroid/media/SubtitleController;->mHandler:Landroid/os/Handler;
+Landroid/media/ThumbnailUtils;->createImageThumbnail(Ljava/lang/String;I)Landroid/graphics/Bitmap;
+Landroid/net/ConnectivityManager;->ACTION_TETHER_STATE_CHANGED:Ljava/lang/String;
+Landroid/net/ConnectivityManager;->EXTRA_ACTIVE_TETHER:Ljava/lang/String;
+Landroid/net/ConnectivityManager;->getActiveLinkProperties()Landroid/net/LinkProperties;
+Landroid/net/ConnectivityManager;->getLinkProperties(I)Landroid/net/LinkProperties;
+Landroid/net/ConnectivityManager;->getMobileDataEnabled()Z
+Landroid/net/ConnectivityManager;->getTetherableUsbRegexs()[Ljava/lang/String;
+Landroid/net/ConnectivityManager;->getTetherableWifiRegexs()[Ljava/lang/String;
+Landroid/net/ConnectivityManager;->getTetheredIfaces()[Ljava/lang/String;
+Landroid/net/ConnectivityManager;->isNetworkSupported(I)Z
+Landroid/net/ConnectivityManager;->isNetworkTypeMobile(I)Z
+Landroid/net/ConnectivityManager;->isTetheringSupported()Z
+Landroid/net/ConnectivityManager;->mService:Landroid/net/IConnectivityManager;
+Landroid/net/ConnectivityManager;->requestRouteToHostAddress(ILjava/net/InetAddress;)Z
+Landroid/net/ConnectivityManager;->requestRouteToHost(II)Z
+Landroid/net/LinkProperties;->setHttpProxy(Landroid/net/ProxyInfo;)V
+Landroid/net/NetworkPolicyManager;->mService:Landroid/net/INetworkPolicyManager;
+Landroid/net/SSLCertificateSocketFactory;->getHttpSocketFactory(ILandroid/net/SSLSessionCache;)Lorg/apache/http/conn/ssl/SSLSocketFactory;
+Landroid/net/wifi/p2p/WifiP2pGroup;->getNetworkId()I
+Landroid/net/wifi/p2p/WifiP2pGroupList;->getGroupList()Ljava/util/Collection;
+Landroid/net/wifi/p2p/WifiP2pManager;->deletePersistentGroup(Landroid/net/wifi/p2p/WifiP2pManager$Channel;ILandroid/net/wifi/p2p/WifiP2pManager$ActionListener;)V
+Landroid/net/wifi/p2p/WifiP2pManager;->requestPersistentGroupInfo(Landroid/net/wifi/p2p/WifiP2pManager$Channel;Landroid/net/wifi/p2p/WifiP2pManager$PersistentGroupInfoListener;)V
+Landroid/net/wifi/p2p/WifiP2pManager;->setDeviceName(Landroid/net/wifi/p2p/WifiP2pManager$Channel;Ljava/lang/String;Landroid/net/wifi/p2p/WifiP2pManager$ActionListener;)V
+Landroid/net/wifi/WifiConfiguration;->apBand:I
+Landroid/net/wifi/WifiConfiguration;->apChannel:I
+Landroid/net/wifi/WifiConfiguration;->hasNoInternetAccess()Z
+Landroid/net/wifi/WifiConfiguration;->mIpConfiguration:Landroid/net/IpConfiguration;
+Landroid/net/wifi/WifiConfiguration;->validatedInternetAccess:Z
+Landroid/net/wifi/WifiManager;->connect(ILandroid/net/wifi/WifiManager$ActionListener;)V
+Landroid/net/wifi/WifiManager;->connect(Landroid/net/wifi/WifiConfiguration;Landroid/net/wifi/WifiManager$ActionListener;)V
+Landroid/net/wifi/WifiManager;->EXTRA_WIFI_AP_STATE:Ljava/lang/String;
+Landroid/net/wifi/WifiManager;->forget(ILandroid/net/wifi/WifiManager$ActionListener;)V
+Landroid/net/wifi/WifiManager;->getWifiApConfiguration()Landroid/net/wifi/WifiConfiguration;
+Landroid/net/wifi/WifiManager;->getWifiApState()I
+Landroid/net/wifi/WifiManager;->isDualBandSupported()Z
+Landroid/net/wifi/WifiManager;->isWifiApEnabled()Z
+Landroid/net/wifi/WifiManager;->mService:Landroid/net/wifi/IWifiManager;
+Landroid/net/wifi/WifiManager;->save(Landroid/net/wifi/WifiConfiguration;Landroid/net/wifi/WifiManager$ActionListener;)V
+Landroid/net/wifi/WifiManager;->setWifiApConfiguration(Landroid/net/wifi/WifiConfiguration;)Z
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_CHANGED_ACTION:Ljava/lang/String;
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_DISABLED:I
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_DISABLING:I
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_ENABLED:I
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_ENABLING:I
+Landroid/net/wifi/WifiManager;->WIFI_AP_STATE_FAILED:I
+Landroid/nfc/NfcAdapter;->getDefaultAdapter()Landroid/nfc/NfcAdapter;
+Landroid/nfc/NfcAdapter;->setNdefPushMessageCallback(Landroid/nfc/NfcAdapter$CreateNdefMessageCallback;Landroid/app/Activity;I)V
+Landroid/opengl/GLSurfaceView$EglHelper;->mEglContext:Ljavax/microedition/khronos/egl/EGLContext;
+Landroid/opengl/GLSurfaceView$GLThread;->mEglHelper:Landroid/opengl/GLSurfaceView$EglHelper;
+Landroid/opengl/GLSurfaceView;->mGLThread:Landroid/opengl/GLSurfaceView$GLThread;
+Landroid/os/AsyncTask;->mFuture:Ljava/util/concurrent/FutureTask;
+Landroid/os/AsyncTask;->mStatus:Landroid/os/AsyncTask$Status;
+Landroid/os/AsyncTask;->mTaskInvoked:Ljava/util/concurrent/atomic/AtomicBoolean;
+Landroid/os/AsyncTask;->mWorker:Landroid/os/AsyncTask$WorkerRunnable;
+Landroid/os/AsyncTask;->sDefaultExecutor:Ljava/util/concurrent/Executor;
+Landroid/os/AsyncTask;->setDefaultExecutor(Ljava/util/concurrent/Executor;)V
+Landroid/os/BatteryStats;->NUM_DATA_CONNECTION_TYPES:I
+Landroid/os/BatteryStats$Timer;->getTotalTimeLocked(JI)J
+Landroid/os/BatteryStats$Uid;->getFullWifiLockTime(JI)J
+Landroid/os/BatteryStats$Uid;->getProcessStats()Landroid/util/ArrayMap;
+Landroid/os/BatteryStats$Uid;->getSensorStats()Landroid/util/SparseArray;
+Landroid/os/BatteryStats$Uid;->getUid()I
+Landroid/os/BatteryStats$Uid;->getWifiMulticastTime(JI)J
+Landroid/os/BatteryStats$Uid;->getWifiScanTime(JI)J
+Landroid/os/BatteryStats$Uid$Proc;->getForegroundTime(I)J
+Landroid/os/BatteryStats$Uid$Proc;->getSystemTime(I)J
+Landroid/os/BatteryStats$Uid$Proc;->getUserTime(I)J
+Landroid/os/BatteryStats$Uid$Sensor;->getHandle()I
+Landroid/os/BatteryStats$Uid$Sensor;->getSensorTime()Landroid/os/BatteryStats$Timer;
+Landroid/os/Build;->getString(Ljava/lang/String;)Ljava/lang/String;
+Landroid/os/Bundle;->getIBinder(Ljava/lang/String;)Landroid/os/IBinder;
+Landroid/os/Bundle;->putIBinder(Ljava/lang/String;Landroid/os/IBinder;)V
+Landroid/os/Debug;->countInstancesOfClass(Ljava/lang/Class;)J
+Landroid/os/Debug;->dumpReferenceTables()V
+Landroid/os/Debug$MemoryInfo;->getOtherLabel(I)Ljava/lang/String;
+Landroid/os/Debug$MemoryInfo;->getOtherPrivateDirty(I)I
+Landroid/os/Debug$MemoryInfo;->getOtherPss(I)I
+Landroid/os/Debug$MemoryInfo;->getOtherSharedDirty(I)I
+Landroid/os/Debug$MemoryInfo;->NUM_DVK_STATS:I
+Landroid/os/Debug$MemoryInfo;->NUM_OTHER_STATS:I
+Landroid/os/Environment;->buildExternalStorageAppDataDirs(Ljava/lang/String;)[Ljava/io/File;
+Landroid/os/FileUtils;->checksumCrc32(Ljava/io/File;)J
+Landroid/os/FileUtils;->copyFile(Ljava/io/File;Ljava/io/File;)Z
+Landroid/os/FileUtils;->copyToFile(Ljava/io/InputStream;Ljava/io/File;)Z
+Landroid/os/FileUtils;->deleteOlderFiles(Ljava/io/File;IJ)Z
+Landroid/os/FileUtils;->readTextFile(Ljava/io/File;ILjava/lang/String;)Ljava/lang/String;
+Landroid/os/FileUtils;->setPermissions(Ljava/io/FileDescriptor;III)I
+Landroid/os/FileUtils;->setPermissions(Ljava/io/File;III)I
+Landroid/os/FileUtils;->setPermissions(Ljava/lang/String;III)I
+Landroid/os/FileUtils;->stringToFile(Ljava/io/File;Ljava/lang/String;)V
+Landroid/os/FileUtils;->stringToFile(Ljava/lang/String;Ljava/lang/String;)V
+Landroid/os/Handler;->getIMessenger()Landroid/os/IMessenger;
+Landroid/os/Handler;->hasCallbacks(Ljava/lang/Runnable;)Z
+Landroid/os/Handler;->mCallback:Landroid/os/Handler$Callback;
+Landroid/os/Handler;->mMessenger:Landroid/os/IMessenger;
+Landroid/os/IPowerManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/os/IPowerManager;
+Landroid/os/IPowerManager;->userActivity(JII)V
+Landroid/os/Looper;->mQueue:Landroid/os/MessageQueue;
+Landroid/os/MemoryFile;->getFileDescriptor()Ljava/io/FileDescriptor;
+Landroid/os/Message;->callback:Ljava/lang/Runnable;
+Landroid/os/Message;->flags:I
+Landroid/os/Message;->next:Landroid/os/Message;
+Landroid/os/MessageQueue;->mIdleHandlers:Ljava/util/ArrayList;
+Landroid/os/MessageQueue;->mMessages:Landroid/os/Message;
+Landroid/os/MessageQueue;->mQuitAllowed:Z
+Landroid/os/MessageQueue;->next()Landroid/os/Message;
+Landroid/os/Message;->target:Landroid/os/Handler;
+Landroid/os/PowerManager;->getMaximumScreenBrightnessSetting()I
+Landroid/os/PowerManager;->getMinimumScreenBrightnessSetting()I
+Landroid/os/PowerManager;->isLightDeviceIdleMode()Z
+Landroid/os/PowerManager;->userActivity(JII)V
+Landroid/os/PowerManager;->userActivity(JZ)V
+Landroid/os/PowerManager;->validateWakeLockParameters(ILjava/lang/String;)V
+Landroid/os/PowerManager;->wakeUp(JLjava/lang/String;)V
+Landroid/os/PowerManager;->wakeUp(J)V
+Landroid/os/Process;->getParentPid(I)I
+Landroid/os/Process;->getPids(Ljava/lang/String;[I)[I
+Landroid/os/Process;->getUidForPid(I)I
+Landroid/os/Process;->isIsolated(I)Z
+Landroid/os/Process;->isIsolated()Z
+Landroid/os/Process;->readProcFile(Ljava/lang/String;[I[Ljava/lang/String;[J[F)Z
+Landroid/os/Process;->readProcLines(Ljava/lang/String;[Ljava/lang/String;[J)V
+Landroid/os/RecoverySystem;->cancelScheduledUpdate(Landroid/content/Context;)V
+Landroid/os/RecoverySystem;->installPackage(Landroid/content/Context;Ljava/io/File;Z)V
+Landroid/os/RecoverySystem;->processPackage(Landroid/content/Context;Ljava/io/File;Landroid/os/RecoverySystem$ProgressListener;Landroid/os/Handler;)V
+Landroid/os/RecoverySystem;->processPackage(Landroid/content/Context;Ljava/io/File;Landroid/os/RecoverySystem$ProgressListener;)V
+Landroid/os/RecoverySystem;->rebootWipeAb(Landroid/content/Context;Ljava/io/File;Ljava/lang/String;)V
+Landroid/os/RecoverySystem;->scheduleUpdateOnBoot(Landroid/content/Context;Ljava/io/File;)V
+Landroid/os/SELinux;->isSELinuxEnabled()Z
+Landroid/os/SELinux;->isSELinuxEnforced()Z
+Landroid/os/ServiceManager;->checkService(Ljava/lang/String;)Landroid/os/IBinder;
+Landroid/os/ServiceManager;->getService(Ljava/lang/String;)Landroid/os/IBinder;
+Landroid/os/storage/DiskInfo;->getDescription()Ljava/lang/String;
+Landroid/os/storage/StorageManager;->findVolumeByUuid(Ljava/lang/String;)Landroid/os/storage/VolumeInfo;
+Landroid/os/storage/StorageManager;->getBestVolumeDescription(Landroid/os/storage/VolumeInfo;)Ljava/lang/String;
+Landroid/os/storage/StorageManager;->getDisks()Ljava/util/List;
+Landroid/os/storage/StorageManager;->getStorageBytesUntilLow(Ljava/io/File;)J
+Landroid/os/storage/StorageManager;->getVolumeList(II)[Landroid/os/storage/StorageVolume;
+Landroid/os/storage/StorageManager;->getVolumeList()[Landroid/os/storage/StorageVolume;
+Landroid/os/storage/StorageManager;->getVolumePaths()[Ljava/lang/String;
+Landroid/os/storage/StorageManager;->getVolumes()Ljava/util/List;
+Landroid/os/storage/StorageManager;->getVolumeState(Ljava/lang/String;)Ljava/lang/String;
+Landroid/os/storage/StorageVolume;->getPathFile()Ljava/io/File;
+Landroid/os/storage/StorageVolume;->getPath()Ljava/lang/String;
+Landroid/os/storage/StorageVolume;->getUserLabel()Ljava/lang/String;
+Landroid/os/storage/VolumeInfo;->getDisk()Landroid/os/storage/DiskInfo;
+Landroid/os/storage/VolumeInfo;->getFsUuid()Ljava/lang/String;
+Landroid/os/storage/VolumeInfo;->getPath()Ljava/io/File;
+Landroid/os/storage/VolumeInfo;->getState()I
+Landroid/os/storage/VolumeInfo;->getType()I
+Landroid/os/storage/VolumeInfo;->isPrimary()Z
+Landroid/os/storage/VolumeInfo;->isVisible()Z
+Landroid/os/StrictMode;->violationsBeingTimed:Ljava/lang/ThreadLocal;
+Landroid/os/SystemProperties;->addChangeCallback(Ljava/lang/Runnable;)V
+Landroid/os/SystemProperties;->getBoolean(Ljava/lang/String;Z)Z
+Landroid/os/SystemProperties;->getInt(Ljava/lang/String;I)I
+Landroid/os/SystemProperties;->get(Ljava/lang/String;)Ljava/lang/String;
+Landroid/os/SystemProperties;->get(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
+Landroid/os/SystemProperties;->getLong(Ljava/lang/String;J)J
+Landroid/os/SystemProperties;->PROP_NAME_MAX:I
+Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V
+Landroid/os/Trace;->asyncTraceBegin(JLjava/lang/String;I)V
+Landroid/os/Trace;->asyncTraceEnd(JLjava/lang/String;I)V
+Landroid/os/Trace;->isTagEnabled(J)Z
+Landroid/os/Trace;->setAppTracingAllowed(Z)V
+Landroid/os/Trace;->traceBegin(JLjava/lang/String;)V
+Landroid/os/Trace;->traceCounter(JLjava/lang/String;I)V
+Landroid/os/Trace;->traceEnd(J)V
+Landroid/os/Trace;->TRACE_TAG_APP:J
+Landroid/os/Trace;->TRACE_TAG_VIEW:J
+Landroid/os/UpdateEngine;->applyPayload(Ljava/lang/String;JJ[Ljava/lang/String;)V
+Landroid/os/UpdateEngine;->bind(Landroid/os/UpdateEngineCallback;Landroid/os/Handler;)Z
+Landroid/os/UpdateEngine;->bind(Landroid/os/UpdateEngineCallback;)Z
+Landroid/os/UpdateEngine;->cancel()V
+Landroid/os/UpdateEngine;->resetStatus()V
+Landroid/os/UpdateLock;->acquire()V
+Landroid/os/UpdateLock;->isHeld()Z
+Landroid/os/UpdateLock;->release()V
+Landroid/os/UserHandle;->ALL:Landroid/os/UserHandle;
+Landroid/os/UserHandle;->getIdentifier()I
+Landroid/os/UserHandle;->getUserId(I)I
+Landroid/os/UserHandle;->isOwner()Z
+Landroid/os/UserHandle;->myUserId()I
+Landroid/os/UserHandle;->of(I)Landroid/os/UserHandle;
+Landroid/os/UserManager;->get(Landroid/content/Context;)Landroid/os/UserManager;
+Landroid/os/UserManager;->getMaxSupportedUsers()I
+Landroid/os/UserManager;->getProfiles(I)Ljava/util/List;
+Landroid/os/UserManager;->getUserHandle()I
+Landroid/os/UserManager;->getUserHandle(I)I
+Landroid/os/UserManager;->getUserInfo(I)Landroid/content/pm/UserInfo;
+Landroid/os/UserManager;->getUserSerialNumber(I)I
+Landroid/os/UserManager;->hasBaseUserRestriction(Ljava/lang/String;Landroid/os/UserHandle;)Z
+Landroid/os/UserManager;->isUserUnlocked(I)Z
+Landroid/os/WorkSource;->add(ILjava/lang/String;)Z
+Landroid/os/WorkSource;->add(I)Z
+Landroid/os/WorkSource;->get(I)I
+Landroid/os/WorkSource;->getName(I)Ljava/lang/String;
+Landroid/os/WorkSource;->size()I
+Landroid/preference/DialogPreference;->mBuilder:Landroid/app/AlertDialog$Builder;
+Landroid/preference/DialogPreference;->mDialogIcon:Landroid/graphics/drawable/Drawable;
+Landroid/preference/DialogPreference;->mDialog:Landroid/app/Dialog;
+Landroid/preference/DialogPreference;->mDialogMessage:Ljava/lang/CharSequence;
+Landroid/preference/DialogPreference;->mDialogTitle:Ljava/lang/CharSequence;
+Landroid/preference/DialogPreference;->mNegativeButtonText:Ljava/lang/CharSequence;
+Landroid/preference/DialogPreference;->mPositiveButtonText:Ljava/lang/CharSequence;
+Landroid/preference/DialogPreference;->mWhichButtonClicked:I
+Landroid/preference/ListPreference;->mClickedDialogEntryIndex:I
+Landroid/preference/PreferenceActivity;->mPreferenceManager:Landroid/preference/PreferenceManager;
+Landroid/preference/PreferenceActivity;->mPrefsContainer:Landroid/view/ViewGroup;
+Landroid/preference/PreferenceManager;->dispatchActivityDestroy()V
+Landroid/preference/PreferenceManager;->dispatchActivityResult(IILandroid/content/Intent;)V
+Landroid/preference/PreferenceManager;->dispatchActivityStop()V
+Landroid/preference/PreferenceManager;->getEditor()Landroid/content/SharedPreferences$Editor;
+Landroid/preference/PreferenceManager;->getPreferenceScreen()Landroid/preference/PreferenceScreen;
+Landroid/preference/PreferenceManager;->inflateFromIntent(Landroid/content/Intent;Landroid/preference/PreferenceScreen;)Landroid/preference/PreferenceScreen;
+Landroid/preference/PreferenceManager;->inflateFromResource(Landroid/content/Context;ILandroid/preference/PreferenceScreen;)Landroid/preference/PreferenceScreen;
+Landroid/preference/PreferenceManager;->mActivityDestroyListeners:Ljava/util/List;
+Landroid/preference/PreferenceManager;->mOnPreferenceTreeClickListener:Landroid/preference/PreferenceManager$OnPreferenceTreeClickListener;
+Landroid/preference/PreferenceManager;->mSharedPreferences:Landroid/content/SharedPreferences;
+Landroid/preference/PreferenceManager;->registerOnActivityDestroyListener(Landroid/preference/PreferenceManager$OnActivityDestroyListener;)V
+Landroid/preference/PreferenceManager;->registerOnActivityStopListener(Landroid/preference/PreferenceManager$OnActivityStopListener;)V
+Landroid/preference/PreferenceManager;->setFragment(Landroid/preference/PreferenceFragment;)V
+Landroid/preference/PreferenceManager;->setPreferences(Landroid/preference/PreferenceScreen;)Z
+Landroid/preference/PreferenceManager;->shouldCommit()Z
+Landroid/preference/PreferenceManager;->unregisterOnActivityDestroyListener(Landroid/preference/PreferenceManager$OnActivityDestroyListener;)V
+Landroid/preference/PreferenceManager;->unregisterOnActivityStopListener(Landroid/preference/PreferenceManager$OnActivityStopListener;)V
+Landroid/preference/Preference;->onKey(Landroid/view/View;ILandroid/view/KeyEvent;)Z
+Landroid/preference/Preference;->performClick(Landroid/preference/PreferenceScreen;)V
+Landroid/preference/PreferenceScreen;->mRootAdapter:Landroid/widget/ListAdapter;
+Landroid/print/PrinterId;->getServiceName()Landroid/content/ComponentName;
+Landroid/print/PrintJobInfo;->getAdvancedOptions()Landroid/os/Bundle;
+Landroid/print/PrintJobInfo;->getDocumentInfo()Landroid/print/PrintDocumentInfo;
+Landroid/provider/Browser;->canClearHistory(Landroid/content/ContentResolver;)Z
+Landroid/provider/Browser;->clearHistory(Landroid/content/ContentResolver;)V
+Landroid/provider/Browser;->clearSearches(Landroid/content/ContentResolver;)V
+Landroid/provider/Browser;->deleteFromHistory(Landroid/content/ContentResolver;Ljava/lang/String;)V
+Landroid/provider/Browser;->getVisitedHistory(Landroid/content/ContentResolver;)[Ljava/lang/String;
+Landroid/provider/Browser;->sendString(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
+Landroid/provider/Settings$Global;->OTA_DISABLE_AUTOMATIC_UPDATE:Ljava/lang/String;
+Landroid/provider/Settings$Global;->PACKAGE_VERIFIER_ENABLE:Ljava/lang/String;
+Landroid/provider/Settings$Secure;->ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED:Ljava/lang/String;
+Landroid/provider/Settings$Secure;->PACKAGE_VERIFIER_USER_CONSENT:Ljava/lang/String;
+Landroid/provider/Settings$Secure;->USER_SETUP_COMPLETE:Ljava/lang/String;
+Landroid/provider/Settings$System;->AIRPLANE_MODE_TOGGLEABLE_RADIOS:Ljava/lang/String;
+Landroid/provider/Settings$System;->getStringForUser(Landroid/content/ContentResolver;Ljava/lang/String;I)Ljava/lang/String;
+Landroid/provider/Settings$System;->putStringForUser(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;I)Z
+Landroid/provider/Telephony$Sms;->addMessageToUri(ILandroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZJ)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms;->addMessageToUri(ILandroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZ)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms;->addMessageToUri(Landroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZJ)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms;->addMessageToUri(Landroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZ)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms$Inbox;->addMessage(ILandroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Z)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms$Inbox;->addMessage(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Z)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms$Sent;->addMessage(ILandroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;)Landroid/net/Uri;
+Landroid/provider/Telephony$Sms$Sent;->addMessage(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;)Landroid/net/Uri;
+Landroid/renderscript/RenderScript;->create(Landroid/content/Context;I)Landroid/renderscript/RenderScript;
+Landroid/renderscript/RenderScript;->create(Landroid/content/Context;ILandroid/renderscript/RenderScript$ContextType;I)Landroid/renderscript/RenderScript;
+Landroid/renderscript/RenderScript;->getMinorID()J
+Landroid/R$styleable;->TextAppearance:[I
+Landroid/R$styleable;->TextAppearance_textColor:I
+Landroid/R$styleable;->TextAppearance_textSize:I
+Landroid/security/KeyStore;->getInstance()Landroid/security/KeyStore;
+Landroid/service/media/IMediaBrowserServiceCallbacks;->onConnectFailed()V
+Landroid/service/media/IMediaBrowserServiceCallbacks;->onConnect(Ljava/lang/String;Landroid/media/session/MediaSession$Token;Landroid/os/Bundle;)V
+Landroid/service/media/IMediaBrowserServiceCallbacks;->onLoadChildren(Ljava/lang/String;Landroid/content/pm/ParceledListSlice;)V
+Landroid/service/media/IMediaBrowserServiceCallbacks;->onLoadChildrenWithOptions(Ljava/lang/String;Landroid/content/pm/ParceledListSlice;Landroid/os/Bundle;)V
+Landroid/service/media/MediaBrowserService;->KEY_MEDIA_ITEM:Ljava/lang/String;
+Landroid/service/notification/NotificationListenerService;->registerAsSystemService(Landroid/content/Context;Landroid/content/ComponentName;I)V
+Landroid/service/notification/NotificationListenerService;->unregisterAsSystemService()V
+Landroid/service/wallpaper/WallpaperService$Engine;->setFixedSizeAllowed(Z)V
+Landroid/speech/tts/TextToSpeech;->getCurrentEngine()Ljava/lang/String;
+Landroid/telephony/PhoneStateListener;->mSubId:Ljava/lang/Integer;
+Landroid/telephony/ServiceState;->newFromBundle(Landroid/os/Bundle;)Landroid/telephony/ServiceState;
+Landroid/telephony/SignalStrength;->getCdmaLevel()I
+Landroid/telephony/SignalStrength;->getLteDbm()I
+Landroid/telephony/SignalStrength;->getLteRsrp()I
+Landroid/telephony/SignalStrength;->getLteRssnr()I
+Landroid/telephony/SignalStrength;->getLteSignalStrength()I
+Landroid/telephony/SmsManager;->RESULT_ERROR_FDN_CHECK_FAILURE:I
+Landroid/telephony/SmsMessage;->getSubId()I
+Landroid/telephony/SmsMessage;->mWrappedSmsMessage:Lcom/android/internal/telephony/SmsMessageBase;
+Landroid/telephony/SubscriptionManager;->getDefaultSmsPhoneId()I
+Landroid/telephony/SubscriptionManager;->getPhoneId(I)I
+Landroid/telephony/SubscriptionManager;->getSubId(I)[I
+Landroid/telephony/SubscriptionManager;->setDefaultSmsSubId(I)V
+Landroid/telephony/TelephonyManager;->from(Landroid/content/Context;)Landroid/telephony/TelephonyManager;
+Landroid/telephony/TelephonyManager;->getCurrentPhoneType()I
+Landroid/telephony/TelephonyManager;->getCurrentPhoneType(I)I
+Landroid/telephony/TelephonyManager;->getDataEnabled(I)Z
+Landroid/telephony/TelephonyManager;->getDataEnabled()Z
+Landroid/telephony/TelephonyManager;->getDefault()Landroid/telephony/TelephonyManager;
+Landroid/telephony/TelephonyManager;->getITelephony()Lcom/android/internal/telephony/ITelephony;
+Landroid/telephony/TelephonyManager;->getLine1Number(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->getNetworkClass(I)I
+Landroid/telephony/TelephonyManager;->getNetworkOperator(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->getNetworkOperatorName(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->getNetworkType(I)I
+Landroid/telephony/TelephonyManager;->getSimOperator(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->getSimSerialNumber(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->getSubscriberId(I)Ljava/lang/String;
+Landroid/telephony/TelephonyManager;->isMultiSimEnabled()Z
+Landroid/telephony/TelephonyManager;->setDataEnabled(IZ)V
+Landroid/text/AndroidBidi;->bidi(I[C[B)I
+Landroid/text/DynamicLayout;->sStaticLayout:Landroid/text/StaticLayout;
+Landroid/text/Html;->withinStyle(Ljava/lang/StringBuilder;Ljava/lang/CharSequence;II)V
+Landroid/text/Layout;->DIRS_ALL_LEFT_TO_RIGHT:Landroid/text/Layout$Directions;
+Landroid/text/method/LinkMovementMethod;->sInstance:Landroid/text/method/LinkMovementMethod;
+Landroid/text/SpannableStringBuilder;->mGapLength:I
+Landroid/text/SpannableStringBuilder;->mGapStart:I
+Landroid/text/SpannableStringBuilder;->mSpanCount:I
+Landroid/text/SpannableStringBuilder;->mSpanEnds:[I
+Landroid/text/SpannableStringBuilder;->mSpanFlags:[I
+Landroid/text/SpannableStringBuilder;->mSpans:[Ljava/lang/Object;
+Landroid/text/SpannableStringBuilder;->mSpanStarts:[I
+Landroid/text/StaticLayout;->mColumns:I
+Landroid/text/StaticLayout;->mLineCount:I
+Landroid/text/StaticLayout;->mLines:[I
+Landroid/text/TextLine;->obtain()Landroid/text/TextLine;
+Landroid/text/TextLine;->sCached:[Landroid/text/TextLine;
+Landroid/text/TextPaint;->setUnderlineText(IF)V
+Landroid/util/Log;->wtf(ILjava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;ZZ)I
+Landroid/util/Pools$SynchronizedPool;->acquire()Ljava/lang/Object;
+Landroid/view/accessibility/AccessibilityManager;->getInstance(Landroid/content/Context;)Landroid/view/accessibility/AccessibilityManager;
+Landroid/view/accessibility/AccessibilityManager;->isHighTextContrastEnabled()Z
+Landroid/view/accessibility/AccessibilityManager;->sInstance:Landroid/view/accessibility/AccessibilityManager;
+Landroid/view/accessibility/AccessibilityManager;->sInstanceSync:Ljava/lang/Object;
+Landroid/view/accessibility/AccessibilityNodeInfo;->refresh(Landroid/os/Bundle;Z)Z
+Landroid/view/ActionMode;->isUiFocusable()Z
+Landroid/view/animation/Animation;->mListener:Landroid/view/animation/Animation$AnimationListener;
+Landroid/view/Choreographer;->doFrame(JI)V
+Landroid/view/Choreographer;->getFrameTime()J
+Landroid/view/Choreographer;->mCallbackQueues:[Landroid/view/Choreographer$CallbackQueue;
+Landroid/view/Choreographer;->postCallback(ILjava/lang/Runnable;Ljava/lang/Object;)V
+Landroid/view/Choreographer;->removeCallbacks(ILjava/lang/Runnable;Ljava/lang/Object;)V
+Landroid/view/Choreographer;->scheduleVsyncLocked()V
+Landroid/view/ContextThemeWrapper;->mResources:Landroid/content/res/Resources;
+Landroid/view/ContextThemeWrapper;->mTheme:Landroid/content/res/Resources$Theme;
+Landroid/view/ContextThemeWrapper;->mThemeResource:I
+Landroid/view/InputDevice;->isExternal()Z
+Landroid/view/inputmethod/InputMethodManager;->finishInputLocked()V
+Landroid/view/inputmethod/InputMethodManager;->focusIn(Landroid/view/View;)V
+Landroid/view/inputmethod/InputMethodManager;->getInputMethodWindowVisibleHeight()I
+Landroid/view/inputmethod/InputMethodManager;->mCurId:Ljava/lang/String;
+Landroid/view/inputmethod/InputMethodManager;->mCurRootView:Landroid/view/View;
+Landroid/view/inputmethod/InputMethodManager;->mNextServedView:Landroid/view/View;
+Landroid/view/inputmethod/InputMethodManager;->mServedView:Landroid/view/View;
+Landroid/view/inputmethod/InputMethodManager;->notifyUserAction()V
+Landroid/view/inputmethod/InputMethodManager;->showSoftInputUnchecked(ILandroid/os/ResultReceiver;)V
+Landroid/view/inputmethod/InputMethodManager;->windowDismissed(Landroid/os/IBinder;)V
+Landroid/view/IWindowManager;->getAnimationScale(I)F
+Landroid/view/IWindowManager;->hasNavigationBar()Z
+Landroid/view/IWindowManager;->setAnimationScale(IF)V
+Landroid/view/IWindowManager;->setStrictModeVisualIndicatorPreference(Ljava/lang/String;)V
+Landroid/view/IWindowManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/view/IWindowManager;
+Landroid/view/IWindowSession$Stub$Proxy;->relayout(Landroid/view/IWindow;ILandroid/view/WindowManager$LayoutParams;IIIILandroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/view/DisplayCutout$ParcelableWrapper;Landroid/util/MergedConfiguration;Landroid/view/Surface;)I
+Landroid/view/LayoutInflater;->mConstructorArgs:[Ljava/lang/Object;
+Landroid/view/LayoutInflater;->mFactory2:Landroid/view/LayoutInflater$Factory2;
+Landroid/view/LayoutInflater;->mFactory:Landroid/view/LayoutInflater$Factory;
+Landroid/view/LayoutInflater;->mFactorySet:Z
+Landroid/view/LayoutInflater;->sConstructorMap:Ljava/util/HashMap;
+Landroid/view/MotionEvent;->HISTORY_CURRENT:I
+Landroid/view/MotionEvent;->mNativePtr:J
+Landroid/view/MotionEvent;->nativeGetRawAxisValue(JIII)F
+Landroid/view/MotionEvent;->scale(F)V
+Landroid/view/ScaleGestureDetector;->mListener:Landroid/view/ScaleGestureDetector$OnScaleGestureListener;
+Landroid/view/SurfaceView;->mCallbacks:Ljava/util/ArrayList;
+Landroid/view/SurfaceView;->mFormat:I
+Landroid/view/SurfaceView;->mRequestedFormat:I
+Landroid/view/SurfaceView;->mSurfaceHolder:Landroid/view/SurfaceHolder;
+Landroid/view/textservice/TextServicesManager;->isSpellCheckerEnabled()Z
+Landroid/view/TextureView;->mLayer:Landroid/view/HardwareLayer;
+Landroid/view/TextureView;->mSurface:Landroid/graphics/SurfaceTexture;
+Landroid/view/TextureView;->mUpdateListener:Landroid/graphics/SurfaceTexture$OnFrameAvailableListener;
+Landroid/view/TouchDelegate;->mDelegateTargeted:Z
+Landroid/view/VelocityTracker;->obtain(Ljava/lang/String;)Landroid/view/VelocityTracker;
+Landroid/view/View;->clearAccessibilityFocus()V
+Landroid/view/View;->computeOpaqueFlags()V
+Landroid/view/ViewConfiguration;->mFadingMarqueeEnabled:Z
+Landroid/view/ViewConfiguration;->sHasPermanentMenuKeySet:Z
+Landroid/view/ViewConfiguration;->sHasPermanentMenuKey:Z
+Landroid/view/View;->createSnapshot(Landroid/view/ViewDebug$CanvasProvider;Z)Landroid/graphics/Bitmap;
+Landroid/view/ViewDebug;->dispatchCommand(Landroid/view/View;Ljava/lang/String;Ljava/lang/String;Ljava/io/OutputStream;)V
+Landroid/view/ViewDebug;->dump(Landroid/view/View;ZZLjava/io/OutputStream;)V
+Landroid/view/View;->dispatchAttachedToWindow(Landroid/view/View$AttachInfo;I)V
+Landroid/view/View;->dispatchDetachedFromWindow()V
+Landroid/view/View;->fitsSystemWindows()Z
+Landroid/view/View;->getListenerInfo()Landroid/view/View$ListenerInfo;
+Landroid/view/View;->getViewRootImpl()Landroid/view/ViewRootImpl;
+Landroid/view/ViewGroup;->FLAG_SUPPORT_STATIC_TRANSFORMATIONS:I
+Landroid/view/ViewGroup;->FLAG_USE_CHILD_DRAWING_ORDER:I
+Landroid/view/ViewGroup$MarginLayoutParams;->endMargin:I
+Landroid/view/ViewGroup$MarginLayoutParams;->startMargin:I
+Landroid/view/ViewGroup;->mChildren:[Landroid/view/View;
+Landroid/view/ViewGroup;->mFirstTouchTarget:Landroid/view/ViewGroup$TouchTarget;
+Landroid/view/ViewGroup;->mGroupFlags:I
+Landroid/view/ViewGroup;->mOnHierarchyChangeListener:Landroid/view/ViewGroup$OnHierarchyChangeListener;
+Landroid/view/View;->initializeScrollbars(Landroid/content/res/TypedArray;)V
+Landroid/view/View;->isPaddingResolved()Z
+Landroid/view/View;->isVisibleToUser(Landroid/graphics/Rect;)Z
+Landroid/view/View;->isVisibleToUser()Z
+Landroid/view/View$ListenerInfo;->mOnClickListener:Landroid/view/View$OnClickListener;
+Landroid/view/View$ListenerInfo;->mOnTouchListener:Landroid/view/View$OnTouchListener;
+Landroid/view/View;->mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate;
+Landroid/view/View;->mAttachInfo:Landroid/view/View$AttachInfo;
+Landroid/view/View;->mBottom:I
+Landroid/view/View;->mContext:Landroid/content/Context;
+Landroid/view/View;->mDrawingCache:Landroid/graphics/Bitmap;
+Landroid/view/View;->mLeft:I
+Landroid/view/View;->mListenerInfo:Landroid/view/View$ListenerInfo;
+Landroid/view/View;->mMinHeight:I
+Landroid/view/View;->mMinWidth:I
+Landroid/view/View;->mPaddingLeft:I
+Landroid/view/View;->mPaddingRight:I
+Landroid/view/View;->mParent:Landroid/view/ViewParent;
+Landroid/view/View;->mPrivateFlags3:I
+Landroid/view/View;->mRecreateDisplayList:Z
+Landroid/view/View;->mResources:Landroid/content/res/Resources;
+Landroid/view/View;->mRight:I
+Landroid/view/View;->mScrollCache:Landroid/view/View$ScrollabilityCache;
+Landroid/view/View;->mScrollX:I
+Landroid/view/View;->mScrollY:I
+Landroid/view/View;->mStartActivityRequestWho:Ljava/lang/String;
+Landroid/view/View;->mTop:I
+Landroid/view/View;->mUnscaledDrawingCache:Landroid/graphics/Bitmap;
+Landroid/view/View;->notifySubtreeAccessibilityStateChangedIfNeeded()V
+Landroid/view/View;->recomputePadding()V
+Landroid/view/View;->requestAccessibilityFocus()Z
+Landroid/view/View;->resetPaddingToInitialValues()V
+Landroid/view/ViewRootImpl;->detachFunctor(J)V
+Landroid/view/ViewRootImpl;->invokeFunctor(JZ)V
+Landroid/view/ViewRootImpl;->mStopped:Z
+Landroid/view/View;->setAssistBlocked(Z)V
+Landroid/view/View;->setFrame(IIII)Z
+Landroid/view/View;->setIsRootNamespace(Z)V
+Landroid/view/View;->startActivityForResult(Landroid/content/Intent;I)V
+Landroid/view/View;->STATUS_BAR_DISABLE_BACK:I
+Landroid/view/View;->STATUS_BAR_DISABLE_EXPAND:I
+Landroid/view/View;->STATUS_BAR_DISABLE_HOME:I
+Landroid/view/View;->STATUS_BAR_DISABLE_RECENT:I
+Landroid/view/View;->toGlobalMotionEvent(Landroid/view/MotionEvent;)Z
+Landroid/view/View;->toLocalMotionEvent(Landroid/view/MotionEvent;)Z
+Landroid/view/ViewTreeObserver;->addOnComputeInternalInsetsListener(Landroid/view/ViewTreeObserver$OnComputeInternalInsetsListener;)V
+Landroid/view/ViewTreeObserver$InternalInsetsInfo;->setTouchableInsets(I)V
+Landroid/view/ViewTreeObserver$InternalInsetsInfo;->TOUCHABLE_INSETS_REGION:I
+Landroid/view/ViewTreeObserver$InternalInsetsInfo;->touchableRegion:Landroid/graphics/Region;
+Landroid/view/ViewTreeObserver;->removeOnComputeInternalInsetsListener(Landroid/view/ViewTreeObserver$OnComputeInternalInsetsListener;)V
+Landroid/view/WindowManagerGlobal;->getInstance()Landroid/view/WindowManagerGlobal;
+Landroid/view/WindowManagerGlobal;->getRootView(Ljava/lang/String;)Landroid/view/View;
+Landroid/view/WindowManagerGlobal;->getViewRootNames()[Ljava/lang/String;
+Landroid/view/WindowManagerGlobal;->getWindowManagerService()Landroid/view/IWindowManager;
+Landroid/view/WindowManagerGlobal;->mLock:Ljava/lang/Object;
+Landroid/view/WindowManagerGlobal;->mViews:Ljava/util/ArrayList;
+Landroid/view/WindowManagerGlobal;->trimMemory(I)V
+Landroid/view/WindowManager$LayoutParams;->needsMenuKey:I
+Landroid/view/WindowManager$LayoutParams;->NEEDS_MENU_SET_TRUE:I
+Landroid/view/WindowManager$LayoutParams;->privateFlags:I
+Landroid/view/WindowManager$LayoutParams;->userActivityTimeout:J
+Landroid/view/Window;->mAppName:Ljava/lang/String;
+Landroid/view/Window;->mAppToken:Landroid/os/IBinder;
+Landroid/view/Window;->mHardwareAccelerated:Z
+Landroid/webkit/WebSettings;->setNavDump(Z)V
+Landroid/webkit/WebSettings;->setPluginsEnabled(Z)V
+Landroid/webkit/WebView;->debugDump()V
+Landroid/webkit/WebView;->disablePlatformNotifications()V
+Landroid/webkit/WebView;->emulateShiftHeld()V
+Landroid/webkit/WebView;->enablePlatformNotifications()V
+Landroid/webkit/WebViewFactory;->getLoadedPackageInfo()Landroid/content/pm/PackageInfo;
+Landroid/webkit/WebViewFactory;->getProvider()Landroid/webkit/WebViewFactoryProvider;
+Landroid/webkit/WebView;->getVisibleTitleHeight()I
+Landroid/webkit/WebView;->getWebViewProvider()Landroid/webkit/WebViewProvider;
+Landroid/webkit/WebView;->isPaused()Z
+Landroid/webkit/WebView;->mProvider:Landroid/webkit/WebViewProvider;
+Landroid/webkit/WebView;->notifyFindDialogDismissed()V
+Landroid/webkit/WebView;->restorePicture(Landroid/os/Bundle;Ljava/io/File;)Z
+Landroid/webkit/WebView;->savePicture(Landroid/os/Bundle;Ljava/io/File;)Z
+Landroid/webkit/WebView;->sEnforceThreadChecking:Z
+Landroid/widget/AbsListView$FlingRunnable;->endFling()V
+Landroid/widget/AbsListView;->invokeOnItemScrollListener()V
+Landroid/widget/AbsListView;->isVerticalScrollBarHidden()Z
+Landroid/widget/AbsListView;->mAdapter:Landroid/widget/ListAdapter;
+Landroid/widget/AbsListView;->mEdgeGlowBottom:Landroid/widget/EdgeEffect;
+Landroid/widget/AbsListView;->mEdgeGlowTop:Landroid/widget/EdgeEffect;
+Landroid/widget/AbsListView;->mFastScroll:Landroid/widget/FastScroller;
+Landroid/widget/AbsListView;->mFlingRunnable:Landroid/widget/AbsListView$FlingRunnable;
+Landroid/widget/AbsListView;->mIsChildViewEnabled:Z
+Landroid/widget/AbsListView;->mMaximumVelocity:I
+Landroid/widget/AbsListView;->mMotionPosition:I
+Landroid/widget/AbsListView;->mOnScrollListener:Landroid/widget/AbsListView$OnScrollListener;
+Landroid/widget/AbsListView;->mRecycler:Landroid/widget/AbsListView$RecycleBin;
+Landroid/widget/AbsListView;->mSelectionTopPadding:I
+Landroid/widget/AbsListView;->mSelectorPosition:I
+Landroid/widget/AbsListView;->mSelectorRect:Landroid/graphics/Rect;
+Landroid/widget/AbsListView;->mTouchMode:I
+Landroid/widget/AbsListView;->mTouchSlop:I
+Landroid/widget/AbsListView;->mVelocityTracker:Landroid/view/VelocityTracker;
+Landroid/widget/AbsListView;->performLongPress(Landroid/view/View;IJFF)Z
+Landroid/widget/AbsListView;->performLongPress(Landroid/view/View;IJ)Z
+Landroid/widget/AbsListView;->smoothScrollBy(IIZZ)V
+Landroid/widget/AbsListView;->trackMotionScroll(II)Z
+Landroid/widget/AbsSeekBar;->mIsDragging:Z
+Landroid/widget/AbsSeekBar;->mSplitTrack:Z
+Landroid/widget/AbsSeekBar;->mThumb:Landroid/graphics/drawable/Drawable;
+Landroid/widget/AbsSeekBar;->mTouchProgressOffset:F
+Landroid/widget/ActivityChooserView;->setExpandActivityOverflowButtonDrawable(Landroid/graphics/drawable/Drawable;)V
+Landroid/widget/AdapterView;->mDataChanged:Z
+Landroid/widget/AdapterView;->setNextSelectedPositionInt(I)V
+Landroid/widget/AdapterView;->setSelectedPositionInt(I)V
+Landroid/widget/AutoCompleteTextView;->doAfterTextChanged()V
+Landroid/widget/AutoCompleteTextView;->doBeforeTextChanged()V
+Landroid/widget/AutoCompleteTextView;->ensureImeVisible(Z)V
+Landroid/widget/AutoCompleteTextView;->mPopup:Landroid/widget/ListPopupWindow;
+Landroid/widget/AutoCompleteTextView;->setDropDownAlwaysVisible(Z)V
+Landroid/widget/CompoundButton;->mButtonDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/DatePicker;->mDelegate:Landroid/widget/DatePicker$DatePickerDelegate;
+Landroid/widget/EdgeEffect;->mPaint:Landroid/graphics/Paint;
+Landroid/widget/Editor;->mShowCursor:J
+Landroid/widget/ExpandableListView;->mChildDivider:Landroid/graphics/drawable/Drawable;
+Landroid/widget/FastScroller;->mThumbDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/FastScroller;->mTrackDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/Gallery;->mDownTouchView:Landroid/view/View;
+Landroid/widget/GridView;->mColumnWidth:I
+Landroid/widget/GridView;->mHorizontalSpacing:I
+Landroid/widget/GridView;->mNumColumns:I
+Landroid/widget/GridView;->mRequestedNumColumns:I
+Landroid/widget/GridView;->mVerticalSpacing:I
+Landroid/widget/HorizontalScrollView;->mEdgeGlowLeft:Landroid/widget/EdgeEffect;
+Landroid/widget/HorizontalScrollView;->mEdgeGlowRight:Landroid/widget/EdgeEffect;
+Landroid/widget/HorizontalScrollView;->mScroller:Landroid/widget/OverScroller;
+Landroid/widget/ImageView;->mAdjustViewBounds:Z
+Landroid/widget/ImageView;->mAlpha:I
+Landroid/widget/ImageView;->mMaxHeight:I
+Landroid/widget/ImageView;->mMaxWidth:I
+Landroid/widget/LinearLayout;->mGravity:I
+Landroid/widget/LinearLayout;->mUseLargestChild:Z
+Landroid/widget/ListPopupWindow;->mPopup:Landroid/widget/PopupWindow;
+Landroid/widget/ListPopupWindow;->setForceIgnoreOutsideTouch(Z)V
+Landroid/widget/ListView;->mAreAllItemsSelectable:Z
+Landroid/widget/ListView;->setSelectionInt(I)V
+Landroid/widget/MediaController;->mAnchor:Landroid/view/View;
+Landroid/widget/MediaController;->mDecor:Landroid/view/View;
+Landroid/widget/MediaController;->mDecorLayoutParams:Landroid/view/WindowManager$LayoutParams;
+Landroid/widget/MediaController;->mWindowManager:Landroid/view/WindowManager;
+Landroid/widget/NumberPicker;->mInputText:Landroid/widget/EditText;
+Landroid/widget/NumberPicker;->mSelectionDivider:Landroid/graphics/drawable/Drawable;
+Landroid/widget/NumberPicker;->mSelectorWheelPaint:Landroid/graphics/Paint;
+Landroid/widget/PopupMenu;->mPopup:Lcom/android/internal/view/menu/MenuPopupHelper;
+Landroid/widget/PopupWindow;->computeAnimationResource()I
+Landroid/widget/PopupWindow;->createPopupLayoutParams(Landroid/os/IBinder;)Landroid/view/WindowManager$LayoutParams;
+Landroid/widget/PopupWindow;->invokePopup(Landroid/view/WindowManager$LayoutParams;)V
+Landroid/widget/PopupWindow;->mAboveAnchor:Z
+Landroid/widget/PopupWindow;->mAnchor:Ljava/lang/ref/WeakReference;
+Landroid/widget/PopupWindow;->mAnimationStyle:I
+Landroid/widget/PopupWindow;->mBackgroundView:Landroid/view/View;
+Landroid/widget/PopupWindow;->mContentView:Landroid/view/View;
+Landroid/widget/PopupWindow;->mHeightMode:I
+Landroid/widget/PopupWindow;->mIsDropdown:Z
+Landroid/widget/PopupWindow;->mIsShowing:Z
+Landroid/widget/PopupWindow;->mLastHeight:I
+Landroid/widget/PopupWindow;->mLastWidth:I
+Landroid/widget/PopupWindow;->mOnScrollChangedListener:Landroid/view/ViewTreeObserver$OnScrollChangedListener;
+Landroid/widget/PopupWindow;->mWidthMode:I
+Landroid/widget/PopupWindow;->preparePopup(Landroid/view/WindowManager$LayoutParams;)V
+Landroid/widget/PopupWindow;->setLayoutInScreenEnabled(Z)V
+Landroid/widget/PopupWindow;->setLayoutInsetDecor(Z)V
+Landroid/widget/PopupWindow;->setTouchModal(Z)V
+Landroid/widget/ProgressBar;->mCurrentDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/ProgressBar;->mDuration:I
+Landroid/widget/ProgressBar;->mIndeterminate:Z
+Landroid/widget/ProgressBar;->mMaxHeight:I
+Landroid/widget/ProgressBar;->mMinHeight:I
+Landroid/widget/ProgressBar;->mOnlyIndeterminate:Z
+Landroid/widget/RelativeLayout$LayoutParams;->mBottom:I
+Landroid/widget/RelativeLayout$LayoutParams;->mLeft:I
+Landroid/widget/RelativeLayout$LayoutParams;->mRight:I
+Landroid/widget/RelativeLayout$LayoutParams;->mTop:I
+Landroid/widget/RelativeLayout;->mGravity:I
+Landroid/widget/RemoteViews$Action;->mergeBehavior()I
+Landroid/widget/RemoteViews$Action;->viewId:I
+Landroid/widget/RemoteViews;->mActions:Ljava/util/ArrayList;
+Landroid/widget/RemoteViews;->mApplication:Landroid/content/pm/ApplicationInfo;
+Landroid/widget/RemoteViews$ReflectionAction;->methodName:Ljava/lang/String;
+Landroid/widget/ScrollView;->mEdgeGlowBottom:Landroid/widget/EdgeEffect;
+Landroid/widget/ScrollView;->mEdgeGlowTop:Landroid/widget/EdgeEffect;
+Landroid/widget/ScrollView;->mIsBeingDragged:Z
+Landroid/widget/ScrollView;->mOverflingDistance:I
+Landroid/widget/ScrollView;->mOverscrollDistance:I
+Landroid/widget/ScrollView;->mScroller:Landroid/widget/OverScroller;
+Landroid/widget/SearchView;->mCloseButton:Landroid/widget/ImageView;
+Landroid/widget/SearchView;->mSearchButton:Landroid/widget/ImageView;
+Landroid/widget/SearchView;->mSearchPlate:Landroid/view/View;
+Landroid/widget/SearchView;->onCloseClicked()V
+Landroid/widget/SearchView;->setQuery(Ljava/lang/CharSequence;)V
+Landroid/widget/SlidingDrawer;->mTopOffset:I
+Landroid/widget/Spinner;->mPopup:Landroid/widget/Spinner$SpinnerPopup;
+Landroid/widget/Switch;->mThumbDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/Switch;->mTrackDrawable:Landroid/graphics/drawable/Drawable;
+Landroid/widget/TabWidget;->setTabSelectionListener(Landroid/widget/TabWidget$OnTabSelectionChanged;)V
+Landroid/widget/TextView;->createEditorIfNeeded()V
+Landroid/widget/TextView;->mCursorDrawableRes:I
+Landroid/widget/TextView;->mCurTextColor:I
+Landroid/widget/TextView;->mEditor:Landroid/widget/Editor;
+Landroid/widget/TextView;->mListeners:Ljava/util/ArrayList;
+Landroid/widget/TextView;->mMarquee:Landroid/widget/TextView$Marquee;
+Landroid/widget/TextView;->mMaximum:I
+Landroid/widget/TextView;->mMaxMode:I
+Landroid/widget/TextView;->mSingleLine:Z
+Landroid/widget/VideoView;->mCurrentBufferPercentage:I
+Landroid/widget/VideoView;->mMediaController:Landroid/widget/MediaController;
+Landroid/widget/VideoView;->mSHCallback:Landroid/view/SurfaceHolder$Callback;
+Landroid/widget/VideoView;->mUri:Landroid/net/Uri;
+Landroid/widget/VideoView;->mVideoHeight:I
+Landroid/widget/VideoView;->mVideoWidth:I
+Lcom/android/internal/app/IBatteryStats;->getStatistics()[B
+Lcom/android/internal/app/IBatteryStats$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/app/IBatteryStats;
+Lcom/android/internal/os/BatteryStatsImpl;->computeBatteryRealtime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl;->computeBatteryUptime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl;->CREATOR:Landroid/os/Parcelable$Creator;
+Lcom/android/internal/os/BatteryStatsImpl;->getGlobalWifiRunningTime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl;->getScreenOnTime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl;->getUidStats()Landroid/util/SparseArray;
+Lcom/android/internal/os/BatteryStatsImpl$Timer;->getCountLocked(I)I
+Lcom/android/internal/os/BatteryStatsImpl$Timer;->getTotalTimeLocked(JI)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getProcessStats()Landroid/util/ArrayMap;
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getSensorStats()Landroid/util/SparseArray;
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getUid()I
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getWakelockStats()Landroid/util/ArrayMap;
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getWifiRunningTime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid;->getWifiScanTime(JI)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Proc;->getForegroundTime(I)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Proc;->getStarts(I)I
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Proc;->getSystemTime(I)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Proc;->getUserTime(I)J
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Sensor;->getHandle()I
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Sensor;->getSensorTime()Lcom/android/internal/os/BatteryStatsImpl$Timer;
+Lcom/android/internal/os/BatteryStatsImpl$Uid$Wakelock;->getWakeTime(I)Lcom/android/internal/os/BatteryStatsImpl$Timer;
+Lcom/android/internal/os/PowerProfile;->getAveragePower(Ljava/lang/String;)D
+Lcom/android/internal/os/PowerProfile;->getAveragePower(Ljava/lang/String;I)D
+Lcom/android/internal/os/PowerProfile;->getBatteryCapacity()D
+Lcom/android/internal/R$array;->config_mobile_hotspot_provision_app:I
+Lcom/android/internal/R$array;->config_tether_wifi_regexs:I
+Lcom/android/internal/R$attr;->switchStyle:I
+Lcom/android/internal/R$bool;->config_mms_content_disposition_support:I
+Lcom/android/internal/R$bool;->config_showNavigationBar:I
+Lcom/android/internal/R$dimen;->navigation_bar_height:I
+Lcom/android/internal/R$dimen;->navigation_bar_height_landscape:I
+Lcom/android/internal/R$dimen;->status_bar_height:I
+Lcom/android/internal/R$drawable;->ic_menu_close_clear_cancel:I
+Lcom/android/internal/R$id;->amPm:I
+Lcom/android/internal/R$id;->edittext_container:I
+Lcom/android/internal/R$id;->icon:I
+Lcom/android/internal/R$id;->message:I
+Lcom/android/internal/R$id;->minute:I
+Lcom/android/internal/R$id;->shortcut:I
+Lcom/android/internal/R$id;->text:I
+Lcom/android/internal/R$id;->time:I
+Lcom/android/internal/R$id;->timePicker:I
+Lcom/android/internal/R$id;->title_container:I
+Lcom/android/internal/R$id;->title:I
+Lcom/android/internal/R$integer;->config_screenBrightnessDim:I
+Lcom/android/internal/R$layout;->screen_title:I
+Lcom/android/internal/R$styleable;->CompoundButton_button:I
+Lcom/android/internal/R$styleable;->CompoundButton:[I
+Lcom/android/internal/R$styleable;->IconMenuView:[I
+Lcom/android/internal/R$styleable;->ImageView:[I
+Lcom/android/internal/R$styleable;->ImageView_src:I
+Lcom/android/internal/R$styleable;->ScrollView:[I
+Lcom/android/internal/R$styleable;->TabWidget:[I
+Lcom/android/internal/R$styleable;->TextView_drawableBottom:I
+Lcom/android/internal/R$styleable;->TextView_drawableLeft:I
+Lcom/android/internal/R$styleable;->TextView_drawableRight:I
+Lcom/android/internal/R$styleable;->TextView_drawableTop:I
+Lcom/android/internal/R$styleable;->TextView:[I
+Lcom/android/internal/R$styleable;->View_background:I
+Lcom/android/internal/R$styleable;->View:[I
+Lcom/android/internal/R$styleable;->View_id:I
+Lcom/android/internal/R$styleable;->ViewStub:[I
+Lcom/android/internal/R$styleable;->ViewStub_inflatedId:I
+Lcom/android/internal/R$styleable;->ViewStub_layout:I
+Lcom/android/internal/R$styleable;->Window_windowActionBarFullscreenDecorLayout:I
+Lcom/android/internal/R$xml;->power_profile:I
+Lcom/android/internal/telephony/IPhoneSubInfo$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/IPhoneSubInfo;
+Lcom/android/internal/telephony/ISms$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ISms;
+Lcom/android/internal/telephony/ITelephony;->call(Ljava/lang/String;Ljava/lang/String;)V
+Lcom/android/internal/telephony/ITelephony;->endCall()Z
+Lcom/android/internal/telephony/ITelephony;->isIdle(Ljava/lang/String;)Z
+Lcom/android/internal/telephony/ITelephony;->silenceRinger()V
+Lcom/android/internal/telephony/ITelephony$Stub;->asInterface(Landroid/os/IBinder;)Lcom/android/internal/telephony/ITelephony;
+Lcom/android/internal/util/XmlUtils;->readMapXml(Ljava/io/InputStream;)Ljava/util/HashMap;
+Lcom/android/internal/view/InputBindResult;->CREATOR:Landroid/os/Parcelable$Creator;
+Lcom/android/internal/view/menu/MenuBuilder;->mContext:Landroid/content/Context;
+Lcom/android/internal/view/menu/MenuBuilder;->setCurrentMenuInfo(Landroid/view/ContextMenu$ContextMenuInfo;)V
+Lcom/android/internal/view/menu/MenuBuilder;->setOptionalIconsVisible(Z)V
+Lcom/android/internal/view/menu/MenuItemImpl;->mIconResId:I
+Lcom/android/internal/view/menu/MenuItemImpl;->setMenuInfo(Landroid/view/ContextMenu$ContextMenuInfo;)V
+Lcom/android/okhttp/ConnectionPool;->maxIdleConnections:I
+Lcom/android/okhttp/ConnectionPool;->systemDefault:Lcom/android/okhttp/ConnectionPool;
+Ldalvik/system/BaseDexClassLoader;->getLdLibraryPath()Ljava/lang/String;
+Ldalvik/system/BaseDexClassLoader;->pathList:Ldalvik/system/DexPathList;
+Ldalvik/system/DexFile;->mCookie:Ljava/lang/Object;
+Ldalvik/system/DexFile;->mFileName:Ljava/lang/String;
+Ldalvik/system/DexFile;->openDexFile(Ljava/lang/String;Ljava/lang/String;ILjava/lang/ClassLoader;[Ldalvik/system/DexPathList$Element;)Ljava/lang/Object;
+Ldalvik/system/DexPathList;->dexElements:[Ldalvik/system/DexPathList$Element;
+Ldalvik/system/DexPathList$Element;->dexFile:Ldalvik/system/DexFile;
+Ldalvik/system/DexPathList;->makeDexElements(Ljava/util/List;Ljava/io/File;Ljava/util/List;Ljava/lang/ClassLoader;)[Ldalvik/system/DexPathList$Element;
+Ldalvik/system/DexPathList;->makePathElements(Ljava/util/List;)[Ldalvik/system/DexPathList$NativeLibraryElement;
+Ldalvik/system/DexPathList;->makePathElements(Ljava/util/List;Ljava/io/File;Ljava/util/List;)[Ldalvik/system/DexPathList$Element;
+Ldalvik/system/DexPathList;->nativeLibraryDirectories:Ljava/util/List;
+Ldalvik/system/DexPathList;->nativeLibraryPathElements:[Ldalvik/system/DexPathList$NativeLibraryElement;
+Ldalvik/system/VMDebug;->dumpReferenceTables()V
+Ldalvik/system/VMRuntime;->clearGrowthLimit()V
+Ldalvik/system/VMRuntime;->getCurrentInstructionSet()Ljava/lang/String;
+Ldalvik/system/VMRuntime;->getRuntime()Ldalvik/system/VMRuntime;
+Ldalvik/system/VMRuntime;->is64Bit()Z
+Ldalvik/system/VMRuntime;->newNonMovableArray(Ljava/lang/Class;I)Ljava/lang/Object;
+Ldalvik/system/VMRuntime;->registerNativeAllocation(I)V
+Ldalvik/system/VMRuntime;->registerNativeFree(I)V
+Ldalvik/system/VMRuntime;->setMinimumHeapSize(J)J
+Ldalvik/system/VMRuntime;->setTargetHeapUtilization(F)F
+Ldalvik/system/VMRuntime;->trackExternalAllocation(J)Z
+Ldalvik/system/VMRuntime;->trackExternalFree(J)V
+Ldalvik/system/VMStack;->getCallingClassLoader()Ljava/lang/ClassLoader;
+Ldalvik/system/VMStack;->getStackClass2()Ljava/lang/Class;
+Ljava/io/FileDescriptor;->descriptor:I
+Ljava/io/FileDescriptor;->getInt$()I
+Ljava/io/FileDescriptor;->setInt$(I)V
+Ljava/io/ObjectStreamClass;->getConstructorId(Ljava/lang/Class;)J
+Ljava/io/ObjectStreamClass;->newInstance(Ljava/lang/Class;J)Ljava/lang/Object;
+Ljava/io/ObjectStreamClass;->newInstance()Ljava/lang/Object;
+Ljava/lang/Class;->dexCache:Ljava/lang/Object;
+Ljava/lang/Class;->dexClassDefIndex:I
+Ljava/lang/ClassLoader;->parent:Ljava/lang/ClassLoader;
+Ljava/lang/Daemons$Daemon;->stop()V
+Ljava/lang/Daemons$FinalizerDaemon;->finalizingObject:Ljava/lang/Object;
+Ljava/lang/Daemons$FinalizerDaemon;->INSTANCE:Ljava/lang/Daemons$FinalizerDaemon;
+Ljava/lang/Daemons$FinalizerWatchdogDaemon;->INSTANCE:Ljava/lang/Daemons$FinalizerWatchdogDaemon;
+Ljava/lang/Runtime;->loadLibrary(Ljava/lang/String;Ljava/lang/ClassLoader;)V
+Ljava/lang/Runtime;->load(Ljava/lang/String;Ljava/lang/ClassLoader;)V
+Ljava/lang/Runtime;->nativeLoad(Ljava/lang/String;Ljava/lang/ClassLoader;)Ljava/lang/String;
+Ljava/lang/ThreadGroup;->parent:Ljava/lang/ThreadGroup;
+Ljava/lang/ThreadGroup;->systemThreadGroup:Ljava/lang/ThreadGroup;
+Ljava/lang/Thread;->inheritableThreadLocals:Ljava/lang/ThreadLocal$ThreadLocalMap;
+Ljava/lang/Throwable;->detailMessage:Ljava/lang/String;
+Ljava/net/Authenticator;->theAuthenticator:Ljava/net/Authenticator;
+Ljava/net/DatagramSocket;->impl:Ljava/net/DatagramSocketImpl;
+Ljava/net/InetAddress;->clearDnsCache()V
+Ljava/net/InetAddress;->isNumeric(Ljava/lang/String;)Z
+Ljava/net/InetAddress;->parseNumericAddress(Ljava/lang/String;)Ljava/net/InetAddress;
+Ljava/net/Socket;->impl:Ljava/net/SocketImpl;
+Ljava/net/URI;->host:Ljava/lang/String;
+Ljava/nio/charset/CharsetEncoder;->canEncode(Ljava/nio/CharBuffer;)Z
+Ljava/util/ArrayList$SubList;->parent:Ljava/util/AbstractList;
+Ljava/util/ArrayList$SubList;->parentOffset:I
+Ljava/util/ArrayList$SubList;->size:I
+Ljava/util/Arrays$ArrayList;->a:[Ljava/lang/Object;
+Ljava/util/Calendar;->zone:Ljava/util/TimeZone;
+Ljava/util/concurrent/FutureTask;->callable:Ljava/util/concurrent/Callable;
+Ljava/util/Locale;->createConstant(Ljava/lang/String;Ljava/lang/String;)Ljava/util/Locale;
+Ljavax/net/ssl/SSLServerSocketFactory;->defaultServerSocketFactory:Ljavax/net/ssl/SSLServerSocketFactory;
+Ljavax/net/ssl/SSLSocketFactory;->defaultSocketFactory:Ljavax/net/ssl/SSLSocketFactory;
+Lorg/json/JSONArray;->values:Ljava/util/List;
+Lsun/misc/Unsafe;->theUnsafe:Lsun/misc/Unsafe;
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 7bfb20f..fdb0ac9 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -7143,7 +7143,10 @@
boolean isApiWarningEnabled = SystemProperties.getInt("ro.art.hiddenapi.warning", 0) == 1;
if (isAppDebuggable || isApiWarningEnabled) {
- if (VMRuntime.getRuntime().hasUsedHiddenApi()) {
+ if (!mMainThread.mHiddenApiWarningShown && VMRuntime.getRuntime().hasUsedHiddenApi()) {
+ // Only show the warning once per process.
+ mMainThread.mHiddenApiWarningShown = true;
+
String appName = getApplicationInfo().loadLabel(getPackageManager())
.toString();
String warning = "Detected problems with API compatiblity\n"
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index e8535cd1..29e091b 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -291,6 +291,7 @@
boolean mJitEnabled = false;
boolean mSomeActivitiesChanged = false;
boolean mUpdatingSystemConfig = false;
+ /* package */ boolean mHiddenApiWarningShown = false;
// These can be accessed by multiple threads; mResourcesManager is the lock.
// XXX For now we keep around information about all packages we have
diff --git a/core/java/android/app/EphemeralResolverService.java b/core/java/android/app/EphemeralResolverService.java
deleted file mode 100644
index 427a0386..0000000
--- a/core/java/android/app/EphemeralResolverService.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.app;
-
-import android.annotation.SystemApi;
-import android.app.Service;
-import android.app.InstantAppResolverService.InstantAppResolutionCallback;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.EphemeralResolveInfo;
-import android.content.pm.InstantAppResolveInfo;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.IRemoteCallback;
-import android.os.Looper;
-import android.os.Message;
-import android.os.RemoteException;
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Base class for implementing the resolver service.
- * @hide
- * @removed
- * @deprecated use InstantAppResolverService instead
- */
-@Deprecated
-@SystemApi
-public abstract class EphemeralResolverService extends InstantAppResolverService {
- private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
- private static final String TAG = "PackageManager";
-
- /**
- * Called to retrieve resolve info for ephemeral applications.
- *
- * @param digestPrefix The hash prefix of the ephemeral's domain.
- * @param prefixMask A mask that was applied to each digest prefix. This should
- * be used when comparing against the digest prefixes as all bits might
- * not be set.
- * @deprecated use {@link #onGetEphemeralResolveInfo(int[])} instead
- */
- @Deprecated
- public abstract List<EphemeralResolveInfo> onEphemeralResolveInfoList(
- int digestPrefix[], int prefix);
-
- /**
- * Called to retrieve resolve info for ephemeral applications.
- *
- * @param digestPrefix The hash prefix of the ephemeral's domain.
- */
- public List<EphemeralResolveInfo> onGetEphemeralResolveInfo(int digestPrefix[]) {
- return onEphemeralResolveInfoList(digestPrefix, 0xFFFFF000);
- }
-
- /**
- * Called to retrieve intent filters for ephemeral applications.
- *
- * @param hostName The name of the host to get intent filters for.
- */
- public EphemeralResolveInfo onGetEphemeralIntentFilter(String hostName) {
- throw new IllegalStateException("Must define");
- }
-
- @Override
- public Looper getLooper() {
- return super.getLooper();
- }
-
- @Override
- void _onGetInstantAppResolveInfo(int[] digestPrefix, String token,
- InstantAppResolutionCallback callback) {
- if (DEBUG_EPHEMERAL) {
- Log.d(TAG, "Legacy resolver; getInstantAppResolveInfo;"
- + " prefix: " + Arrays.toString(digestPrefix));
- }
- final List<EphemeralResolveInfo> response = onGetEphemeralResolveInfo(digestPrefix);
- final int responseSize = response == null ? 0 : response.size();
- final List<InstantAppResolveInfo> resultList = new ArrayList<>(responseSize);
- for (int i = 0; i < responseSize; i++) {
- resultList.add(response.get(i).getInstantAppResolveInfo());
- }
- callback.onInstantAppResolveInfo(resultList);
- }
-
- @Override
- void _onGetInstantAppIntentFilter(int[] digestPrefix, String token,
- String hostName, InstantAppResolutionCallback callback) {
- if (DEBUG_EPHEMERAL) {
- Log.d(TAG, "Legacy resolver; getInstantAppIntentFilter;"
- + " prefix: " + Arrays.toString(digestPrefix));
- }
- final EphemeralResolveInfo response = onGetEphemeralIntentFilter(hostName);
- final List<InstantAppResolveInfo> resultList = new ArrayList<>(1);
- resultList.add(response.getInstantAppResolveInfo());
- callback.onInstantAppResolveInfo(resultList);
- }
-}
diff --git a/core/java/android/app/IInstantAppResolver.aidl b/core/java/android/app/IInstantAppResolver.aidl
index 805d8c0..ae20057 100644
--- a/core/java/android/app/IInstantAppResolver.aidl
+++ b/core/java/android/app/IInstantAppResolver.aidl
@@ -16,13 +16,15 @@
package android.app;
+import android.content.Intent;
import android.os.IRemoteCallback;
/** @hide */
oneway interface IInstantAppResolver {
- void getInstantAppResolveInfoList(in int[] digestPrefix,
+ void getInstantAppResolveInfoList(in Intent sanitizedIntent, in int[] hostDigestPrefix,
String token, int sequence, IRemoteCallback callback);
- void getInstantAppIntentFilterList(in int[] digestPrefix,
- String token, String hostName, IRemoteCallback callback);
+ void getInstantAppIntentFilterList(in Intent sanitizedIntent, in int[] hostDigestPrefix,
+ String token, IRemoteCallback callback);
+
}
diff --git a/core/java/android/app/InstantAppResolverService.java b/core/java/android/app/InstantAppResolverService.java
index c5dc86c..76a3682 100644
--- a/core/java/android/app/InstantAppResolverService.java
+++ b/core/java/android/app/InstantAppResolverService.java
@@ -17,7 +17,6 @@
package android.app;
import android.annotation.SystemApi;
-import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.InstantAppResolveInfo;
@@ -35,6 +34,7 @@
import com.android.internal.os.SomeArgs;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
/**
@@ -43,7 +43,7 @@
*/
@SystemApi
public abstract class InstantAppResolverService extends Service {
- private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
+ private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
private static final String TAG = "PackageManager";
/** @hide */
@@ -53,23 +53,65 @@
Handler mHandler;
/**
- * Called to retrieve resolve info for instant applications.
+ * Called to retrieve resolve info for instant applications immediately.
*
* @param digestPrefix The hash prefix of the instant app's domain.
+ * @deprecated should implement {@link #onGetInstantAppResolveInfo(Intent, int[], String,
+ * InstantAppResolutionCallback)}
*/
+ @Deprecated
public void onGetInstantAppResolveInfo(
int digestPrefix[], String token, InstantAppResolutionCallback callback) {
throw new IllegalStateException("Must define");
}
/**
- * Called to retrieve intent filters for instant applications.
+ * Called to retrieve intent filters for instant applications from potentially expensive
+ * sources.
*
* @param digestPrefix The hash prefix of the instant app's domain.
+ * @deprecated should implement {@link #onGetInstantAppIntentFilter(Intent, int[], String,
+ * InstantAppResolutionCallback)}
*/
+ @Deprecated
public void onGetInstantAppIntentFilter(
int digestPrefix[], String token, InstantAppResolutionCallback callback) {
- throw new IllegalStateException("Must define");
+ throw new IllegalStateException("Must define onGetInstantAppIntentFilter");
+ }
+
+ /**
+ * Called to retrieve resolve info for instant applications immediately.
+ *
+ * @param sanitizedIntent The sanitized {@link Intent} used for resolution.
+ * @param hostDigestPrefix The hash prefix of the instant app's domain.
+ */
+ public void onGetInstantAppResolveInfo(Intent sanitizedIntent, int[] hostDigestPrefix,
+ String token, InstantAppResolutionCallback callback) {
+ // if not overridden, forward to old methods and filter out non-web intents
+ if (sanitizedIntent.isBrowsableWebIntent()) {
+ onGetInstantAppResolveInfo(hostDigestPrefix, token, callback);
+ } else {
+ callback.onInstantAppResolveInfo(Collections.emptyList());
+ }
+ }
+
+ /**
+ * Called to retrieve intent filters for instant applications from potentially expensive
+ * sources.
+ *
+ * @param sanitizedIntent The sanitized {@link Intent} used for resolution.
+ * @param hostDigestPrefix The hash prefix of the instant app's domain or null if no host is
+ * defined.
+ */
+ public void onGetInstantAppIntentFilter(Intent sanitizedIntent, int[] hostDigestPrefix,
+ String token, InstantAppResolutionCallback callback) {
+ Log.e(TAG, "New onGetInstantAppIntentFilter is not overridden");
+ // if not overridden, forward to old methods and filter out non-web intents
+ if (sanitizedIntent.isBrowsableWebIntent()) {
+ onGetInstantAppIntentFilter(hostDigestPrefix, token, callback);
+ } else {
+ callback.onInstantAppResolveInfo(Collections.emptyList());
+ }
}
/**
@@ -89,33 +131,33 @@
public final IBinder onBind(Intent intent) {
return new IInstantAppResolver.Stub() {
@Override
- public void getInstantAppResolveInfoList(
- int digestPrefix[], String token, int sequence, IRemoteCallback callback) {
- if (DEBUG_EPHEMERAL) {
+ public void getInstantAppResolveInfoList(Intent sanitizedIntent, int[] digestPrefix,
+ String token, int sequence, IRemoteCallback callback) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "[" + token + "] Phase1 called; posting");
}
final SomeArgs args = SomeArgs.obtain();
args.arg1 = callback;
args.arg2 = digestPrefix;
args.arg3 = token;
- mHandler.obtainMessage(
- ServiceHandler.MSG_GET_INSTANT_APP_RESOLVE_INFO, sequence, 0, args)
- .sendToTarget();
+ args.arg4 = sanitizedIntent;
+ mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_RESOLVE_INFO,
+ sequence, 0, args).sendToTarget();
}
@Override
- public void getInstantAppIntentFilterList(
- int digestPrefix[], String token, String hostName, IRemoteCallback callback) {
- if (DEBUG_EPHEMERAL) {
+ public void getInstantAppIntentFilterList(Intent sanitizedIntent,
+ int[] digestPrefix, String token, IRemoteCallback callback) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "[" + token + "] Phase2 called; posting");
}
final SomeArgs args = SomeArgs.obtain();
args.arg1 = callback;
args.arg2 = digestPrefix;
args.arg3 = token;
- args.arg4 = hostName;
- mHandler.obtainMessage(
- ServiceHandler.MSG_GET_INSTANT_APP_INTENT_FILTER, callback).sendToTarget();
+ args.arg4 = sanitizedIntent;
+ mHandler.obtainMessage(ServiceHandler.MSG_GET_INSTANT_APP_INTENT_FILTER,
+ callback).sendToTarget();
}
};
}
@@ -142,29 +184,9 @@
}
}
- @Deprecated
- void _onGetInstantAppResolveInfo(int[] digestPrefix, String token,
- InstantAppResolutionCallback callback) {
- if (DEBUG_EPHEMERAL) {
- Slog.d(TAG, "[" + token + "] Phase1 request;"
- + " prefix: " + Arrays.toString(digestPrefix));
- }
- onGetInstantAppResolveInfo(digestPrefix, token, callback);
- }
- @Deprecated
- void _onGetInstantAppIntentFilter(int digestPrefix[], String token, String hostName,
- InstantAppResolutionCallback callback) {
- if (DEBUG_EPHEMERAL) {
- Slog.d(TAG, "[" + token + "] Phase2 request;"
- + " prefix: " + Arrays.toString(digestPrefix));
- }
- onGetInstantAppIntentFilter(digestPrefix, token, callback);
- }
-
private final class ServiceHandler extends Handler {
public static final int MSG_GET_INSTANT_APP_RESOLVE_INFO = 1;
public static final int MSG_GET_INSTANT_APP_INTENT_FILTER = 2;
-
public ServiceHandler(Looper looper) {
super(looper, null /*callback*/, true /*async*/);
}
@@ -179,9 +201,13 @@
final IRemoteCallback callback = (IRemoteCallback) args.arg1;
final int[] digestPrefix = (int[]) args.arg2;
final String token = (String) args.arg3;
+ final Intent intent = (Intent) args.arg4;
final int sequence = message.arg1;
- _onGetInstantAppResolveInfo(
- digestPrefix, token,
+ if (DEBUG_INSTANT) {
+ Slog.d(TAG, "[" + token + "] Phase1 request;"
+ + " prefix: " + Arrays.toString(digestPrefix));
+ }
+ onGetInstantAppResolveInfo(intent, digestPrefix, token,
new InstantAppResolutionCallback(sequence, callback));
} break;
@@ -190,9 +216,12 @@
final IRemoteCallback callback = (IRemoteCallback) args.arg1;
final int[] digestPrefix = (int[]) args.arg2;
final String token = (String) args.arg3;
- final String hostName = (String) args.arg4;
- _onGetInstantAppIntentFilter(
- digestPrefix, token, hostName,
+ final Intent intent = (Intent) args.arg4;
+ if (DEBUG_INSTANT) {
+ Slog.d(TAG, "[" + token + "] Phase2 request;"
+ + " prefix: " + Arrays.toString(digestPrefix));
+ }
+ onGetInstantAppIntentFilter(intent, digestPrefix, token,
new InstantAppResolutionCallback(-1 /*sequence*/, callback));
} break;
diff --git a/core/java/android/app/WindowConfiguration.java b/core/java/android/app/WindowConfiguration.java
index 085fc79..46566e7 100644
--- a/core/java/android/app/WindowConfiguration.java
+++ b/core/java/android/app/WindowConfiguration.java
@@ -146,6 +146,9 @@
})
public @interface WindowConfig {}
+ /** @hide */
+ public static final int PINNED_WINDOWING_MODE_ELEVATION_IN_DIP = 5;
+
public WindowConfiguration() {
unset();
}
diff --git a/core/java/android/app/slice/SliceManager.java b/core/java/android/app/slice/SliceManager.java
index 2fa9d8e..e5f3eae 100644
--- a/core/java/android/app/slice/SliceManager.java
+++ b/core/java/android/app/slice/SliceManager.java
@@ -314,6 +314,59 @@
}
/**
+ * Turns a slice intent into a slice uri. Expects an explicit intent. If there is no
+ * {@link android.content.ContentProvider} associated with the given intent this will throw
+ * {@link IllegalArgumentException}.
+ *
+ * @param intent The intent associated with a slice.
+ * @return The Slice Uri provided by the app or null if none is given.
+ * @see Slice
+ * @see SliceProvider#onMapIntentToUri(Intent)
+ * @see Intent
+ */
+ public @Nullable Uri mapIntentToUri(@NonNull Intent intent) {
+ Preconditions.checkNotNull(intent, "intent");
+ Preconditions.checkArgument(intent.getComponent() != null || intent.getPackage() != null,
+ "Slice intent must be explicit %s", intent);
+ ContentResolver resolver = mContext.getContentResolver();
+
+ // Check if the intent has data for the slice uri on it and use that
+ final Uri intentData = intent.getData();
+ if (intentData != null && SliceProvider.SLICE_TYPE.equals(resolver.getType(intentData))) {
+ return intentData;
+ }
+ // Otherwise ask the app
+ List<ResolveInfo> providers =
+ mContext.getPackageManager().queryIntentContentProviders(intent, 0);
+ if (providers == null || providers.isEmpty()) {
+ throw new IllegalArgumentException("Unable to resolve intent " + intent);
+ }
+ String authority = providers.get(0).providerInfo.authority;
+ Uri uri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT)
+ .authority(authority).build();
+ IContentProvider provider = resolver.acquireProvider(uri);
+ if (provider == null) {
+ throw new IllegalArgumentException("Unknown URI " + uri);
+ }
+ try {
+ Bundle extras = new Bundle();
+ extras.putParcelable(SliceProvider.EXTRA_INTENT, intent);
+ final Bundle res = provider.call(mContext.getPackageName(),
+ SliceProvider.METHOD_MAP_ONLY_INTENT, null, extras);
+ if (res == null) {
+ return null;
+ }
+ return res.getParcelable(SliceProvider.EXTRA_SLICE);
+ } catch (RemoteException e) {
+ // Arbitrary and not worth documenting, as Activity
+ // Manager will kill this process shortly anyway.
+ return null;
+ } finally {
+ resolver.releaseProvider(provider);
+ }
+ }
+
+ /**
* Turns a slice intent into slice content. Expects an explicit intent. If there is no
* {@link android.content.ContentProvider} associated with the given intent this will throw
* {@link IllegalArgumentException}.
@@ -329,7 +382,7 @@
@NonNull List<SliceSpec> supportedSpecs) {
Preconditions.checkNotNull(intent, "intent");
Preconditions.checkArgument(intent.getComponent() != null || intent.getPackage() != null,
- "Slice intent must be explicit " + intent);
+ "Slice intent must be explicit %s", intent);
ContentResolver resolver = mContext.getContentResolver();
// Check if the intent has data for the slice uri on it and use that
@@ -340,7 +393,7 @@
// Otherwise ask the app
List<ResolveInfo> providers =
mContext.getPackageManager().queryIntentContentProviders(intent, 0);
- if (providers == null) {
+ if (providers == null || providers.isEmpty()) {
throw new IllegalArgumentException("Unable to resolve intent " + intent);
}
String authority = providers.get(0).providerInfo.authority;
diff --git a/core/java/android/app/slice/SliceProvider.java b/core/java/android/app/slice/SliceProvider.java
index 336bd47..af43032 100644
--- a/core/java/android/app/slice/SliceProvider.java
+++ b/core/java/android/app/slice/SliceProvider.java
@@ -114,6 +114,10 @@
/**
* @hide
*/
+ public static final String METHOD_MAP_ONLY_INTENT = "map_only";
+ /**
+ * @hide
+ */
public static final String METHOD_PIN = "pin";
/**
* @hide
@@ -341,6 +345,13 @@
b.putParcelable(EXTRA_SLICE, null);
}
return b;
+ } else if (method.equals(METHOD_MAP_ONLY_INTENT)) {
+ Intent intent = extras.getParcelable(EXTRA_INTENT);
+ if (intent == null) return null;
+ Uri uri = onMapIntentToUri(intent);
+ Bundle b = new Bundle();
+ b.putParcelable(EXTRA_SLICE, uri);
+ return b;
} else if (method.equals(METHOD_PIN)) {
Uri uri = getUriWithoutUserId(extras.getParcelable(EXTRA_BIND_URI));
if (Binder.getCallingUid() != Process.SYSTEM_UID) {
diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java
index e02a294..9b62f19 100644
--- a/core/java/android/content/Intent.java
+++ b/core/java/android/content/Intent.java
@@ -50,6 +50,7 @@
import android.provider.DocumentsProvider;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
+import android.text.TextUtils;
import android.util.ArraySet;
import android.util.AttributeSet;
import android.util.Log;
@@ -1553,16 +1554,6 @@
public static final String ACTION_INSTALL_FAILURE = "android.intent.action.INSTALL_FAILURE";
/**
- * @hide
- * @removed
- * @deprecated Do not use. This will go away.
- * Replace with {@link #ACTION_INSTALL_INSTANT_APP_PACKAGE}.
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_INSTALL_EPHEMERAL_PACKAGE
- = "android.intent.action.INSTALL_EPHEMERAL_PACKAGE";
- /**
* Activity Action: Launch instant application installer.
* <p class="note">
* This is a protected intent that can only be sent by the system.
@@ -1576,16 +1567,6 @@
= "android.intent.action.INSTALL_INSTANT_APP_PACKAGE";
/**
- * @hide
- * @removed
- * @deprecated Do not use. This will go away.
- * Replace with {@link #ACTION_RESOLVE_INSTANT_APP_PACKAGE}.
- */
- @SystemApi
- @SdkConstant(SdkConstantType.SERVICE_ACTION)
- public static final String ACTION_RESOLVE_EPHEMERAL_PACKAGE
- = "android.intent.action.RESOLVE_EPHEMERAL_PACKAGE";
- /**
* Service Action: Resolve instant application.
* <p>
* The system will have a persistent connection to this service.
@@ -1600,16 +1581,6 @@
= "android.intent.action.RESOLVE_INSTANT_APP_PACKAGE";
/**
- * @hide
- * @removed
- * @deprecated Do not use. This will go away.
- * Replace with {@link #ACTION_INSTANT_APP_RESOLVER_SETTINGS}.
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_EPHEMERAL_RESOLVER_SETTINGS
- = "android.intent.action.EPHEMERAL_RESOLVER_SETTINGS";
- /**
* Activity Action: Launch instant app settings.
*
* <p class="note">
@@ -4443,45 +4414,109 @@
/**
* A {@link IntentSender} to start after ephemeral installation success.
+ * @deprecated Use {@link #EXTRA_INSTANT_APP_SUCCESS).
+ * @removed
* @hide
*/
+ @Deprecated
public static final String EXTRA_EPHEMERAL_SUCCESS = "android.intent.extra.EPHEMERAL_SUCCESS";
/**
- * A {@link IntentSender} to start after ephemeral installation failure.
+ * A {@link IntentSender} to start after instant app installation success.
* @hide
*/
+ @SystemApi
+ public static final String EXTRA_INSTANT_APP_SUCCESS =
+ "android.intent.extra.INSTANT_APP_SUCCESS";
+
+ /**
+ * A {@link IntentSender} to start after ephemeral installation failure.
+ * @deprecated Use {@link #EXTRA_INSTANT_APP_FAILURE).
+ * @removed
+ * @hide
+ */
+ @Deprecated
public static final String EXTRA_EPHEMERAL_FAILURE = "android.intent.extra.EPHEMERAL_FAILURE";
/**
- * The host name that triggered an ephemeral resolution.
+ * A {@link IntentSender} to start after instant app installation failure.
* @hide
*/
+ @SystemApi
+ public static final String EXTRA_INSTANT_APP_FAILURE =
+ "android.intent.extra.INSTANT_APP_FAILURE";
+
+ /**
+ * The host name that triggered an ephemeral resolution.
+ * @deprecated Use {@link #EXTRA_INSTANT_APP_HOSTNAME).
+ * @removed
+ * @hide
+ */
+ @Deprecated
public static final String EXTRA_EPHEMERAL_HOSTNAME = "android.intent.extra.EPHEMERAL_HOSTNAME";
/**
- * An opaque token to track ephemeral resolution.
+ * The host name that triggered an instant app resolution.
* @hide
*/
+ @SystemApi
+ public static final String EXTRA_INSTANT_APP_HOSTNAME =
+ "android.intent.extra.INSTANT_APP_HOSTNAME";
+
+ /**
+ * An opaque token to track ephemeral resolution.
+ * @deprecated Use {@link #EXTRA_INSTANT_APP_TOKEN).
+ * @removed
+ * @hide
+ */
+ @Deprecated
public static final String EXTRA_EPHEMERAL_TOKEN = "android.intent.extra.EPHEMERAL_TOKEN";
/**
+ * An opaque token to track instant app resolution.
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_INSTANT_APP_TOKEN =
+ "android.intent.extra.INSTANT_APP_TOKEN";
+
+ /**
* The action that triggered an instant application resolution.
* @hide
*/
+ @SystemApi
public static final String EXTRA_INSTANT_APP_ACTION = "android.intent.extra.INSTANT_APP_ACTION";
/**
- * A {@link Bundle} of metadata that describes the instanta application that needs to be
+ * An array of {@link Bundle}s containing details about resolved instant apps..
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_INSTANT_APP_BUNDLES =
+ "android.intent.extra.INSTANT_APP_BUNDLES";
+
+ /**
+ * A {@link Bundle} of metadata that describes the instant application that needs to be
* installed. This data is populated from the response to
* {@link android.content.pm.InstantAppResolveInfo#getExtras()} as provided by the registered
* instant application resolver.
* @hide
*/
+ @SystemApi
public static final String EXTRA_INSTANT_APP_EXTRAS =
"android.intent.extra.INSTANT_APP_EXTRAS";
/**
+ * A boolean value indicating that the instant app resolver was unable to state with certainty
+ * that it did or did not have an app for the sanitized {@link Intent} defined at
+ * {@link #EXTRA_INTENT}.
+ * @hide
+ */
+ @SystemApi
+ public static final String EXTRA_UNKNOWN_INSTANT_APP =
+ "android.intent.extra.UNKNOWN_INSTANT_APP";
+
+ /**
* The version code of the app to install components from.
* @deprecated Use {@link #EXTRA_LONG_VERSION_CODE).
* @hide
@@ -4493,12 +4528,14 @@
* The version code of the app to install components from.
* @hide
*/
+ @SystemApi
public static final String EXTRA_LONG_VERSION_CODE = "android.intent.extra.LONG_VERSION_CODE";
/**
- * The app that triggered the ephemeral installation.
+ * The app that triggered the instant app installation.
* @hide
*/
+ @SystemApi
public static final String EXTRA_CALLING_PACKAGE
= "android.intent.extra.CALLING_PACKAGE";
@@ -4507,6 +4544,7 @@
* installer may use.
* @hide
*/
+ @SystemApi
public static final String EXTRA_VERIFICATION_BUNDLE
= "android.intent.extra.VERIFICATION_BUNDLE";
@@ -5029,6 +5067,7 @@
FLAG_GRANT_PREFIX_URI_PERMISSION,
FLAG_DEBUG_TRIAGED_MISSING,
FLAG_IGNORE_EPHEMERAL,
+ FLAG_ACTIVITY_MATCH_EXTERNAL,
FLAG_ACTIVITY_NO_HISTORY,
FLAG_ACTIVITY_SINGLE_TOP,
FLAG_ACTIVITY_NEW_TASK,
@@ -5072,6 +5111,7 @@
FLAG_INCLUDE_STOPPED_PACKAGES,
FLAG_DEBUG_TRIAGED_MISSING,
FLAG_IGNORE_EPHEMERAL,
+ FLAG_ACTIVITY_MATCH_EXTERNAL,
FLAG_ACTIVITY_NO_HISTORY,
FLAG_ACTIVITY_SINGLE_TOP,
FLAG_ACTIVITY_NEW_TASK,
@@ -5475,6 +5515,14 @@
*/
public static final int FLAG_ACTIVITY_LAUNCH_ADJACENT = 0x00001000;
+
+ /**
+ * If set, resolution of this intent may take place via an instant app not
+ * yet on the device if there does not yet exist an app on device to
+ * resolve it.
+ */
+ public static final int FLAG_ACTIVITY_MATCH_EXTERNAL = 0x00000800;
+
/**
* If set, when sending a broadcast only registered receivers will be
* called -- no BroadcastReceiver components will be launched.
@@ -10028,6 +10076,25 @@
}
}
+ /** @hide */
+ public boolean hasWebURI() {
+ if (getData() == null) {
+ return false;
+ }
+ final String scheme = getScheme();
+ if (TextUtils.isEmpty(scheme)) {
+ return false;
+ }
+ return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
+ }
+
+ /** @hide */
+ public boolean isBrowsableWebIntent() {
+ return ACTION_VIEW.equals(mAction)
+ && hasCategory(CATEGORY_BROWSABLE)
+ && hasWebURI();
+ }
+
/**
* @hide
*/
diff --git a/core/java/android/content/pm/ApplicationInfo.java b/core/java/android/content/pm/ApplicationInfo.java
index f6697e8..b61a6d9 100644
--- a/core/java/android/content/pm/ApplicationInfo.java
+++ b/core/java/android/content/pm/ApplicationInfo.java
@@ -958,6 +958,7 @@
* Version of the sandbox the application wants to run in.
* @hide
*/
+ @SystemApi
public int targetSandboxVersion;
/**
@@ -1600,7 +1601,7 @@
* @hide
*/
public boolean isAllowedToUseHiddenApi() {
- return isSystemApp();
+ return false;
}
/**
@@ -1655,7 +1656,11 @@
return (privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
}
- /** @hide */
+ /**
+ * True if the application is installed as an instant app.
+ * @hide
+ */
+ @SystemApi
public boolean isInstantApp() {
return (privateFlags & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
}
diff --git a/core/java/android/content/pm/AuxiliaryResolveInfo.java b/core/java/android/content/pm/AuxiliaryResolveInfo.java
index 6bdcefb..202df50 100644
--- a/core/java/android/content/pm/AuxiliaryResolveInfo.java
+++ b/core/java/android/content/pm/AuxiliaryResolveInfo.java
@@ -21,6 +21,10 @@
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
+import android.os.Bundle;
+
+import java.util.Collections;
+import java.util.List;
/**
* Auxiliary application resolution response.
@@ -31,56 +35,95 @@
* hasn't been installed.
* @hide
*/
-public final class AuxiliaryResolveInfo extends IntentFilter {
- /** Resolved information returned from the external instant resolver */
- public final InstantAppResolveInfo resolveInfo;
- /** The resolved package. Copied from {@link #resolveInfo}. */
- public final String packageName;
+public final class AuxiliaryResolveInfo {
/** The activity to launch if there's an installation failure. */
public final ComponentName installFailureActivity;
- /** The resolve split. Copied from the matched filter in {@link #resolveInfo}. */
- public final String splitName;
/** Whether or not instant resolution needs the second phase */
public final boolean needsPhaseTwo;
/** Opaque token to track the instant application resolution */
public final String token;
- /** The version code of the package */
- public final long versionCode;
/** An intent to start upon failure to install */
public final Intent failureIntent;
+ /** The matching filters for this resolve info. */
+ public final List<AuxiliaryFilter> filters;
/** Create a response for installing an instant application. */
- public AuxiliaryResolveInfo(@NonNull InstantAppResolveInfo resolveInfo,
- @NonNull IntentFilter orig,
- @Nullable String splitName,
- @NonNull String token,
+ public AuxiliaryResolveInfo(@NonNull String token,
boolean needsPhase2,
- @Nullable Intent failureIntent) {
- super(orig);
- this.resolveInfo = resolveInfo;
- this.packageName = resolveInfo.getPackageName();
- this.splitName = splitName;
+ @Nullable Intent failureIntent,
+ @Nullable List<AuxiliaryFilter> filters) {
this.token = token;
this.needsPhaseTwo = needsPhase2;
- this.versionCode = resolveInfo.getVersionCode();
this.failureIntent = failureIntent;
+ this.filters = filters;
this.installFailureActivity = null;
}
/** Create a response for installing a split on demand. */
- public AuxiliaryResolveInfo(@NonNull String packageName,
- @Nullable String splitName,
- @Nullable ComponentName failureActivity,
- long versionCode,
- @Nullable Intent failureIntent) {
+ public AuxiliaryResolveInfo(@Nullable ComponentName failureActivity,
+ @Nullable Intent failureIntent,
+ @Nullable List<AuxiliaryFilter> filters) {
super();
- this.packageName = packageName;
this.installFailureActivity = failureActivity;
- this.splitName = splitName;
- this.versionCode = versionCode;
- this.resolveInfo = null;
+ this.filters = filters;
this.token = null;
this.needsPhaseTwo = false;
this.failureIntent = failureIntent;
}
+
+ /** Create a response for installing a split on demand. */
+ public AuxiliaryResolveInfo(@Nullable ComponentName failureActivity,
+ String packageName, long versionCode, String splitName) {
+ this(failureActivity, null, Collections.singletonList(
+ new AuxiliaryResolveInfo.AuxiliaryFilter(packageName, versionCode, splitName)));
+ }
+
+ /** @hide */
+ public static final class AuxiliaryFilter extends IntentFilter {
+ /** Resolved information returned from the external instant resolver */
+ public final InstantAppResolveInfo resolveInfo;
+ /** The resolved package. Copied from {@link #resolveInfo}. */
+ public final String packageName;
+ /** The version code of the package */
+ public final long versionCode;
+ /** The resolve split. Copied from the matched filter in {@link #resolveInfo}. */
+ public final String splitName;
+ /** The extras to pass on to the installer for this filter. */
+ public final Bundle extras;
+
+ public AuxiliaryFilter(IntentFilter orig, InstantAppResolveInfo resolveInfo,
+ String splitName, Bundle extras) {
+ super(orig);
+ this.resolveInfo = resolveInfo;
+ this.packageName = resolveInfo.getPackageName();
+ this.versionCode = resolveInfo.getLongVersionCode();
+ this.splitName = splitName;
+ this.extras = extras;
+ }
+
+ public AuxiliaryFilter(InstantAppResolveInfo resolveInfo,
+ String splitName, Bundle extras) {
+ this.resolveInfo = resolveInfo;
+ this.packageName = resolveInfo.getPackageName();
+ this.versionCode = resolveInfo.getLongVersionCode();
+ this.splitName = splitName;
+ this.extras = extras;
+ }
+
+ public AuxiliaryFilter(String packageName, long versionCode, String splitName) {
+ this.resolveInfo = null;
+ this.packageName = packageName;
+ this.versionCode = versionCode;
+ this.splitName = splitName;
+ this.extras = null;
+ }
+
+ @Override
+ public String toString() {
+ return "AuxiliaryFilter{"
+ + "packageName='" + packageName + '\''
+ + ", versionCode=" + versionCode
+ + ", splitName='" + splitName + '\'' + '}';
+ }
+ }
}
\ No newline at end of file
diff --git a/core/java/android/content/pm/EphemeralIntentFilter.java b/core/java/android/content/pm/EphemeralIntentFilter.java
deleted file mode 100644
index 1dbbf81..0000000
--- a/core/java/android/content/pm/EphemeralIntentFilter.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.pm;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.content.IntentFilter;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Information about an ephemeral application intent filter.
- * @hide
- * @removed
- */
-@Deprecated
-@SystemApi
-public final class EphemeralIntentFilter implements Parcelable {
- private final InstantAppIntentFilter mInstantAppIntentFilter;
-
- public EphemeralIntentFilter(@Nullable String splitName, @NonNull List<IntentFilter> filters) {
- mInstantAppIntentFilter = new InstantAppIntentFilter(splitName, filters);
- }
-
- EphemeralIntentFilter(@NonNull InstantAppIntentFilter intentFilter) {
- mInstantAppIntentFilter = intentFilter;
- }
-
- EphemeralIntentFilter(Parcel in) {
- mInstantAppIntentFilter = in.readParcelable(null /*loader*/);
- }
-
- public String getSplitName() {
- return mInstantAppIntentFilter.getSplitName();
- }
-
- public List<IntentFilter> getFilters() {
- return mInstantAppIntentFilter.getFilters();
- }
-
- /** @hide */
- InstantAppIntentFilter getInstantAppIntentFilter() {
- return mInstantAppIntentFilter;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel out, int flags) {
- out.writeParcelable(mInstantAppIntentFilter, flags);
- }
-
- public static final Parcelable.Creator<EphemeralIntentFilter> CREATOR
- = new Parcelable.Creator<EphemeralIntentFilter>() {
- @Override
- public EphemeralIntentFilter createFromParcel(Parcel in) {
- return new EphemeralIntentFilter(in);
- }
- @Override
- public EphemeralIntentFilter[] newArray(int size) {
- return new EphemeralIntentFilter[size];
- }
- };
-}
diff --git a/core/java/android/content/pm/EphemeralResolveInfo.java b/core/java/android/content/pm/EphemeralResolveInfo.java
deleted file mode 100644
index 12131a3..0000000
--- a/core/java/android/content/pm/EphemeralResolveInfo.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.content.pm;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.content.IntentFilter;
-import android.content.pm.InstantAppResolveInfo.InstantAppDigest;
-import android.net.Uri;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * Information about an ephemeral application.
- * @hide
- * @removed
- */
-@Deprecated
-@SystemApi
-public final class EphemeralResolveInfo implements Parcelable {
- /** Algorithm that will be used to generate the domain digest */
- public static final String SHA_ALGORITHM = "SHA-256";
-
- private final InstantAppResolveInfo mInstantAppResolveInfo;
- @Deprecated
- private final List<IntentFilter> mLegacyFilters;
-
- @Deprecated
- public EphemeralResolveInfo(@NonNull Uri uri, @NonNull String packageName,
- @NonNull List<IntentFilter> filters) {
- if (uri == null || packageName == null || filters == null || filters.isEmpty()) {
- throw new IllegalArgumentException();
- }
- final List<EphemeralIntentFilter> ephemeralFilters = new ArrayList<>(1);
- ephemeralFilters.add(new EphemeralIntentFilter(packageName, filters));
- mInstantAppResolveInfo = new InstantAppResolveInfo(uri.getHost(), packageName,
- createInstantAppIntentFilterList(ephemeralFilters));
- mLegacyFilters = new ArrayList<IntentFilter>(filters.size());
- mLegacyFilters.addAll(filters);
- }
-
- @Deprecated
- public EphemeralResolveInfo(@NonNull EphemeralDigest digest, @Nullable String packageName,
- @Nullable List<EphemeralIntentFilter> filters) {
- this(digest, packageName, filters, -1 /*versionCode*/);
- }
-
- public EphemeralResolveInfo(@NonNull EphemeralDigest digest, @Nullable String packageName,
- @Nullable List<EphemeralIntentFilter> filters, int versionCode) {
- mInstantAppResolveInfo = new InstantAppResolveInfo(
- digest.getInstantAppDigest(), packageName,
- createInstantAppIntentFilterList(filters), versionCode);
- mLegacyFilters = null;
- }
-
- public EphemeralResolveInfo(@NonNull String hostName, @Nullable String packageName,
- @Nullable List<EphemeralIntentFilter> filters) {
- this(new EphemeralDigest(hostName), packageName, filters);
- }
-
- EphemeralResolveInfo(Parcel in) {
- mInstantAppResolveInfo = in.readParcelable(null /*loader*/);
- mLegacyFilters = new ArrayList<IntentFilter>();
- in.readList(mLegacyFilters, null /*loader*/);
- }
-
- /** @hide */
- public InstantAppResolveInfo getInstantAppResolveInfo() {
- return mInstantAppResolveInfo;
- }
-
- private static List<InstantAppIntentFilter> createInstantAppIntentFilterList(
- List<EphemeralIntentFilter> filters) {
- if (filters == null) {
- return null;
- }
- final int filterCount = filters.size();
- final List<InstantAppIntentFilter> returnList = new ArrayList<>(filterCount);
- for (int i = 0; i < filterCount; i++) {
- returnList.add(filters.get(i).getInstantAppIntentFilter());
- }
- return returnList;
- }
-
- public byte[] getDigestBytes() {
- return mInstantAppResolveInfo.getDigestBytes();
- }
-
- public int getDigestPrefix() {
- return mInstantAppResolveInfo.getDigestPrefix();
- }
-
- public String getPackageName() {
- return mInstantAppResolveInfo.getPackageName();
- }
-
- public List<EphemeralIntentFilter> getIntentFilters() {
- final List<InstantAppIntentFilter> filters = mInstantAppResolveInfo.getIntentFilters();
- final int filterCount = filters.size();
- final List<EphemeralIntentFilter> returnList = new ArrayList<>(filterCount);
- for (int i = 0; i < filterCount; i++) {
- returnList.add(new EphemeralIntentFilter(filters.get(i)));
- }
- return returnList;
- }
-
- public int getVersionCode() {
- return mInstantAppResolveInfo.getVersionCode();
- }
-
- @Deprecated
- public List<IntentFilter> getFilters() {
- return mLegacyFilters;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel out, int flags) {
- out.writeParcelable(mInstantAppResolveInfo, flags);
- out.writeList(mLegacyFilters);
- }
-
- public static final Parcelable.Creator<EphemeralResolveInfo> CREATOR
- = new Parcelable.Creator<EphemeralResolveInfo>() {
- @Override
- public EphemeralResolveInfo createFromParcel(Parcel in) {
- return new EphemeralResolveInfo(in);
- }
- @Override
- public EphemeralResolveInfo[] newArray(int size) {
- return new EphemeralResolveInfo[size];
- }
- };
-
- /**
- * Helper class to generate and store each of the digests and prefixes
- * sent to the Ephemeral Resolver.
- * <p>
- * Since intent filters may want to handle multiple hosts within a
- * domain [eg “*.google.com”], the resolver is presented with multiple
- * hash prefixes. For example, "a.b.c.d.e" generates digests for
- * "d.e", "c.d.e", "b.c.d.e" and "a.b.c.d.e".
- *
- * @hide
- */
- @SystemApi
- public static final class EphemeralDigest implements Parcelable {
- private final InstantAppDigest mInstantAppDigest;
-
- public EphemeralDigest(@NonNull String hostName) {
- this(hostName, -1 /*maxDigests*/);
- }
-
- /** @hide */
- public EphemeralDigest(@NonNull String hostName, int maxDigests) {
- mInstantAppDigest = new InstantAppDigest(hostName, maxDigests);
- }
-
- EphemeralDigest(Parcel in) {
- mInstantAppDigest = in.readParcelable(null /*loader*/);
- }
-
- /** @hide */
- InstantAppDigest getInstantAppDigest() {
- return mInstantAppDigest;
- }
-
- public byte[][] getDigestBytes() {
- return mInstantAppDigest.getDigestBytes();
- }
-
- public int[] getDigestPrefix() {
- return mInstantAppDigest.getDigestPrefix();
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel out, int flags) {
- out.writeParcelable(mInstantAppDigest, flags);
- }
-
- @SuppressWarnings("hiding")
- public static final Parcelable.Creator<EphemeralDigest> CREATOR =
- new Parcelable.Creator<EphemeralDigest>() {
- @Override
- public EphemeralDigest createFromParcel(Parcel in) {
- return new EphemeralDigest(in);
- }
- @Override
- public EphemeralDigest[] newArray(int size) {
- return new EphemeralDigest[size];
- }
- };
- }
-}
diff --git a/core/java/android/content/pm/InstantAppResolveInfo.java b/core/java/android/content/pm/InstantAppResolveInfo.java
index 19cb932..112c5da 100644
--- a/core/java/android/content/pm/InstantAppResolveInfo.java
+++ b/core/java/android/content/pm/InstantAppResolveInfo.java
@@ -19,6 +19,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.SystemApi;
+import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
@@ -26,11 +27,35 @@
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
/**
- * Information about an instant application.
+ * Describes an externally resolvable instant application. There are three states that this class
+ * can represent: <p/>
+ * <ul>
+ * <li>
+ * The first, usable only for non http/s intents, implies that the resolver cannot
+ * immediately resolve this intent and would prefer that resolution be deferred to the
+ * instant app installer. Represent this state with {@link #InstantAppResolveInfo(Bundle)}.
+ * If the {@link android.content.Intent} has the scheme set to http/s and a set of digest
+ * prefixes were passed into one of the resolve methods in
+ * {@link android.app.InstantAppResolverService}, this state cannot be used.
+ * </li>
+ * <li>
+ * The second represents a partial match and is constructed with any of the other
+ * constructors. By setting one or more of the {@link Nullable}arguments to null, you
+ * communicate to the resolver in response to
+ * {@link android.app.InstantAppResolverService#onGetInstantAppResolveInfo(Intent, int[],
+ * String, InstantAppResolverService.InstantAppResolutionCallback)}
+ * that you need a 2nd round of resolution to complete the request.
+ * </li>
+ * <li>
+ * The third represents a complete match and is constructed with all @Nullable parameters
+ * populated.
+ * </li>
+ * </ul>
* @hide
*/
@SystemApi
@@ -38,6 +63,8 @@
/** Algorithm that will be used to generate the domain digest */
private static final String SHA_ALGORITHM = "SHA-256";
+ private static final byte[] EMPTY_DIGEST = new byte[0];
+
private final InstantAppDigest mDigest;
private final String mPackageName;
/** The filters used to match domain */
@@ -46,15 +73,30 @@
private final long mVersionCode;
/** Data about the app that should be passed along to the Instant App installer on resolve */
private final Bundle mExtras;
+ /**
+ * A flag that indicates that the resolver is aware that an app may match, but would prefer
+ * that the installer get the sanitized intent to decide. This should not be used for
+ * resolutions that include a host and will be ignored in such cases.
+ */
+ private final boolean mShouldLetInstallerDecide;
+ /** Constructor for intent-based InstantApp resolution results. */
public InstantAppResolveInfo(@NonNull InstantAppDigest digest, @Nullable String packageName,
@Nullable List<InstantAppIntentFilter> filters, int versionCode) {
this(digest, packageName, filters, (long) versionCode, null /* extras */);
}
+ /** Constructor for intent-based InstantApp resolution results with extras. */
public InstantAppResolveInfo(@NonNull InstantAppDigest digest, @Nullable String packageName,
@Nullable List<InstantAppIntentFilter> filters, long versionCode,
@Nullable Bundle extras) {
+ this(digest, packageName, filters, versionCode, extras, false);
+ }
+
+ /** Constructor for intent-based InstantApp resolution results with extras. */
+ private InstantAppResolveInfo(@NonNull InstantAppDigest digest, @Nullable String packageName,
+ @Nullable List<InstantAppIntentFilter> filters, long versionCode,
+ @Nullable Bundle extras, boolean shouldLetInstallerDecide) {
// validate arguments
if ((packageName == null && (filters != null && filters.size() != 0))
|| (packageName != null && (filters == null || filters.size() == 0))) {
@@ -62,7 +104,7 @@
}
mDigest = digest;
if (filters != null) {
- mFilters = new ArrayList<InstantAppIntentFilter>(filters.size());
+ mFilters = new ArrayList<>(filters.size());
mFilters.addAll(filters);
} else {
mFilters = null;
@@ -70,25 +112,48 @@
mPackageName = packageName;
mVersionCode = versionCode;
mExtras = extras;
+ mShouldLetInstallerDecide = shouldLetInstallerDecide;
}
+ /** Constructor for intent-based InstantApp resolution results by hostname. */
public InstantAppResolveInfo(@NonNull String hostName, @Nullable String packageName,
@Nullable List<InstantAppIntentFilter> filters) {
this(new InstantAppDigest(hostName), packageName, filters, -1 /*versionCode*/,
null /* extras */);
}
+ /**
+ * Constructor that creates a "let the installer decide" response with optional included
+ * extras.
+ */
+ public InstantAppResolveInfo(@Nullable Bundle extras) {
+ this(InstantAppDigest.UNDEFINED, null, null, -1, extras, true);
+ }
+
InstantAppResolveInfo(Parcel in) {
- mDigest = in.readParcelable(null /*loader*/);
- mPackageName = in.readString();
- mFilters = new ArrayList<InstantAppIntentFilter>();
- in.readList(mFilters, null /*loader*/);
- mVersionCode = in.readLong();
+ mShouldLetInstallerDecide = in.readBoolean();
mExtras = in.readBundle();
+ if (mShouldLetInstallerDecide) {
+ mDigest = InstantAppDigest.UNDEFINED;
+ mPackageName = null;
+ mFilters = Collections.emptyList();
+ mVersionCode = -1;
+ } else {
+ mDigest = in.readParcelable(null /*loader*/);
+ mPackageName = in.readString();
+ mFilters = new ArrayList<>();
+ in.readList(mFilters, null /*loader*/);
+ mVersionCode = in.readLong();
+ }
+ }
+
+ /** Returns true if the installer should be notified that it should query for packages. */
+ public boolean shouldLetInstallerDecide() {
+ return mShouldLetInstallerDecide;
}
public byte[] getDigestBytes() {
- return mDigest.getDigestBytes()[0];
+ return mDigest.mDigestBytes.length > 0 ? mDigest.getDigestBytes()[0] : EMPTY_DIGEST;
}
public int getDigestPrefix() {
@@ -127,11 +192,15 @@
@Override
public void writeToParcel(Parcel out, int flags) {
+ out.writeBoolean(mShouldLetInstallerDecide);
+ out.writeBundle(mExtras);
+ if (mShouldLetInstallerDecide) {
+ return;
+ }
out.writeParcelable(mDigest, flags);
out.writeString(mPackageName);
out.writeList(mFilters);
out.writeLong(mVersionCode);
- out.writeBundle(mExtras);
}
public static final Parcelable.Creator<InstantAppResolveInfo> CREATOR
@@ -159,7 +228,9 @@
@SystemApi
public static final class InstantAppDigest implements Parcelable {
private static final int DIGEST_MASK = 0xfffff000;
- private static final int DIGEST_PREFIX_COUNT = 5;
+
+ public static final InstantAppDigest UNDEFINED =
+ new InstantAppDigest(new byte[][]{}, new int[]{});
/** Full digest of the domain hashes */
private final byte[][] mDigestBytes;
/** The first 4 bytes of the domain hashes */
@@ -186,6 +257,11 @@
}
}
+ private InstantAppDigest(byte[][] digestBytes, int[] prefix) {
+ this.mDigestPrefix = prefix;
+ this.mDigestBytes = digestBytes;
+ }
+
private static byte[][] generateDigest(String hostName, int maxDigests) {
ArrayList<byte[]> digests = new ArrayList<>();
try {
diff --git a/core/java/android/hardware/display/AmbientBrightnessDayStats.aidl b/core/java/android/hardware/display/AmbientBrightnessDayStats.aidl
new file mode 100644
index 0000000..9070777
--- /dev/null
+++ b/core/java/android/hardware/display/AmbientBrightnessDayStats.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.display;
+
+parcelable AmbientBrightnessDayStats;
diff --git a/core/java/android/hardware/display/AmbientBrightnessDayStats.java b/core/java/android/hardware/display/AmbientBrightnessDayStats.java
new file mode 100644
index 0000000..41be397
--- /dev/null
+++ b/core/java/android/hardware/display/AmbientBrightnessDayStats.java
@@ -0,0 +1,196 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.display;
+
+import android.annotation.NonNull;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.android.internal.util.Preconditions;
+
+import java.time.LocalDate;
+import java.util.Arrays;
+
+/**
+ * AmbientBrightnessDayStats stores and manipulates brightness stats over a single day.
+ * {@see DisplayManager.getAmbientBrightnessStats()}
+ * TODO: Make this system API
+ *
+ * @hide
+ */
+public class AmbientBrightnessDayStats implements Parcelable {
+
+ /** The localdate for which brightness stats are being tracked */
+ private final LocalDate mLocalDate;
+
+ /** Ambient brightness values for creating bucket boundaries from */
+ private final float[] mBucketBoundaries;
+
+ /** Stats of how much time (in seconds) was spent in each of the buckets */
+ private final float[] mStats;
+
+ /**
+ * @hide
+ */
+ public AmbientBrightnessDayStats(@NonNull LocalDate localDate,
+ @NonNull float[] bucketBoundaries) {
+ Preconditions.checkNotNull(localDate);
+ Preconditions.checkNotNull(bucketBoundaries);
+ int numBuckets = bucketBoundaries.length;
+ if (numBuckets < 1) {
+ throw new IllegalArgumentException("Bucket boundaries must contain at least 1 value");
+ }
+ mLocalDate = localDate;
+ mBucketBoundaries = bucketBoundaries;
+ mStats = new float[numBuckets];
+ }
+
+ /**
+ * @hide
+ */
+ public AmbientBrightnessDayStats(@NonNull LocalDate localDate,
+ @NonNull float[] bucketBoundaries, @NonNull float[] stats) {
+ Preconditions.checkNotNull(localDate);
+ Preconditions.checkNotNull(bucketBoundaries);
+ Preconditions.checkNotNull(stats);
+ if (bucketBoundaries.length < 1) {
+ throw new IllegalArgumentException("Bucket boundaries must contain at least 1 value");
+ }
+ if (bucketBoundaries.length != stats.length) {
+ throw new IllegalArgumentException("Bucket boundaries and stats must be of same size.");
+ }
+ mLocalDate = localDate;
+ mBucketBoundaries = bucketBoundaries;
+ mStats = stats;
+ }
+
+ public LocalDate getLocalDate() {
+ return mLocalDate;
+ }
+
+ public float[] getStats() {
+ return mStats;
+ }
+
+ public float[] getBucketBoundaries() {
+ return mBucketBoundaries;
+ }
+
+ private AmbientBrightnessDayStats(Parcel source) {
+ mLocalDate = LocalDate.parse(source.readString());
+ mBucketBoundaries = source.createFloatArray();
+ mStats = source.createFloatArray();
+ }
+
+ public static final Creator<AmbientBrightnessDayStats> CREATOR =
+ new Creator<AmbientBrightnessDayStats>() {
+
+ @Override
+ public AmbientBrightnessDayStats createFromParcel(Parcel source) {
+ return new AmbientBrightnessDayStats(source);
+ }
+
+ @Override
+ public AmbientBrightnessDayStats[] newArray(int size) {
+ return new AmbientBrightnessDayStats[size];
+ }
+ };
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ AmbientBrightnessDayStats other = (AmbientBrightnessDayStats) obj;
+ return mLocalDate.equals(other.mLocalDate) && Arrays.equals(mBucketBoundaries,
+ other.mBucketBoundaries) && Arrays.equals(mStats, other.mStats);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = result * prime + mLocalDate.hashCode();
+ result = result * prime + Arrays.hashCode(mBucketBoundaries);
+ result = result * prime + Arrays.hashCode(mStats);
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder bucketBoundariesString = new StringBuilder();
+ StringBuilder statsString = new StringBuilder();
+ for (int i = 0; i < mBucketBoundaries.length; i++) {
+ if (i != 0) {
+ bucketBoundariesString.append(", ");
+ statsString.append(", ");
+ }
+ bucketBoundariesString.append(mBucketBoundaries[i]);
+ statsString.append(mStats[i]);
+ }
+ return new StringBuilder()
+ .append(mLocalDate).append(" ")
+ .append("{").append(bucketBoundariesString).append("} ")
+ .append("{").append(statsString).append("}").toString();
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeString(mLocalDate.toString());
+ dest.writeFloatArray(mBucketBoundaries);
+ dest.writeFloatArray(mStats);
+ }
+
+ /** @hide */
+ public void log(float ambientBrightness, float durationSec) {
+ int bucketIndex = getBucketIndex(ambientBrightness);
+ if (bucketIndex >= 0) {
+ mStats[bucketIndex] += durationSec;
+ }
+ }
+
+ private int getBucketIndex(float ambientBrightness) {
+ if (ambientBrightness < mBucketBoundaries[0]) {
+ return -1;
+ }
+ int low = 0;
+ int high = mBucketBoundaries.length - 1;
+ while (low < high) {
+ int mid = (low + high) / 2;
+ if (mBucketBoundaries[mid] <= ambientBrightness
+ && ambientBrightness < mBucketBoundaries[mid + 1]) {
+ return mid;
+ } else if (mBucketBoundaries[mid] < ambientBrightness) {
+ low = mid + 1;
+ } else if (mBucketBoundaries[mid] > ambientBrightness) {
+ high = mid - 1;
+ }
+ }
+ return low;
+ }
+}
diff --git a/core/java/android/hardware/display/BrightnessChangeEvent.java b/core/java/android/hardware/display/BrightnessChangeEvent.java
index 2301824..02eb28c 100644
--- a/core/java/android/hardware/display/BrightnessChangeEvent.java
+++ b/core/java/android/hardware/display/BrightnessChangeEvent.java
@@ -54,19 +54,30 @@
/** Most recent battery level when brightness was changed or Float.NaN */
public final float batteryLevel;
+ /** Factor applied to brightness due to battery level, 0.0-1.0 */
+ public final float powerBrightnessFactor;
+
/** Color filter active to provide night mode */
public final boolean nightMode;
/** If night mode color filter is active this will be the temperature in kelvin */
public final int colorTemperature;
- /** Brightness le vel before slider adjustment */
+ /** Brightness level before slider adjustment */
public final float lastBrightness;
+ /** Whether brightness configuration is default version */
+ public final boolean isDefaultBrightnessConfig;
+
+ /** Whether brightness curve includes a user brightness point */
+ public final boolean isUserSetBrightness;
+
+
/** @hide */
private BrightnessChangeEvent(float brightness, long timeStamp, String packageName,
int userId, float[] luxValues, long[] luxTimestamps, float batteryLevel,
- boolean nightMode, int colorTemperature, float lastBrightness) {
+ float powerBrightnessFactor, boolean nightMode, int colorTemperature,
+ float lastBrightness, boolean isDefaultBrightnessConfig, boolean isUserSetBrightness) {
this.brightness = brightness;
this.timeStamp = timeStamp;
this.packageName = packageName;
@@ -74,9 +85,12 @@
this.luxValues = luxValues;
this.luxTimestamps = luxTimestamps;
this.batteryLevel = batteryLevel;
+ this.powerBrightnessFactor = powerBrightnessFactor;
this.nightMode = nightMode;
this.colorTemperature = colorTemperature;
this.lastBrightness = lastBrightness;
+ this.isDefaultBrightnessConfig = isDefaultBrightnessConfig;
+ this.isUserSetBrightness = isUserSetBrightness;
}
/** @hide */
@@ -88,9 +102,12 @@
this.luxValues = other.luxValues;
this.luxTimestamps = other.luxTimestamps;
this.batteryLevel = other.batteryLevel;
+ this.powerBrightnessFactor = other.powerBrightnessFactor;
this.nightMode = other.nightMode;
this.colorTemperature = other.colorTemperature;
this.lastBrightness = other.lastBrightness;
+ this.isDefaultBrightnessConfig = other.isDefaultBrightnessConfig;
+ this.isUserSetBrightness = other.isUserSetBrightness;
}
private BrightnessChangeEvent(Parcel source) {
@@ -101,9 +118,12 @@
luxValues = source.createFloatArray();
luxTimestamps = source.createLongArray();
batteryLevel = source.readFloat();
+ powerBrightnessFactor = source.readFloat();
nightMode = source.readBoolean();
colorTemperature = source.readInt();
lastBrightness = source.readFloat();
+ isDefaultBrightnessConfig = source.readBoolean();
+ isUserSetBrightness = source.readBoolean();
}
public static final Creator<BrightnessChangeEvent> CREATOR =
@@ -130,9 +150,12 @@
dest.writeFloatArray(luxValues);
dest.writeLongArray(luxTimestamps);
dest.writeFloat(batteryLevel);
+ dest.writeFloat(powerBrightnessFactor);
dest.writeBoolean(nightMode);
dest.writeInt(colorTemperature);
dest.writeFloat(lastBrightness);
+ dest.writeBoolean(isDefaultBrightnessConfig);
+ dest.writeBoolean(isUserSetBrightness);
}
/** @hide */
@@ -144,9 +167,12 @@
private float[] mLuxValues;
private long[] mLuxTimestamps;
private float mBatteryLevel;
+ private float mPowerBrightnessFactor;
private boolean mNightMode;
private int mColorTemperature;
private float mLastBrightness;
+ private boolean mIsDefaultBrightnessConfig;
+ private boolean mIsUserSetBrightness;
/** {@see BrightnessChangeEvent#brightness} */
public Builder setBrightness(float brightness) {
@@ -190,6 +216,12 @@
return this;
}
+ /** {@see BrightnessChangeEvent#powerSaveBrightness} */
+ public Builder setPowerBrightnessFactor(float powerBrightnessFactor) {
+ mPowerBrightnessFactor = powerBrightnessFactor;
+ return this;
+ }
+
/** {@see BrightnessChangeEvent#nightMode} */
public Builder setNightMode(boolean nightMode) {
mNightMode = nightMode;
@@ -208,11 +240,24 @@
return this;
}
+ /** {@see BrightnessChangeEvent#isDefaultBrightnessConfig} */
+ public Builder setIsDefaultBrightnessConfig(boolean isDefaultBrightnessConfig) {
+ mIsDefaultBrightnessConfig = isDefaultBrightnessConfig;
+ return this;
+ }
+
+ /** {@see BrightnessChangeEvent#userBrightnessPoint} */
+ public Builder setUserBrightnessPoint(boolean isUserSetBrightness) {
+ mIsUserSetBrightness = isUserSetBrightness;
+ return this;
+ }
+
/** Builds a BrightnessChangeEvent */
public BrightnessChangeEvent build() {
return new BrightnessChangeEvent(mBrightness, mTimeStamp,
mPackageName, mUserId, mLuxValues, mLuxTimestamps, mBatteryLevel,
- mNightMode, mColorTemperature, mLastBrightness);
+ mPowerBrightnessFactor, mNightMode, mColorTemperature, mLastBrightness,
+ mIsDefaultBrightnessConfig, mIsUserSetBrightness);
}
}
}
diff --git a/core/java/android/hardware/display/DisplayManager.java b/core/java/android/hardware/display/DisplayManager.java
index 4de4880..22fb8e7 100644
--- a/core/java/android/hardware/display/DisplayManager.java
+++ b/core/java/android/hardware/display/DisplayManager.java
@@ -631,6 +631,16 @@
}
/**
+ * Fetch {@link AmbientBrightnessDayStats}s.
+ *
+ * @hide until we make it a system api
+ */
+ @RequiresPermission(Manifest.permission.ACCESS_AMBIENT_LIGHT_STATS)
+ public List<AmbientBrightnessDayStats> getAmbientBrightnessStats() {
+ return mGlobal.getAmbientBrightnessStats();
+ }
+
+ /**
* Sets the global display brightness configuration.
*
* @hide
diff --git a/core/java/android/hardware/display/DisplayManagerGlobal.java b/core/java/android/hardware/display/DisplayManagerGlobal.java
index 2d5f5e0..d7f7c86 100644
--- a/core/java/android/hardware/display/DisplayManagerGlobal.java
+++ b/core/java/android/hardware/display/DisplayManagerGlobal.java
@@ -525,6 +525,21 @@
}
}
+ /**
+ * Retrieves ambient brightness stats.
+ */
+ public List<AmbientBrightnessDayStats> getAmbientBrightnessStats() {
+ try {
+ ParceledListSlice<AmbientBrightnessDayStats> stats = mDm.getAmbientBrightnessStats();
+ if (stats == null) {
+ return Collections.emptyList();
+ }
+ return stats.getList();
+ } catch (RemoteException ex) {
+ throw ex.rethrowFromSystemServer();
+ }
+ }
+
private final class DisplayManagerCallback extends IDisplayManagerCallback.Stub {
@Override
public void onDisplayEvent(int displayId, int event) {
diff --git a/core/java/android/hardware/display/DisplayManagerInternal.java b/core/java/android/hardware/display/DisplayManagerInternal.java
index 1cfad4f..f468942 100644
--- a/core/java/android/hardware/display/DisplayManagerInternal.java
+++ b/core/java/android/hardware/display/DisplayManagerInternal.java
@@ -174,9 +174,9 @@
public abstract boolean isUidPresentOnDisplay(int uid, int displayId);
/**
- * Persist brightness slider events.
+ * Persist brightness slider events and ambient brightness stats.
*/
- public abstract void persistBrightnessSliderEvents();
+ public abstract void persistBrightnessTrackerState();
/**
* Notifies the display manager that resource overlays have changed.
diff --git a/core/java/android/hardware/display/IDisplayManager.aidl b/core/java/android/hardware/display/IDisplayManager.aidl
index 13599cf..0571ae1 100644
--- a/core/java/android/hardware/display/IDisplayManager.aidl
+++ b/core/java/android/hardware/display/IDisplayManager.aidl
@@ -87,6 +87,9 @@
// Requires BRIGHTNESS_SLIDER_USAGE permission.
ParceledListSlice getBrightnessEvents(String callingPackage);
+ // Requires ACCESS_AMBIENT_LIGHT_STATS permission.
+ ParceledListSlice getAmbientBrightnessStats();
+
// Sets the global brightness configuration for a given user. Requires
// CONFIGURE_DISPLAY_BRIGHTNESS, and INTERACT_ACROSS_USER if the user being configured is not
// the same as the calling user.
diff --git a/core/java/android/hardware/usb/IUsbManager.aidl b/core/java/android/hardware/usb/IUsbManager.aidl
index 398dda1..91bbdc7 100644
--- a/core/java/android/hardware/usb/IUsbManager.aidl
+++ b/core/java/android/hardware/usb/IUsbManager.aidl
@@ -88,18 +88,22 @@
/* Returns true if the specified USB function is enabled. */
boolean isFunctionEnabled(String function);
- /* Sets the current USB function as well as whether USB data
- * (for example, MTP exposed pictures) should be made available
- * on the USB connection. Unlocking data should only be done with
- * user involvement, since exposing pictures or other data could
- * leak sensitive user information.
- */
+ /* Sets the current USB function. */
+ void setCurrentFunctions(long functions);
+
+ /* Compatibility version of setCurrentFunctions(long). */
void setCurrentFunction(String function, boolean usbDataUnlocked);
+ /* Gets the current USB functions. */
+ long getCurrentFunctions();
+
/* Sets the screen unlocked USB function(s), which will be set automatically
* when the screen is unlocked.
*/
- void setScreenUnlockedFunctions(String function);
+ void setScreenUnlockedFunctions(long functions);
+
+ /* Gets the current screen unlocked functions. */
+ long getScreenUnlockedFunctions();
/* Allow USB debugging from the attached host. If alwaysAllow is true, add the
* the public key to list of host keys that the user has approved.
diff --git a/core/java/android/hardware/usb/UsbManager.java b/core/java/android/hardware/usb/UsbManager.java
index 7617c2b..8daecac 100644
--- a/core/java/android/hardware/usb/UsbManager.java
+++ b/core/java/android/hardware/usb/UsbManager.java
@@ -28,6 +28,7 @@
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
+import android.hardware.usb.gadget.V1_0.GadgetFunction;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.Process;
@@ -37,6 +38,8 @@
import com.android.internal.util.Preconditions;
import java.util.HashMap;
+import java.util.Map;
+import java.util.StringJoiner;
/**
* This class allows you to access the state of USB and communicate with USB devices.
@@ -70,7 +73,7 @@
* MTP function is enabled
* <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
* PTP function is enabled
- * <li> {@link #USB_FUNCTION_PTP} boolean extra indicating whether the
+ * <li> {@link #USB_FUNCTION_ACCESSORY} boolean extra indicating whether the
* accessory function is enabled
* <li> {@link #USB_FUNCTION_AUDIO_SOURCE} boolean extra indicating whether the
* audio source function is enabled
@@ -196,8 +199,7 @@
/**
* A placeholder indicating that no USB function is being specified.
- * Used to distinguish between selecting no function vs. the default function in
- * {@link #setCurrentFunction(String)}.
+ * Used for compatibility with old init scripts to indicate no functions vs. charging function.
*
* {@hide}
*/
@@ -298,6 +300,69 @@
*/
public static final String EXTRA_PERMISSION_GRANTED = "permission";
+ /**
+ * Code for the charging usb function. Passed into {@link #setCurrentFunctions(long)}
+ * {@hide}
+ */
+ public static final long FUNCTION_NONE = 0;
+
+ /**
+ * Code for the mtp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
+ * {@hide}
+ */
+ public static final long FUNCTION_MTP = GadgetFunction.MTP;
+
+ /**
+ * Code for the ptp usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
+ * {@hide}
+ */
+ public static final long FUNCTION_PTP = GadgetFunction.PTP;
+
+ /**
+ * Code for the rndis usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
+ * {@hide}
+ */
+ public static final long FUNCTION_RNDIS = GadgetFunction.RNDIS;
+
+ /**
+ * Code for the midi usb function. Passed as a mask into {@link #setCurrentFunctions(long)}
+ * {@hide}
+ */
+ public static final long FUNCTION_MIDI = GadgetFunction.MIDI;
+
+ /**
+ * Code for the accessory usb function.
+ * {@hide}
+ */
+ public static final long FUNCTION_ACCESSORY = GadgetFunction.ACCESSORY;
+
+ /**
+ * Code for the audio source usb function.
+ * {@hide}
+ */
+ public static final long FUNCTION_AUDIO_SOURCE = GadgetFunction.AUDIO_SOURCE;
+
+ /**
+ * Code for the adb usb function.
+ * {@hide}
+ */
+ public static final long FUNCTION_ADB = GadgetFunction.ADB;
+
+ private static final long SETTABLE_FUNCTIONS = FUNCTION_MTP | FUNCTION_PTP | FUNCTION_RNDIS
+ | FUNCTION_MIDI;
+
+ private static final Map<String, Long> FUNCTION_NAME_TO_CODE = new HashMap<>();
+
+ static {
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MTP, FUNCTION_MTP);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_PTP, FUNCTION_PTP);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_RNDIS, FUNCTION_RNDIS);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_MIDI, FUNCTION_MIDI);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ACCESSORY, FUNCTION_ACCESSORY);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_AUDIO_SOURCE, FUNCTION_AUDIO_SOURCE);
+ FUNCTION_NAME_TO_CODE.put(UsbManager.USB_FUNCTION_ADB, FUNCTION_ADB);
+ }
+
private final Context mContext;
private final IUsbManager mService;
@@ -548,15 +613,14 @@
* services offered by the device.
* </p>
*
+ * @deprecated use getCurrentFunctions() instead.
* @param function name of the USB function
* @return true if the USB function is enabled
*
* {@hide}
*/
+ @Deprecated
public boolean isFunctionEnabled(String function) {
- if (mService == null) {
- return false;
- }
try {
return mService.isFunctionEnabled(function);
} catch (RemoteException e) {
@@ -565,7 +629,7 @@
}
/**
- * Sets the current USB function when in device mode.
+ * Sets the current USB functions when in device mode.
* <p>
* USB functions represent interfaces which are published to the host to access
* services offered by the device.
@@ -574,27 +638,59 @@
* automatically activate additional functions such as {@link #USB_FUNCTION_ADB}
* or {@link #USB_FUNCTION_ACCESSORY} based on other settings and states.
* </p><p>
- * The allowed values are: {@link #USB_FUNCTION_NONE}, {@link #USB_FUNCTION_AUDIO_SOURCE},
- * {@link #USB_FUNCTION_MIDI}, {@link #USB_FUNCTION_MTP}, {@link #USB_FUNCTION_PTP},
- * or {@link #USB_FUNCTION_RNDIS}.
- * </p><p>
- * Also sets whether USB data (for example, MTP exposed pictures) should be made available
- * on the USB connection when in device mode. Unlocking usb data should only be done with
- * user involvement, since exposing pictures or other data could leak sensitive
- * user information.
+ * An argument of 0 indicates that the device is charging, and can pick any
+ * appropriate function for that purpose.
* </p><p>
* Note: This function is asynchronous and may fail silently without applying
* the requested changes.
* </p>
*
- * @param function name of the USB function, or null to restore the default function
- * @param usbDataUnlocked whether user data is accessible
+ * @param functions the USB function(s) to set, as a bitwise mask.
+ * Must satisfy {@link UsbManager#areSettableFunctions}
*
* {@hide}
*/
- public void setCurrentFunction(String function, boolean usbDataUnlocked) {
+ public void setCurrentFunctions(long functions) {
try {
- mService.setCurrentFunction(function, usbDataUnlocked);
+ mService.setCurrentFunctions(functions);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Sets the current USB functions when in device mode.
+ *
+ * @deprecated use setCurrentFunctions(long) instead.
+ * @param functions the USB function(s) to set.
+ * @param usbDataUnlocked unused
+
+ * {@hide}
+ */
+ @Deprecated
+ public void setCurrentFunction(String functions, boolean usbDataUnlocked) {
+ try {
+ mService.setCurrentFunction(functions, usbDataUnlocked);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Returns the current USB functions in device mode.
+ * <p>
+ * This function returns the state of primary USB functions and can return a
+ * mask containing any usb function(s) except for ADB.
+ * </p>
+ *
+ * @return The currently enabled functions, in a bitwise mask.
+ * A zero mask indicates that the current function is the charging function.
+ *
+ * {@hide}
+ */
+ public long getCurrentFunctions() {
+ try {
+ return mService.getCurrentFunctions();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -604,23 +700,37 @@
* Sets the screen unlocked functions, which are persisted and set as the current functions
* whenever the screen is unlocked.
* <p>
- * The allowed values are: {@link #USB_FUNCTION_NONE},
- * {@link #USB_FUNCTION_MIDI}, {@link #USB_FUNCTION_MTP}, {@link #USB_FUNCTION_PTP},
- * or {@link #USB_FUNCTION_RNDIS}.
- * {@link #USB_FUNCTION_NONE} has the effect of switching off this feature, so functions
+ * A zero mask has the effect of switching off this feature, so functions
* no longer change on screen unlock.
* </p><p>
* Note: When the screen is on, this method will apply given functions as current functions,
* which is asynchronous and may fail silently without applying the requested changes.
* </p>
*
- * @param function function to set as default
+ * @param functions functions to set, in a bitwise mask.
+ * Must satisfy {@link UsbManager#areSettableFunctions}
*
* {@hide}
*/
- public void setScreenUnlockedFunctions(String function) {
+ public void setScreenUnlockedFunctions(long functions) {
try {
- mService.setScreenUnlockedFunctions(function);
+ mService.setScreenUnlockedFunctions(functions);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Gets the current screen unlocked functions.
+ *
+ * @return The currently set screen enabled functions.
+ * A zero mask indicates that the screen unlocked functions feature is not enabled.
+ *
+ * {@hide}
+ */
+ public long getScreenUnlockedFunctions() {
+ try {
+ return mService.getScreenUnlockedFunctions();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -719,51 +829,71 @@
}
}
- /** @hide */
- public static String addFunction(String functions, String function) {
- if (USB_FUNCTION_NONE.equals(functions)) {
- return function;
- }
- if (!containsFunction(functions, function)) {
- if (functions.length() > 0) {
- functions += ",";
- }
- functions += function;
- }
- return functions;
+ /**
+ * Returns whether the given functions are valid inputs to UsbManager.
+ * Currently the empty functions or any of MTP, PTP, RNDIS, MIDI are accepted.
+ *
+ * @return Whether the mask is settable.
+ *
+ * {@hide}
+ */
+ public static boolean areSettableFunctions(long functions) {
+ return functions == FUNCTION_NONE
+ || ((~SETTABLE_FUNCTIONS & functions) == 0 && Long.bitCount(functions) == 1);
}
- /** @hide */
- public static String removeFunction(String functions, String function) {
- String[] split = functions.split(",");
- for (int i = 0; i < split.length; i++) {
- if (function.equals(split[i])) {
- split[i] = null;
- }
+ /**
+ * Converts the given function mask to string. Maintains ordering with respect to init scripts.
+ *
+ * @return String representation of given mask
+ *
+ * {@hide}
+ */
+ public static String usbFunctionsToString(long functions) {
+ StringJoiner joiner = new StringJoiner(",");
+ if ((functions & FUNCTION_MTP) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_MTP);
}
- if (split.length == 1 && split[0] == null) {
- return USB_FUNCTION_NONE;
+ if ((functions & FUNCTION_PTP) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_PTP);
}
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < split.length; i++) {
- String s = split[i];
- if (s != null) {
- if (builder.length() > 0) {
- builder.append(",");
- }
- builder.append(s);
- }
+ if ((functions & FUNCTION_RNDIS) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_RNDIS);
}
- return builder.toString();
+ if ((functions & FUNCTION_MIDI) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_MIDI);
+ }
+ if ((functions & FUNCTION_ACCESSORY) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_ACCESSORY);
+ }
+ if ((functions & FUNCTION_AUDIO_SOURCE) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_AUDIO_SOURCE);
+ }
+ if ((functions & FUNCTION_ADB) != 0) {
+ joiner.add(UsbManager.USB_FUNCTION_ADB);
+ }
+ return joiner.toString();
}
- /** @hide */
- public static boolean containsFunction(String functions, String function) {
- int index = functions.indexOf(function);
- if (index < 0) return false;
- if (index > 0 && functions.charAt(index - 1) != ',') return false;
- int charAfter = index + function.length();
- if (charAfter < functions.length() && functions.charAt(charAfter) != ',') return false;
- return true;
+ /**
+ * Parses a string of usb functions that are comma separated.
+ *
+ * @return A mask of all valid functions in the string
+ *
+ * {@hide}
+ */
+ public static long usbFunctionsFromString(String functions) {
+ if (functions == null || functions.equals(USB_FUNCTION_NONE)) {
+ return FUNCTION_NONE;
+ }
+ long ret = 0;
+ for (String function : functions.split(",")) {
+ if (FUNCTION_NAME_TO_CODE.containsKey(function)) {
+ ret |= FUNCTION_NAME_TO_CODE.get(function);
+ } else if (function.length() > 0) {
+ throw new IllegalArgumentException("Invalid usb function " + functions);
+ }
+ }
+ return ret;
}
}
diff --git a/core/java/android/net/IpSecTransform.java b/core/java/android/net/IpSecTransform.java
index 9ccdbe2..0829b4a 100644
--- a/core/java/android/net/IpSecTransform.java
+++ b/core/java/android/net/IpSecTransform.java
@@ -462,7 +462,7 @@
mConfig.setMode(MODE_TUNNEL);
mConfig.setSourceAddress(sourceAddress.getHostAddress());
mConfig.setSpiResourceId(spi.getResourceId());
- return new IpSecTransform(mContext, mConfig);
+ return new IpSecTransform(mContext, mConfig).activate();
}
/**
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 7c53ec1..21d245d 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -16,6 +16,11 @@
package android.os;
+import static android.system.OsConstants.SPLICE_F_MORE;
+import static android.system.OsConstants.SPLICE_F_MOVE;
+import static android.system.OsConstants.S_ISFIFO;
+import static android.system.OsConstants.S_ISREG;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.provider.DocumentsContract.Document;
@@ -29,6 +34,7 @@
import com.android.internal.annotations.VisibleForTesting;
+import libcore.io.IoUtils;
import libcore.util.EmptyArray;
import java.io.BufferedInputStream;
@@ -41,10 +47,12 @@
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
+import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
@@ -81,6 +89,14 @@
private static final File[] EMPTY = new File[0];
+ private static final boolean ENABLE_COPY_OPTIMIZATIONS = true;
+
+ private static final long COPY_CHECKPOINT_BYTES = 524288;
+
+ public interface CopyListener {
+ public void onProgress(long progress);
+ }
+
/**
* Set owner and mode of of given {@link File}.
*
@@ -185,6 +201,9 @@
return false;
}
+ /**
+ * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
+ */
@Deprecated
public static boolean copyFile(File srcFile, File destFile) {
try {
@@ -195,14 +214,19 @@
}
}
- // copy a file from srcFile to destFile, return true if succeed, return
- // false if fail
+ /**
+ * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
+ */
+ @Deprecated
public static void copyFileOrThrow(File srcFile, File destFile) throws IOException {
try (InputStream in = new FileInputStream(srcFile)) {
copyToFileOrThrow(in, destFile);
}
}
+ /**
+ * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
+ */
@Deprecated
public static boolean copyToFile(InputStream inputStream, File destFile) {
try {
@@ -214,28 +238,153 @@
}
/**
- * Copy data from a source stream to destFile.
- * Return true if succeed, return false if failed.
+ * @deprecated use {@link #copy(InputStream, OutputStream)} instead.
*/
- public static void copyToFileOrThrow(InputStream inputStream, File destFile)
- throws IOException {
+ @Deprecated
+ public static void copyToFileOrThrow(InputStream in, File destFile) throws IOException {
if (destFile.exists()) {
destFile.delete();
}
- FileOutputStream out = new FileOutputStream(destFile);
- try {
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = inputStream.read(buffer)) >= 0) {
- out.write(buffer, 0, bytesRead);
- }
- } finally {
- out.flush();
+ try (FileOutputStream out = new FileOutputStream(destFile)) {
+ copy(in, out);
try {
- out.getFD().sync();
- } catch (IOException e) {
+ Os.fsync(out.getFD());
+ } catch (ErrnoException e) {
+ throw e.rethrowAsIOException();
}
- out.close();
+ }
+ }
+
+ public static void copy(File from, File to) throws IOException {
+ try (FileInputStream in = new FileInputStream(from);
+ FileOutputStream out = new FileOutputStream(to)) {
+ copy(in, out);
+ }
+ }
+
+ public static void copy(InputStream in, OutputStream out) throws IOException {
+ copy(in, out, null, null);
+ }
+
+ public static void copy(InputStream in, OutputStream out, CopyListener listener,
+ CancellationSignal signal) throws IOException {
+ if (ENABLE_COPY_OPTIMIZATIONS) {
+ if (in instanceof FileInputStream && out instanceof FileOutputStream) {
+ copy(((FileInputStream) in).getFD(), ((FileOutputStream) out).getFD(),
+ listener, signal);
+ }
+ }
+
+ // Worse case fallback to userspace
+ copyInternalUserspace(in, out, listener, signal);
+ }
+
+ public static void copy(FileDescriptor in, FileDescriptor out) throws IOException {
+ copy(in, out, null, null);
+ }
+
+ public static void copy(FileDescriptor in, FileDescriptor out, CopyListener listener,
+ CancellationSignal signal) throws IOException {
+ if (ENABLE_COPY_OPTIMIZATIONS) {
+ try {
+ final StructStat st_in = Os.fstat(in);
+ final StructStat st_out = Os.fstat(out);
+ if (S_ISREG(st_in.st_mode) && S_ISREG(st_out.st_mode)) {
+ copyInternalSendfile(in, out, listener, signal);
+ } else if (S_ISFIFO(st_in.st_mode) || S_ISFIFO(st_out.st_mode)) {
+ copyInternalSplice(in, out, listener, signal);
+ }
+ } catch (ErrnoException e) {
+ throw e.rethrowAsIOException();
+ }
+ }
+
+ // Worse case fallback to userspace
+ copyInternalUserspace(in, out, listener, signal);
+ }
+
+ /**
+ * Requires one of input or output to be a pipe.
+ */
+ @VisibleForTesting
+ public static void copyInternalSplice(FileDescriptor in, FileDescriptor out,
+ CopyListener listener, CancellationSignal signal) throws ErrnoException {
+ long progress = 0;
+ long checkpoint = 0;
+
+ long t;
+ while ((t = Os.splice(in, null, out, null, COPY_CHECKPOINT_BYTES,
+ SPLICE_F_MOVE | SPLICE_F_MORE)) != 0) {
+ progress += t;
+ checkpoint += t;
+
+ if (checkpoint >= COPY_CHECKPOINT_BYTES) {
+ if (signal != null) {
+ signal.throwIfCanceled();
+ }
+ if (listener != null) {
+ listener.onProgress(progress);
+ }
+ checkpoint = 0;
+ }
+ }
+ }
+
+ /**
+ * Requires both input and output to be a regular file.
+ */
+ @VisibleForTesting
+ public static void copyInternalSendfile(FileDescriptor in, FileDescriptor out,
+ CopyListener listener, CancellationSignal signal) throws ErrnoException {
+ long progress = 0;
+ long checkpoint = 0;
+
+ long t;
+ while ((t = Os.sendfile(out, in, null, COPY_CHECKPOINT_BYTES)) != 0) {
+ progress += t;
+ checkpoint += t;
+
+ if (checkpoint >= COPY_CHECKPOINT_BYTES) {
+ if (signal != null) {
+ signal.throwIfCanceled();
+ }
+ if (listener != null) {
+ listener.onProgress(progress);
+ }
+ checkpoint = 0;
+ }
+ }
+ }
+
+ @VisibleForTesting
+ public static void copyInternalUserspace(FileDescriptor in, FileDescriptor out,
+ CopyListener listener, CancellationSignal signal) throws IOException {
+ copyInternalUserspace(new FileInputStream(in), new FileOutputStream(out), listener, signal);
+ }
+
+ @VisibleForTesting
+ public static void copyInternalUserspace(InputStream in, OutputStream out,
+ CopyListener listener, CancellationSignal signal) throws IOException {
+ long progress = 0;
+ long checkpoint = 0;
+ byte[] buffer = new byte[8192];
+
+ int t;
+ while ((t = in.read(buffer)) != -1) {
+ out.write(buffer, 0, t);
+
+ progress += t;
+ checkpoint += t;
+
+ if (checkpoint >= COPY_CHECKPOINT_BYTES) {
+ if (signal != null) {
+ signal.throwIfCanceled();
+ }
+ if (listener != null) {
+ listener.onProgress(progress);
+ }
+ checkpoint = 0;
+ }
}
}
@@ -797,4 +946,69 @@
}
return val * pow;
}
+
+ @VisibleForTesting
+ public static class MemoryPipe extends Thread implements AutoCloseable {
+ private final FileDescriptor[] pipe;
+ private final byte[] data;
+ private final boolean sink;
+
+ private MemoryPipe(byte[] data, boolean sink) throws IOException {
+ try {
+ this.pipe = Os.pipe();
+ } catch (ErrnoException e) {
+ throw e.rethrowAsIOException();
+ }
+ this.data = data;
+ this.sink = sink;
+ }
+
+ private MemoryPipe startInternal() {
+ super.start();
+ return this;
+ }
+
+ public static MemoryPipe createSource(byte[] data) throws IOException {
+ return new MemoryPipe(data, false).startInternal();
+ }
+
+ public static MemoryPipe createSink(byte[] data) throws IOException {
+ return new MemoryPipe(data, true).startInternal();
+ }
+
+ public FileDescriptor getFD() {
+ return sink ? pipe[1] : pipe[0];
+ }
+
+ public FileDescriptor getInternalFD() {
+ return sink ? pipe[0] : pipe[1];
+ }
+
+ @Override
+ public void run() {
+ final FileDescriptor fd = getInternalFD();
+ try {
+ int i = 0;
+ while (i < data.length) {
+ if (sink) {
+ i += Os.read(fd, data, i, data.length - i);
+ } else {
+ i += Os.write(fd, data, i, data.length - i);
+ }
+ }
+ } catch (IOException | ErrnoException e) {
+ throw new RuntimeException(e);
+ } finally {
+ if (sink) {
+ SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
+ }
+ IoUtils.closeQuietly(fd);
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ IoUtils.closeQuietly(getFD());
+ }
+ }
}
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 1f0d683..ad0ce49 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -1903,7 +1903,7 @@
cp.call(cr.getPackageName(), mCallSetCommand, name, arg);
String newValue = getStringForUser(cr, name, userHandle);
StatsLog.write(StatsLog.SETTING_CHANGED, name, value, newValue, prevValue, tag,
- makeDefault ? 1 : 0, userHandle);
+ makeDefault, userHandle);
} catch (RemoteException e) {
Log.w(TAG, "Can't set key " + name + " in " + mUri, e);
return false;
diff --git a/core/java/android/service/autofill/AutofillService.java b/core/java/android/service/autofill/AutofillService.java
index 917efa8..12aa64e 100644
--- a/core/java/android/service/autofill/AutofillService.java
+++ b/core/java/android/service/autofill/AutofillService.java
@@ -468,9 +468,8 @@
* <p>Typically, field classification can be used to detect fields that can be autofilled with
* user data that is not associated with a specific app—such as email and physical
* address. Once the service identifies that a such field was manually filled by the user, the
- * service could use this signal to improve its heuristics, either locally (i.e., in the same
- * device) or globally (i.e., by crowdsourcing the results back to the service's server so it can
- * be used by other users).
+ * service could use this signal to improve its heuristics on subsequent requests (for example, by
+ * infering which resource ids are associated with known fields).
*
* <p>The field classification workflow involves 4 steps:
*
@@ -481,8 +480,8 @@
* <li>Identify which fields should be analysed by calling
* {@link FillResponse.Builder#setFieldClassificationIds(AutofillId...)}.
* <li>Verify the results through {@link FillEventHistory.Event#getFieldsClassification()}.
- * <li>Use the results to dynamically create {@link Dataset} or {@link SaveInfo} objects in future
- * requests.
+ * <li>Use the results to dynamically create {@link Dataset} or {@link SaveInfo} objects in
+ * subsequent requests.
* </ol>
*
* <p>The field classification is an expensive operation and should be used carefully, otherwise it
diff --git a/core/java/android/service/autofill/CustomDescription.java b/core/java/android/service/autofill/CustomDescription.java
index b8e8b19..fb468a8 100644
--- a/core/java/android/service/autofill/CustomDescription.java
+++ b/core/java/android/service/autofill/CustomDescription.java
@@ -173,7 +173,10 @@
}
/**
- * Updates the {@link RemoteViews presentation template} when a condition is satisfied.
+ * Updates the {@link RemoteViews presentation template} when a condition is satisfied by
+ * applying a series of remote view operations. This allows dynamic customization of the
+ * portion of the save UI that is controlled by the autofill service. Such dynamic
+ * customization is based on the content of target views.
*
* <p>The updates are applied in the sequence they are added, after the
* {@link #addChild(int, Transformation) transformations} are applied to the children
diff --git a/core/java/android/service/autofill/Dataset.java b/core/java/android/service/autofill/Dataset.java
index 266bcda..f32dee1 100644
--- a/core/java/android/service/autofill/Dataset.java
+++ b/core/java/android/service/autofill/Dataset.java
@@ -29,7 +29,6 @@
import com.android.internal.util.Preconditions;
-import java.io.Serializable;
import java.util.ArrayList;
import java.util.regex.Pattern;
@@ -99,7 +98,7 @@
private final ArrayList<AutofillId> mFieldIds;
private final ArrayList<AutofillValue> mFieldValues;
private final ArrayList<RemoteViews> mFieldPresentations;
- private final ArrayList<Pattern> mFieldFilters;
+ private final ArrayList<DatasetFieldFilter> mFieldFilters;
private final RemoteViews mPresentation;
private final IntentSender mAuthentication;
@Nullable String mId;
@@ -132,7 +131,7 @@
/** @hide */
@Nullable
- public Pattern getFilter(int index) {
+ public DatasetFieldFilter getFilter(int index) {
return mFieldFilters.get(index);
}
@@ -189,7 +188,7 @@
private ArrayList<AutofillId> mFieldIds;
private ArrayList<AutofillValue> mFieldValues;
private ArrayList<RemoteViews> mFieldPresentations;
- private ArrayList<Pattern> mFieldFilters;
+ private ArrayList<DatasetFieldFilter> mFieldFilters;
private RemoteViews mPresentation;
private IntentSender mAuthentication;
private boolean mDestroyed;
@@ -363,19 +362,21 @@
* @param value the value to be autofilled. Pass {@code null} if you do not have the value
* but the target view is a logical part of the dataset. For example, if
* the dataset needs authentication and you have no access to the value.
- * @param filter regex used to determine if the dataset should be shown in the autofill UI.
+ * @param filter regex used to determine if the dataset should be shown in the autofill UI;
+ * when {@code null}, it disables filtering on that dataset (this is the recommended
+ * approach when {@code value} is not {@code null} and field contains sensitive data
+ * such as passwords).
*
* @return this builder.
* @throws IllegalStateException if the builder was constructed without a
* {@link RemoteViews presentation}.
*/
public @NonNull Builder setValue(@NonNull AutofillId id, @Nullable AutofillValue value,
- @NonNull Pattern filter) {
+ @Nullable Pattern filter) {
throwIfDestroyed();
- Preconditions.checkNotNull(filter, "filter cannot be null");
Preconditions.checkState(mPresentation != null,
"Dataset presentation not set on constructor");
- setLifeTheUniverseAndEverything(id, value, null, filter);
+ setLifeTheUniverseAndEverything(id, value, null, new DatasetFieldFilter(filter));
return this;
}
@@ -398,23 +399,26 @@
* @param value the value to be autofilled. Pass {@code null} if you do not have the value
* but the target view is a logical part of the dataset. For example, if
* the dataset needs authentication and you have no access to the value.
+ * @param filter regex used to determine if the dataset should be shown in the autofill UI;
+ * when {@code null}, it disables filtering on that dataset (this is the recommended
+ * approach when {@code value} is not {@code null} and field contains sensitive data
+ * such as passwords).
* @param presentation the presentation used to visualize this field.
- * @param filter regex used to determine if the dataset should be shown in the autofill UI.
*
* @return this builder.
*/
public @NonNull Builder setValue(@NonNull AutofillId id, @Nullable AutofillValue value,
- @NonNull Pattern filter, @NonNull RemoteViews presentation) {
+ @Nullable Pattern filter, @NonNull RemoteViews presentation) {
throwIfDestroyed();
- Preconditions.checkNotNull(filter, "filter cannot be null");
Preconditions.checkNotNull(presentation, "presentation cannot be null");
- setLifeTheUniverseAndEverything(id, value, presentation, filter);
+ setLifeTheUniverseAndEverything(id, value, presentation,
+ new DatasetFieldFilter(filter));
return this;
}
private void setLifeTheUniverseAndEverything(@NonNull AutofillId id,
@Nullable AutofillValue value, @Nullable RemoteViews presentation,
- @Nullable Pattern filter) {
+ @Nullable DatasetFieldFilter filter) {
Preconditions.checkNotNull(id, "id cannot be null");
if (mFieldIds != null) {
final int existingIdx = mFieldIds.indexOf(id);
@@ -477,8 +481,8 @@
parcel.writeParcelable(mPresentation, flags);
parcel.writeTypedList(mFieldIds, flags);
parcel.writeTypedList(mFieldValues, flags);
- parcel.writeParcelableList(mFieldPresentations, flags);
- parcel.writeSerializable(mFieldFilters);
+ parcel.writeTypedList(mFieldPresentations, flags);
+ parcel.writeTypedList(mFieldFilters, flags);
parcel.writeParcelable(mAuthentication, flags);
parcel.writeString(mId);
}
@@ -493,22 +497,19 @@
final Builder builder = (presentation == null)
? new Builder()
: new Builder(presentation);
- final ArrayList<AutofillId> ids = parcel.createTypedArrayList(AutofillId.CREATOR);
+ final ArrayList<AutofillId> ids =
+ parcel.createTypedArrayList(AutofillId.CREATOR);
final ArrayList<AutofillValue> values =
parcel.createTypedArrayList(AutofillValue.CREATOR);
- final ArrayList<RemoteViews> presentations = new ArrayList<>();
- parcel.readParcelableList(presentations, null);
- @SuppressWarnings("unchecked")
- final ArrayList<Serializable> filters =
- (ArrayList<Serializable>) parcel.readSerializable();
- final int idCount = (ids != null) ? ids.size() : 0;
- final int valueCount = (values != null) ? values.size() : 0;
- for (int i = 0; i < idCount; i++) {
+ final ArrayList<RemoteViews> presentations =
+ parcel.createTypedArrayList(RemoteViews.CREATOR);
+ final ArrayList<DatasetFieldFilter> filters =
+ parcel.createTypedArrayList(DatasetFieldFilter.CREATOR);
+ for (int i = 0; i < ids.size(); i++) {
final AutofillId id = ids.get(i);
- final AutofillValue value = (valueCount > i) ? values.get(i) : null;
- final RemoteViews fieldPresentation = presentations.isEmpty() ? null
- : presentations.get(i);
- final Pattern filter = (Pattern) filters.get(i);
+ final AutofillValue value = values.get(i);
+ final RemoteViews fieldPresentation = presentations.get(i);
+ final DatasetFieldFilter filter = filters.get(i);
builder.setLifeTheUniverseAndEverything(id, value, fieldPresentation, filter);
}
builder.setAuthentication(parcel.readParcelable(null));
@@ -521,4 +522,55 @@
return new Dataset[size];
}
};
+
+ /**
+ * Helper class used to indicate when the service explicitly set a {@link Pattern} filter for a
+ * dataset field‐ we cannot use a {@link Pattern} directly because then we wouldn't be
+ * able to differentiate whether the service explicitly passed a {@code null} filter to disable
+ * filter, or when it called the methods that does not take a filter {@link Pattern}.
+ *
+ * @hide
+ */
+ public static final class DatasetFieldFilter implements Parcelable {
+
+ @Nullable
+ public final Pattern pattern;
+
+ private DatasetFieldFilter(@Nullable Pattern pattern) {
+ this.pattern = pattern;
+ }
+
+ @Override
+ public String toString() {
+ if (!sDebug) return super.toString();
+
+ // Cannot log pattern because it could contain PII
+ return pattern == null ? "null" : pattern.pattern().length() + "_chars";
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int flags) {
+ parcel.writeSerializable(pattern);
+ }
+
+ @SuppressWarnings("hiding")
+ public static final Creator<DatasetFieldFilter> CREATOR =
+ new Creator<DatasetFieldFilter>() {
+
+ @Override
+ public DatasetFieldFilter createFromParcel(Parcel parcel) {
+ return new DatasetFieldFilter((Pattern) parcel.readSerializable());
+ }
+
+ @Override
+ public DatasetFieldFilter[] newArray(int size) {
+ return new DatasetFieldFilter[size];
+ }
+ };
+ }
}
diff --git a/core/java/android/service/settings/suggestions/Suggestion.java b/core/java/android/service/settings/suggestions/Suggestion.java
index 11e1e67..e97f963a 100644
--- a/core/java/android/service/settings/suggestions/Suggestion.java
+++ b/core/java/android/service/settings/suggestions/Suggestion.java
@@ -40,6 +40,7 @@
*/
@IntDef(flag = true, prefix = { "FLAG_" }, value = {
FLAG_HAS_BUTTON,
+ FLAG_ICON_TINTABLE,
})
@Retention(RetentionPolicy.SOURCE)
public @interface Flags {
@@ -49,6 +50,10 @@
* Flag for suggestion type with a single button
*/
public static final int FLAG_HAS_BUTTON = 1 << 0;
+ /**
+ * @hide
+ */
+ public static final int FLAG_ICON_TINTABLE = 1 << 1;
private final String mId;
private final CharSequence mTitle;
diff --git a/core/java/android/util/FeatureFlagUtils.java b/core/java/android/util/FeatureFlagUtils.java
index 57d23ce..410cdc6 100644
--- a/core/java/android/util/FeatureFlagUtils.java
+++ b/core/java/android/util/FeatureFlagUtils.java
@@ -42,7 +42,6 @@
DEFAULT_FLAGS.put("settings_battery_v2", "true");
DEFAULT_FLAGS.put("settings_battery_display_app_list", "false");
DEFAULT_FLAGS.put("settings_zone_picker_v2", "true");
- DEFAULT_FLAGS.put("settings_suggestion_ui_v2", "false");
DEFAULT_FLAGS.put("settings_about_phone_v2", "false");
DEFAULT_FLAGS.put("settings_bluetooth_while_driving", "false");
}
diff --git a/core/java/android/util/StatsManager.java b/core/java/android/util/StatsManager.java
index 687aa83..51fb18a 100644
--- a/core/java/android/util/StatsManager.java
+++ b/core/java/android/util/StatsManager.java
@@ -60,9 +60,19 @@
*/
@RequiresPermission(Manifest.permission.DUMP)
public boolean addConfiguration(String configKey, byte[] config, String pkg, String cls) {
- // To prevent breakages of dependencies on old API.
-
- return false;
+ synchronized (this) {
+ try {
+ IStatsManager service = getIStatsManagerLocked();
+ if (service == null) {
+ Slog.d(TAG, "Failed to find statsd when adding configuration");
+ return false;
+ }
+ return service.addConfiguration(Long.parseLong(configKey), config, pkg, cls);
+ } catch (RemoteException e) {
+ Slog.d(TAG, "Failed to connect to statsd when adding configuration");
+ return false;
+ }
+ }
}
/**
@@ -99,7 +109,19 @@
@RequiresPermission(Manifest.permission.DUMP)
public boolean removeConfiguration(String configKey) {
// To prevent breakages of old dependencies.
- return false;
+ synchronized (this) {
+ try {
+ IStatsManager service = getIStatsManagerLocked();
+ if (service == null) {
+ Slog.d(TAG, "Failed to find statsd when removing configuration");
+ return false;
+ }
+ return service.removeConfiguration(Long.parseLong(configKey));
+ } catch (RemoteException e) {
+ Slog.d(TAG, "Failed to connect to statsd when removing configuration");
+ return false;
+ }
+ }
}
/**
@@ -132,7 +154,19 @@
public byte[] getData(String configKey) {
// TODO: remove this and all other methods with String-based config keys.
// To prevent build breakages of dependencies.
- return null;
+ synchronized (this) {
+ try {
+ IStatsManager service = getIStatsManagerLocked();
+ if (service == null) {
+ Slog.d(TAG, "Failed to find statsd when getting data");
+ return null;
+ }
+ return service.getData(Long.parseLong(configKey));
+ } catch (RemoteException e) {
+ Slog.d(TAG, "Failed to connecto statsd when getting data");
+ return null;
+ }
+ }
}
/**
diff --git a/core/java/android/view/RenderNode.java b/core/java/android/view/RenderNode.java
index 5070151..ce7e8f3 100644
--- a/core/java/android/view/RenderNode.java
+++ b/core/java/android/view/RenderNode.java
@@ -353,9 +353,24 @@
return nHasShadow(mNativeRenderNode);
}
- /** setShadowColor */
- public boolean setShadowColor(int color) {
- return nSetShadowColor(mNativeRenderNode, color);
+ /** setSpotShadowColor */
+ public boolean setSpotShadowColor(int color) {
+ return nSetSpotShadowColor(mNativeRenderNode, color);
+ }
+
+ /** setAmbientShadowColor */
+ public boolean setAmbientShadowColor(int color) {
+ return nSetAmbientShadowColor(mNativeRenderNode, color);
+ }
+
+ /** getSpotShadowColor */
+ public int getSpotShadowColor() {
+ return nGetSpotShadowColor(mNativeRenderNode);
+ }
+
+ /** getAmbientShadowColor */
+ public int getAmbientShadowColor() {
+ return nGetAmbientShadowColor(mNativeRenderNode);
}
/**
@@ -915,7 +930,13 @@
@CriticalNative
private static native boolean nHasShadow(long renderNode);
@CriticalNative
- private static native boolean nSetShadowColor(long renderNode, int color);
+ private static native boolean nSetSpotShadowColor(long renderNode, int color);
+ @CriticalNative
+ private static native boolean nSetAmbientShadowColor(long renderNode, int color);
+ @CriticalNative
+ private static native int nGetSpotShadowColor(long renderNode);
+ @CriticalNative
+ private static native int nGetAmbientShadowColor(long renderNode);
@CriticalNative
private static native boolean nSetClipToOutline(long renderNode, boolean clipToOutline);
@CriticalNative
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 9770fba..3cbd275 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -725,6 +725,8 @@
* @attr ref android.R.styleable#View_nextFocusRight
* @attr ref android.R.styleable#View_nextFocusUp
* @attr ref android.R.styleable#View_onClick
+ * @attr ref android.R.styleable#View_outlineSpotShadowColor
+ * @attr ref android.R.styleable#View_outlineAmbientShadowColor
* @attr ref android.R.styleable#View_padding
* @attr ref android.R.styleable#View_paddingHorizontal
* @attr ref android.R.styleable#View_paddingVertical
@@ -5446,6 +5448,12 @@
setAccessibilityPaneTitle(a.getString(attr));
}
break;
+ case R.styleable.View_outlineSpotShadowColor:
+ setOutlineSpotShadowColor(a.getColor(attr, Color.BLACK));
+ break;
+ case R.styleable.View_outlineAmbientShadowColor:
+ setOutlineAmbientShadowColor(a.getColor(attr, Color.BLACK));
+ break;
}
}
@@ -15481,14 +15489,61 @@
}
/**
- * @hide
+ * Sets the color of the spot shadow that is drawn when the view has a positive Z or
+ * elevation value.
+ * <p>
+ * By default the shadow color is black. Generally, this color will be opaque so the intensity
+ * of the shadow is consistent between different views with different colors.
+ * <p>
+ * The opacity of the final spot shadow is a function of the shadow caster height, the
+ * alpha channel of the outlineSpotShadowColor (typically opaque), and the
+ * {@link android.R.attr#spotShadowAlpha} theme attribute.
+ *
+ * @attr ref android.R.styleable#View_outlineSpotShadowColor
+ * @param color The color this View will cast for its elevation spot shadow.
*/
- public void setShadowColor(@ColorInt int color) {
- if (mRenderNode.setShadowColor(color)) {
+ public void setOutlineSpotShadowColor(@ColorInt int color) {
+ if (mRenderNode.setSpotShadowColor(color)) {
invalidateViewProperty(true, true);
}
}
+ /**
+ * @return The shadow color set by {@link #setOutlineSpotShadowColor(int)}, or black if nothing
+ * was set
+ */
+ public @ColorInt int getOutlineSpotShadowColor() {
+ return mRenderNode.getSpotShadowColor();
+ }
+
+ /**
+ * Sets the color of the ambient shadow that is drawn when the view has a positive Z or
+ * elevation value.
+ * <p>
+ * By default the shadow color is black. Generally, this color will be opaque so the intensity
+ * of the shadow is consistent between different views with different colors.
+ * <p>
+ * The opacity of the final ambient shadow is a function of the shadow caster height, the
+ * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
+ * {@link android.R.attr#ambientShadowAlpha} theme attribute.
+ *
+ * @attr ref android.R.styleable#View_outlineAmbientShadowColor
+ * @param color The color this View will cast for its elevation shadow.
+ */
+ public void setOutlineAmbientShadowColor(@ColorInt int color) {
+ if (mRenderNode.setAmbientShadowColor(color)) {
+ invalidateViewProperty(true, true);
+ }
+ }
+
+ /**
+ * @return The shadow color set by {@link #setOutlineAmbientShadowColor(int)}, or black if
+ * nothing was set
+ */
+ public @ColorInt int getOutlineAmbientShadowColor() {
+ return mRenderNode.getAmbientShadowColor();
+ }
+
/** @hide */
public void setRevealClip(boolean shouldClip, float x, float y, float radius) {
@@ -26992,6 +27047,8 @@
stream.addProperty("drawing:willNotCacheDrawing", willNotCacheDrawing());
stream.addProperty("drawing:drawingCacheEnabled", isDrawingCacheEnabled());
stream.addProperty("drawing:overlappingRendering", hasOverlappingRendering());
+ stream.addProperty("drawing:outlineAmbientShadowColor", getOutlineAmbientShadowColor());
+ stream.addProperty("drawing:outlineSpotShadowColor", getOutlineSpotShadowColor());
// focus
stream.addProperty("focus:hasFocus", hasFocus());
diff --git a/core/java/android/view/textclassifier/TextClassifierImpl.java b/core/java/android/view/textclassifier/TextClassifierImpl.java
index b03c70d..9f389ba 100644
--- a/core/java/android/view/textclassifier/TextClassifierImpl.java
+++ b/core/java/android/view/textclassifier/TextClassifierImpl.java
@@ -73,7 +73,7 @@
private static final String LOG_TAG = DEFAULT_LOG_TAG;
private static final String MODEL_DIR = "/etc/textclassifier/";
- private static final String MODEL_FILE_REGEX = "textclassifier\\.smartselection\\.(.*)\\.model";
+ private static final String MODEL_FILE_REGEX = "textclassifier\\.(.*)\\.model";
private static final String UPDATED_MODEL_FILE_PATH =
"/data/misc/textclassifier/textclassifier.model";
private static final List<String> ENTITY_TYPES_ALL =
@@ -232,6 +232,7 @@
}
builder.addLink(span.getStartIndex(), span.getEndIndex(), entityScores);
}
+ return builder.build();
} catch (Throwable t) {
// Avoid throwing from this method. Log the error.
Log.e(LOG_TAG, "Error getting links info.", t);
diff --git a/core/java/android/view/textclassifier/TextLinks.java b/core/java/android/view/textclassifier/TextLinks.java
index 670efdd..ede5211 100644
--- a/core/java/android/view/textclassifier/TextLinks.java
+++ b/core/java/android/view/textclassifier/TextLinks.java
@@ -23,13 +23,13 @@
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
-import android.widget.TextView;
import android.text.Spannable;
import android.text.style.ClickableSpan;
import android.text.util.Linkify;
import android.text.util.Linkify.LinkifyMask;
import android.view.View;
import android.view.textclassifier.TextClassifier.EntityType;
+import android.widget.TextView;
import com.android.internal.util.Preconditions;
@@ -351,7 +351,7 @@
* @throws IllegalArgumentException if applyStrategy is not valid
*
* @see #APPLY_STRATEGY_IGNORE
- * @see #APPLY_STRAGETY_REPLACE
+ * @see #APPLY_STRATEGY_REPLACE
*/
public Options setApplyStrategy(@ApplyStrategy int applyStrategy) {
checkValidApplyStrategy(applyStrategy);
@@ -391,8 +391,8 @@
* @return the strategy for resolving conflictswhen applying generated links to text that
* already have links.
*
- * @see #APPLY_STATEGY_IGNORE
- * @see #APPLY_STRAGETY_REPLACE
+ * @see #APPLY_STRATEGY_IGNORE
+ * @see #APPLY_STRATEGY_REPLACE
*/
@ApplyStrategy
public int getApplyStrategy() {
diff --git a/core/java/com/android/internal/app/ResolverListController.java b/core/java/com/android/internal/app/ResolverListController.java
index 2ab2d20..1dfff5e 100644
--- a/core/java/com/android/internal/app/ResolverListController.java
+++ b/core/java/com/android/internal/app/ResolverListController.java
@@ -103,11 +103,14 @@
List<ResolverActivity.ResolvedComponentInfo> resolvedComponents = null;
for (int i = 0, N = intents.size(); i < N; i++) {
final Intent intent = intents.get(i);
- final List<ResolveInfo> infos = mpm.queryIntentActivities(intent,
- PackageManager.MATCH_DEFAULT_ONLY
- | (shouldGetResolvedFilter ? PackageManager.GET_RESOLVED_FILTER : 0)
- | (shouldGetActivityMetadata ? PackageManager.GET_META_DATA : 0)
- | PackageManager.MATCH_INSTANT);
+ int flags = PackageManager.MATCH_DEFAULT_ONLY
+ | (shouldGetResolvedFilter ? PackageManager.GET_RESOLVED_FILTER : 0)
+ | (shouldGetActivityMetadata ? PackageManager.GET_META_DATA : 0);
+ if (intent.isBrowsableWebIntent()
+ || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
+ flags |= PackageManager.MATCH_INSTANT;
+ }
+ final List<ResolveInfo> infos = mpm.queryIntentActivities(intent, flags);
// Remove any activities that are not exported.
int totalSize = infos.size();
for (int j = totalSize - 1; j >= 0 ; j--) {
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 7def876..40dcf25b 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -3880,7 +3880,8 @@
public void addIsolatedUidLocked(int isolatedUid, int appUid) {
mIsolatedUids.put(isolatedUid, appUid);
- StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid, 1);
+ StatsLog.write(StatsLog.ISOLATED_UID_CHANGED, appUid, isolatedUid,
+ StatsLog.ISOLATED_UID_CHANGED__EVENT__CREATED);
final Uid u = getUidStatsLocked(appUid);
u.addIsolatedUid(isolatedUid);
}
@@ -3904,7 +3905,8 @@
*/
public void removeIsolatedUidLocked(int isolatedUid) {
StatsLog.write(
- StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1), isolatedUid, 0);
+ StatsLog.ISOLATED_UID_CHANGED, mIsolatedUids.get(isolatedUid, -1),
+ isolatedUid, StatsLog.ISOLATED_UID_CHANGED__EVENT__REMOVED);
final int idx = mIsolatedUids.indexOfKey(isolatedUid);
if (idx >= 0) {
final int ownerUid = mIsolatedUids.valueAt(idx);
@@ -4255,10 +4257,12 @@
if (wc != null) {
StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
- getPowerManagerWakeLockLevel(type), name, 1);
+ getPowerManagerWakeLockLevel(type), name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
} else {
StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
- getPowerManagerWakeLockLevel(type), name, 1);
+ getPowerManagerWakeLockLevel(type), name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__ACQUIRE);
}
}
}
@@ -4298,10 +4302,12 @@
getUidStatsLocked(uid).noteStopWakeLocked(pid, name, type, elapsedRealtime);
if (wc != null) {
StatsLog.write(StatsLog.WAKELOCK_STATE_CHANGED, wc.getUids(), wc.getTags(),
- getPowerManagerWakeLockLevel(type), name, 0);
+ getPowerManagerWakeLockLevel(type), name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
} else {
StatsLog.write_non_chained(StatsLog.WAKELOCK_STATE_CHANGED, uid, null,
- getPowerManagerWakeLockLevel(type), name, 0);
+ getPowerManagerWakeLockLevel(type), name,
+ StatsLog.WAKELOCK_STATE_CHANGED__STATE__RELEASE);
}
}
}
@@ -4426,7 +4432,8 @@
public void noteLongPartialWakelockStart(String name, String historyName, int uid) {
StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- uid, null, name, historyName, 1);
+ uid, null, name, historyName,
+ StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
uid = mapUid(uid);
noteLongPartialWakeLockStartInternal(name, historyName, uid);
@@ -4439,7 +4446,8 @@
final int uid = mapUid(workSource.get(i));
noteLongPartialWakeLockStartInternal(name, historyName, uid);
StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- workSource.get(i), workSource.getName(i), name, historyName, 1);
+ workSource.get(i), workSource.getName(i), name, historyName,
+ StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
}
final ArrayList<WorkChain> workChains = workSource.getWorkChains();
@@ -4450,7 +4458,8 @@
noteLongPartialWakeLockStartInternal(name, historyName, uid);
StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), name, historyName, 1);
+ workChain.getUids(), workChain.getTags(), name, historyName,
+ StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__ON);
}
}
}
@@ -4470,8 +4479,8 @@
}
public void noteLongPartialWakelockFinish(String name, String historyName, int uid) {
- StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- uid, null, name, historyName, 0);
+ StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED, uid, null,
+ name, historyName, StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
uid = mapUid(uid);
noteLongPartialWakeLockFinishInternal(name, historyName, uid);
@@ -4484,7 +4493,8 @@
final int uid = mapUid(workSource.get(i));
noteLongPartialWakeLockFinishInternal(name, historyName, uid);
StatsLog.write_non_chained(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- workSource.get(i), workSource.getName(i), name, historyName, 0);
+ workSource.get(i), workSource.getName(i), name, historyName,
+ StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
}
final ArrayList<WorkChain> workChains = workSource.getWorkChains();
@@ -4494,7 +4504,8 @@
final int uid = workChain.getAttributionUid();
noteLongPartialWakeLockFinishInternal(name, historyName, uid);
StatsLog.write(StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), name, historyName, 0);
+ workChain.getUids(), workChain.getTags(), name, historyName,
+ StatsLog.LONG_PARTIAL_WAKELOCK_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -4518,7 +4529,8 @@
long deltaUptime = uptimeMs - mLastWakeupUptimeMs;
SamplingTimer timer = getWakeupReasonTimerLocked(mLastWakeupReason);
timer.add(deltaUptime * 1000, 1); // time in in microseconds
- StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason, deltaUptime * 1000);
+ StatsLog.write(StatsLog.KERNEL_WAKEUP_REPORTED, mLastWakeupReason,
+ /* duration_usec */ deltaUptime * 1000);
mLastWakeupReason = null;
}
}
@@ -4659,10 +4671,12 @@
mGpsNesting++;
if (workChain == null) {
- StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null, 1);
+ StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
+ StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
} else {
StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 1);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.GPS_SCAN_STATE_CHANGED__STATE__ON);
}
getUidStatsLocked(uid).noteStartGps(elapsedRealtime);
@@ -4683,10 +4697,11 @@
}
if (workChain == null) {
- StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null, 0);
+ StatsLog.write_non_chained(StatsLog.GPS_SCAN_STATE_CHANGED, uid, null,
+ StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
} else {
StatsLog.write(StatsLog.GPS_SCAN_STATE_CHANGED, workChain.getUids(),
- workChain.getTags(), 0);
+ workChain.getTags(), StatsLog.GPS_SCAN_STATE_CHANGED__STATE__OFF);
}
getUidStatsLocked(uid).noteStopGps(elapsedRealtime);
@@ -4941,7 +4956,9 @@
mPowerSaveModeEnabledTimer.stopRunningLocked(elapsedRealtime);
}
addHistoryRecordLocked(elapsedRealtime, uptime);
- StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ? 1 : 0);
+ StatsLog.write(StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED, enabled ?
+ StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__ON :
+ StatsLog.BATTERY_SAVER_MODE_STATE_CHANGED__STATE__OFF);
}
}
@@ -5545,16 +5562,19 @@
if (workChain != null) {
StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 1);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
if (isUnoptimized) {
StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 1);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
}
} else {
- StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 1);
+ StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
+ StatsLog.BLE_SCAN_STATE_CHANGED__STATE__ON);
if (isUnoptimized) {
StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
- 1);
+ StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__ON);
}
}
@@ -5594,16 +5614,19 @@
if (workChain != null) {
StatsLog.write(
- StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(), 0);
+ StatsLog.BLE_SCAN_STATE_CHANGED, workChain.getUids(), workChain.getTags(),
+ StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
if (isUnoptimized) {
StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 0);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
}
} else {
- StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null, 0);
+ StatsLog.write_non_chained(StatsLog.BLE_SCAN_STATE_CHANGED, uid, null,
+ StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
if (isUnoptimized) {
StatsLog.write_non_chained(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED, uid, null,
- 0);
+ StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
}
}
@@ -5656,7 +5679,8 @@
for (int j = 0; j < allWorkChains.size(); ++j) {
StatsLog.write(StatsLog.BLE_SCAN_STATE_CHANGED,
allWorkChains.get(j).getUids(),
- allWorkChains.get(j).getTags(), 0);
+ allWorkChains.get(j).getTags(),
+ StatsLog.BLE_SCAN_STATE_CHANGED__STATE__OFF);
}
allWorkChains.clear();
}
@@ -5666,7 +5690,8 @@
for (int j = 0; j < unoptimizedWorkChains.size(); ++j) {
StatsLog.write(StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED,
unoptimizedWorkChains.get(j).getUids(),
- unoptimizedWorkChains.get(j).getTags(), 0);
+ unoptimizedWorkChains.get(j).getTags(),
+ StatsLog.BLE_UNOPTIMIZED_SCAN_STATE_CHANGED__STATE__OFF);
}
unoptimizedWorkChains.clear();
}
@@ -6011,7 +6036,8 @@
for (int i=0; i<N; i++) {
final int uid = mapUid(ws.get(i));
noteFullWifiLockAcquiredLocked(uid);
- StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 1);
+ StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
+ StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
}
final List<WorkChain> workChains = ws.getWorkChains();
@@ -6021,7 +6047,8 @@
final int uid = mapUid(workChain.getAttributionUid());
noteFullWifiLockAcquiredLocked(uid);
StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 1);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__ON);
}
}
}
@@ -6031,7 +6058,8 @@
for (int i=0; i<N; i++) {
final int uid = mapUid(ws.get(i));
noteFullWifiLockReleasedLocked(uid);
- StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i), 0);
+ StatsLog.write_non_chained(StatsLog.WIFI_LOCK_STATE_CHANGED, ws.get(i), ws.getName(i),
+ StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
}
final List<WorkChain> workChains = ws.getWorkChains();
@@ -6041,7 +6069,8 @@
final int uid = mapUid(workChain.getAttributionUid());
noteFullWifiLockReleasedLocked(uid);
StatsLog.write(StatsLog.WIFI_LOCK_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 0);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.WIFI_LOCK_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -6052,7 +6081,7 @@
final int uid = mapUid(ws.get(i));
noteWifiScanStartedLocked(uid);
StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
- 1);
+ StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
}
final List<WorkChain> workChains = ws.getWorkChains();
@@ -6062,7 +6091,7 @@
final int uid = mapUid(workChain.getAttributionUid());
noteWifiScanStartedLocked(uid);
StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED, workChain.getUids(),
- workChain.getTags(), 1);
+ workChain.getTags(), StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__ON);
}
}
}
@@ -6073,7 +6102,7 @@
final int uid = mapUid(ws.get(i));
noteWifiScanStoppedLocked(uid);
StatsLog.write_non_chained(StatsLog.WIFI_SCAN_STATE_CHANGED, ws.get(i), ws.getName(i),
- 0);
+ StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
}
final List<WorkChain> workChains = ws.getWorkChains();
@@ -6083,7 +6112,8 @@
final int uid = mapUid(workChain.getAttributionUid());
noteWifiScanStoppedLocked(uid);
StatsLog.write(StatsLog.WIFI_SCAN_STATE_CHANGED,
- workChain.getUids(), workChain.getTags(), 0);
+ workChain.getUids(), workChain.getTags(),
+ StatsLog.WIFI_SCAN_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -7035,7 +7065,8 @@
}
mWifiMulticastTimer.startRunningLocked(elapsedRealtimeMs);
StatsLog.write_non_chained(
- StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 1);
+ StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
+ StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__ON);
}
}
@@ -7045,7 +7076,8 @@
mWifiMulticastEnabled = false;
mWifiMulticastTimer.stopRunningLocked(elapsedRealtimeMs);
StatsLog.write_non_chained(
- StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED, getUid(), null,
+ StatsLog.WIFI_MULTICAST_LOCK_STATE_CHANGED__STATE__OFF);
}
}
@@ -7098,14 +7130,16 @@
public void noteAudioTurnedOnLocked(long elapsedRealtimeMs) {
createAudioTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 1);
+ StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
+ StatsLog.AUDIO_STATE_CHANGED__STATE__ON);
}
public void noteAudioTurnedOffLocked(long elapsedRealtimeMs) {
if (mAudioTurnedOnTimer != null) {
mAudioTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
if (!mAudioTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
- StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
+ StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -7113,7 +7147,8 @@
public void noteResetAudioLocked(long elapsedRealtimeMs) {
if (mAudioTurnedOnTimer != null) {
mAudioTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.write_non_chained(StatsLog.AUDIO_STATE_CHANGED, getUid(), null,
+ StatsLog.AUDIO_STATE_CHANGED__STATE__OFF);
}
}
@@ -7127,7 +7162,8 @@
public void noteVideoTurnedOnLocked(long elapsedRealtimeMs) {
createVideoTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null, 1);
+ StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
+ StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__ON);
}
public void noteVideoTurnedOffLocked(long elapsedRealtimeMs) {
@@ -7135,7 +7171,7 @@
mVideoTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
if (!mVideoTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(),
- null, 0);
+ null, StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
}
}
}
@@ -7144,7 +7180,7 @@
if (mVideoTurnedOnTimer != null) {
mVideoTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
StatsLog.write_non_chained(StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED, getUid(), null,
- 0);
+ StatsLog.MEDIA_CODEC_ACTIVITY_CHANGED__STATE__OFF);
}
}
@@ -7158,7 +7194,8 @@
public void noteFlashlightTurnedOnLocked(long elapsedRealtimeMs) {
createFlashlightTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,1);
+ StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
+ StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__ON);
}
public void noteFlashlightTurnedOffLocked(long elapsedRealtimeMs) {
@@ -7166,7 +7203,7 @@
mFlashlightTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
if (!mFlashlightTurnedOnTimer.isRunningLocked()) {
StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
- 0);
+ StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -7174,7 +7211,8 @@
public void noteResetFlashlightLocked(long elapsedRealtimeMs) {
if (mFlashlightTurnedOnTimer != null) {
mFlashlightTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.write_non_chained(StatsLog.FLASHLIGHT_STATE_CHANGED, getUid(), null,
+ StatsLog.FLASHLIGHT_STATE_CHANGED__STATE__OFF);
}
}
@@ -7188,14 +7226,16 @@
public void noteCameraTurnedOnLocked(long elapsedRealtimeMs) {
createCameraTurnedOnTimerLocked().startRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 1);
+ StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
+ StatsLog.CAMERA_STATE_CHANGED__STATE__ON);
}
public void noteCameraTurnedOffLocked(long elapsedRealtimeMs) {
if (mCameraTurnedOnTimer != null) {
mCameraTurnedOnTimer.stopRunningLocked(elapsedRealtimeMs);
if (!mCameraTurnedOnTimer.isRunningLocked()) { // only tell statsd if truly stopped
- StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
+ StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -7203,7 +7243,8 @@
public void noteResetCameraLocked(long elapsedRealtimeMs) {
if (mCameraTurnedOnTimer != null) {
mCameraTurnedOnTimer.stopAllRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null, 0);
+ StatsLog.write_non_chained(StatsLog.CAMERA_STATE_CHANGED, getUid(), null,
+ StatsLog.CAMERA_STATE_CHANGED__STATE__OFF);
}
}
@@ -9777,7 +9818,8 @@
DualTimer t = mSyncStats.startObject(name);
if (t != null) {
t.startRunningLocked(elapsedRealtimeMs);
- StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 1);
+ StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
+ StatsLog.SYNC_STATE_CHANGED__STATE__ON);
}
}
@@ -9786,7 +9828,8 @@
if (t != null) {
t.stopRunningLocked(elapsedRealtimeMs);
if (!t.isRunningLocked()) { // only tell statsd if truly stopped
- StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name, 0);
+ StatsLog.write_non_chained(StatsLog.SYNC_STATE_CHANGED, getUid(), null, name,
+ StatsLog.SYNC_STATE_CHANGED__STATE__OFF);
}
}
}
@@ -9796,7 +9839,7 @@
if (t != null) {
t.startRunningLocked(elapsedRealtimeMs);
StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
- name, 1);
+ name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__STARTED);
}
}
@@ -9806,7 +9849,7 @@
t.stopRunningLocked(elapsedRealtimeMs);
if (!t.isRunningLocked()) { // only tell statsd if truly stopped
StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED, getUid(), null,
- name, 0);
+ name, StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__FINISHED);
}
}
if (mBsi.mOnBatteryTimeBase.isRunning()) {
@@ -9919,7 +9962,7 @@
t.startRunningLocked(elapsedRealtimeMs);
if (sensor != Sensor.GPS) {
StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null, sensor,
- 1);
+ StatsLog.SENSOR_STATE_CHANGED__STATE__ON);
}
}
@@ -9930,7 +9973,7 @@
t.stopRunningLocked(elapsedRealtimeMs);
if (sensor != Sensor.GPS) {
StatsLog.write_non_chained(StatsLog.SENSOR_STATE_CHANGED, getUid(), null,
- sensor, 0);
+ sensor, StatsLog.SENSOR_STATE_CHANGED__STATE__OFF);
}
}
}
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index 95bc352..eadefc9 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -86,6 +86,7 @@
import android.widget.FrameLayout;
import android.widget.PopupWindow;
+import static android.app.WindowConfiguration.PINNED_WINDOWING_MODE_ELEVATION_IN_DIP;
import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
@@ -2216,7 +2217,7 @@
elevation = dipToPx(elevation);
mElevationAdjustedForStack = true;
} else if (windowingMode == WINDOWING_MODE_PINNED) {
- elevation = dipToPx(DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP);
+ elevation = dipToPx(PINNED_WINDOWING_MODE_ELEVATION_IN_DIP);
mElevationAdjustedForStack = true;
} else {
mElevationAdjustedForStack = false;
diff --git a/core/java/com/android/internal/util/FileRotator.java b/core/java/com/android/internal/util/FileRotator.java
index 71550be..f8885a2 100644
--- a/core/java/com/android/internal/util/FileRotator.java
+++ b/core/java/com/android/internal/util/FileRotator.java
@@ -160,7 +160,7 @@
final File file = new File(mBasePath, name);
final FileInputStream is = new FileInputStream(file);
try {
- Streams.copy(is, zos);
+ FileUtils.copy(is, zos);
} finally {
IoUtils.closeQuietly(is);
}
diff --git a/core/java/com/android/internal/widget/LockPatternView.java b/core/java/com/android/internal/widget/LockPatternView.java
index 32a7a2d..7a248f2 100644
--- a/core/java/com/android/internal/widget/LockPatternView.java
+++ b/core/java/com/android/internal/widget/LockPatternView.java
@@ -118,6 +118,7 @@
private float mInProgressY = -1;
private long mAnimatingPeriodStart;
+ private long[] mLineFadeStart = new long[9];
private DisplayMode mPatternDisplayMode = DisplayMode.Correct;
private boolean mInputEnabled = true;
@@ -596,12 +597,14 @@
}
/**
- * Clear the pattern lookup table.
+ * Clear the pattern lookup table. Also reset the line fade start times for
+ * the next attempt.
*/
private void clearPatternDrawLookup() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
mPatternDrawLookup[i][j] = false;
+ mLineFadeStart[i+j] = 0;
}
}
}
@@ -1136,7 +1139,8 @@
boolean anyCircles = false;
float lastX = 0f;
float lastY = 0f;
- for (int i = 0; i < count; i++) {
+ long elapsedRealtime = SystemClock.elapsedRealtime();
+ for (int i = 0; i < count; i++) {
Cell cell = pattern.get(i);
// only draw the part of the pattern stored in
@@ -1147,16 +1151,26 @@
}
anyCircles = true;
+ if (mLineFadeStart[i] == 0) {
+ mLineFadeStart[i] = SystemClock.elapsedRealtime();
+ }
+
float centerX = getCenterXForColumn(cell.column);
float centerY = getCenterYForRow(cell.row);
if (i != 0) {
+ // Set this line segment to slowly fade over the next second.
+ int lineFadeVal = (int) Math.min((elapsedRealtime -
+ mLineFadeStart[i])/2f, 255f);
+
CellState state = mCellStates[cell.row][cell.column];
currentPath.rewind();
currentPath.moveTo(lastX, lastY);
if (state.lineEndX != Float.MIN_VALUE && state.lineEndY != Float.MIN_VALUE) {
currentPath.lineTo(state.lineEndX, state.lineEndY);
+ mPathPaint.setAlpha((int) 255 - lineFadeVal );
} else {
currentPath.lineTo(centerX, centerY);
+ mPathPaint.setAlpha((int) 255 - lineFadeVal );
}
canvas.drawPath(currentPath, mPathPaint);
}
diff --git a/core/jni/Android.bp b/core/jni/Android.bp
index 93f95c6..33f80ce 100644
--- a/core/jni/Android.bp
+++ b/core/jni/Android.bp
@@ -164,6 +164,7 @@
"android_media_DeviceCallback.cpp",
"android_media_JetPlayer.cpp",
"android_media_MediaMetricsJNI.cpp",
+ "android_media_MicrophoneInfo.cpp",
"android_media_RemoteDisplay.cpp",
"android_media_ToneGenerator.cpp",
"android_hardware_Camera.cpp",
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index bf7a7794..d202173 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -104,6 +104,7 @@
extern int register_android_media_AudioRecord(JNIEnv *env);
extern int register_android_media_AudioSystem(JNIEnv *env);
extern int register_android_media_AudioTrack(JNIEnv *env);
+extern int register_android_media_MicrophoneInfo(JNIEnv *env);
extern int register_android_media_JetPlayer(JNIEnv *env);
extern int register_android_media_ToneGenerator(JNIEnv *env);
@@ -765,18 +766,17 @@
/*
* Enable debugging only for apps forked from zygote.
- * Set suspend=y to pause during VM init and use android ADB transport.
*/
if (zygote) {
+ // Set the JDWP provider and required arguments. By default let the runtime choose how JDWP is
+ // implemented. When this is not set the runtime defaults to not allowing JDWP.
addOption("-XjdwpOptions:suspend=n,server=y");
+ parseRuntimeOption("dalvik.vm.jdwp-provider",
+ jdwpProviderBuf,
+ "-XjdwpProvider:",
+ "default");
}
- // Set the JDWP provider. By default let the runtime choose.
- parseRuntimeOption("dalvik.vm.jdwp-provider",
- jdwpProviderBuf,
- "-XjdwpProvider:",
- "default");
-
parseRuntimeOption("dalvik.vm.lockprof.threshold",
lockProfThresholdBuf,
"-Xlockprofthreshold:");
@@ -1461,6 +1461,7 @@
REG_JNI(register_android_media_AudioSystem),
REG_JNI(register_android_media_AudioTrack),
REG_JNI(register_android_media_JetPlayer),
+ REG_JNI(register_android_media_MicrophoneInfo),
REG_JNI(register_android_media_RemoteDisplay),
REG_JNI(register_android_media_ToneGenerator),
diff --git a/core/jni/android/graphics/AnimatedImageDrawable.cpp b/core/jni/android/graphics/AnimatedImageDrawable.cpp
index c88cf5c..ba56d59 100644
--- a/core/jni/android/graphics/AnimatedImageDrawable.cpp
+++ b/core/jni/android/graphics/AnimatedImageDrawable.cpp
@@ -26,10 +26,11 @@
#include <SkPictureRecorder.h>
#include <hwui/AnimatedImageDrawable.h>
#include <hwui/Canvas.h>
+#include <utils/Looper.h>
using namespace android;
-static jmethodID gAnimatedImageDrawable_postOnAnimationEndMethodID;
+static jmethodID gAnimatedImageDrawable_onAnimationEndMethodID;
// Note: jpostProcess holds a handle to the ImageDecoder.
static jlong AnimatedImageDrawable_nCreate(JNIEnv* env, jobject /*clazz*/,
@@ -123,9 +124,9 @@
return drawable->start();
}
-static void AnimatedImageDrawable_nStop(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
+static jboolean AnimatedImageDrawable_nStop(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
auto* drawable = reinterpret_cast<AnimatedImageDrawable*>(nativePtr);
- drawable->stop();
+ return drawable->stop();
}
// Java's LOOP_INFINITE relies on this being the same.
@@ -137,33 +138,63 @@
drawable->setRepetitionCount(loopCount);
}
-class JniAnimationEndListener : public OnAnimationEndListener {
+class InvokeListener : public MessageHandler {
public:
- JniAnimationEndListener(JNIEnv* env, jobject javaObject) {
+ InvokeListener(JNIEnv* env, jobject javaObject) {
LOG_ALWAYS_FATAL_IF(env->GetJavaVM(&mJvm) != JNI_OK);
- mJavaObject = env->NewGlobalRef(javaObject);
+ // Hold a weak reference to break a cycle that would prevent GC.
+ mWeakRef = env->NewWeakGlobalRef(javaObject);
}
- ~JniAnimationEndListener() override {
+ ~InvokeListener() override {
auto* env = get_env_or_die(mJvm);
- env->DeleteGlobalRef(mJavaObject);
+ env->DeleteWeakGlobalRef(mWeakRef);
}
- void onAnimationEnd() override {
+ virtual void handleMessage(const Message&) override {
auto* env = get_env_or_die(mJvm);
- env->CallVoidMethod(mJavaObject, gAnimatedImageDrawable_postOnAnimationEndMethodID);
+ jobject localRef = env->NewLocalRef(mWeakRef);
+ if (localRef) {
+ env->CallVoidMethod(localRef, gAnimatedImageDrawable_onAnimationEndMethodID);
+ }
}
private:
JavaVM* mJvm;
- jobject mJavaObject;
+ jweak mWeakRef;
+};
+
+class JniAnimationEndListener : public OnAnimationEndListener {
+public:
+ JniAnimationEndListener(sp<Looper>&& looper, JNIEnv* env, jobject javaObject) {
+ mListener = new InvokeListener(env, javaObject);
+ mLooper = std::move(looper);
+ }
+
+ void onAnimationEnd() override { mLooper->sendMessage(mListener, 0); }
+
+private:
+ sp<InvokeListener> mListener;
+ sp<Looper> mLooper;
};
static void AnimatedImageDrawable_nSetOnAnimationEndListener(JNIEnv* env, jobject /*clazz*/,
jlong nativePtr, jobject jdrawable) {
auto* drawable = reinterpret_cast<AnimatedImageDrawable*>(nativePtr);
- drawable->setOnAnimationEndListener(std::unique_ptr<OnAnimationEndListener>(
- new JniAnimationEndListener(env, jdrawable)));
+ if (!jdrawable) {
+ drawable->setOnAnimationEndListener(nullptr);
+ } else {
+ sp<Looper> looper = Looper::getForThread();
+ if (!looper.get()) {
+ doThrowISE(env,
+ "Must set AnimatedImageDrawable's AnimationCallback on a thread with a "
+ "looper!");
+ return;
+ }
+
+ drawable->setOnAnimationEndListener(
+ std::make_unique<JniAnimationEndListener>(std::move(looper), env, jdrawable));
+ }
}
static long AnimatedImageDrawable_nNativeByteSize(JNIEnv* env, jobject /*clazz*/, jlong nativePtr) {
@@ -186,7 +217,7 @@
{ "nSetColorFilter", "(JJ)V", (void*) AnimatedImageDrawable_nSetColorFilter },
{ "nIsRunning", "(J)Z", (void*) AnimatedImageDrawable_nIsRunning },
{ "nStart", "(J)Z", (void*) AnimatedImageDrawable_nStart },
- { "nStop", "(J)V", (void*) AnimatedImageDrawable_nStop },
+ { "nStop", "(J)Z", (void*) AnimatedImageDrawable_nStop },
{ "nSetLoopCount", "(JI)V", (void*) AnimatedImageDrawable_nSetLoopCount },
{ "nSetOnAnimationEndListener", "(JLandroid/graphics/drawable/AnimatedImageDrawable;)V", (void*) AnimatedImageDrawable_nSetOnAnimationEndListener },
{ "nNativeByteSize", "(J)J", (void*) AnimatedImageDrawable_nNativeByteSize },
@@ -195,7 +226,7 @@
int register_android_graphics_drawable_AnimatedImageDrawable(JNIEnv* env) {
jclass animatedImageDrawable_class = FindClassOrDie(env, "android/graphics/drawable/AnimatedImageDrawable");
- gAnimatedImageDrawable_postOnAnimationEndMethodID = GetMethodIDOrDie(env, animatedImageDrawable_class, "postOnAnimationEnd", "()V");
+ gAnimatedImageDrawable_onAnimationEndMethodID = GetMethodIDOrDie(env, animatedImageDrawable_class, "onAnimationEnd", "()V");
return android::RegisterMethodsOrDie(env, "android/graphics/drawable/AnimatedImageDrawable",
gAnimatedImageDrawableMethods, NELEM(gAnimatedImageDrawableMethods));
diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp
index ebd16c7..375d68b 100644
--- a/core/jni/android_media_AudioRecord.cpp
+++ b/core/jni/android_media_AudioRecord.cpp
@@ -25,6 +25,8 @@
#include <utils/Log.h>
#include <media/AudioRecord.h>
+#include <media/MicrophoneInfo.h>
+#include <vector>
#include <nativehelper/ScopedUtfChars.h>
@@ -32,6 +34,7 @@
#include "android_media_AudioErrors.h"
#include "android_media_DeviceCallback.h"
#include "android_media_MediaMetricsJNI.h"
+#include "android_media_MicrophoneInfo.h"
// ----------------------------------------------------------------------------
@@ -41,6 +44,11 @@
static const char* const kClassPathName = "android/media/AudioRecord";
static const char* const kAudioAttributesClassPathName = "android/media/AudioAttributes";
+static jclass gArrayListClass;
+static struct {
+ jmethodID add;
+} gArrayListMethods;
+
struct audio_record_fields_t {
// these fields provide access from C++ to the...
jmethodID postNativeEventInJava; //... event post callback method
@@ -785,6 +793,46 @@
}
// ----------------------------------------------------------------------------
+static jint android_media_AudioRecord_get_active_microphones(JNIEnv *env,
+ jobject thiz, jobject jActiveMicrophones) {
+ if (jActiveMicrophones == NULL) {
+ ALOGE("jActiveMicrophones is null");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+ if (!env->IsInstanceOf(jActiveMicrophones, gArrayListClass)) {
+ ALOGE("getActiveMicrophones not an arraylist");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+
+ sp<AudioRecord> lpRecorder = getAudioRecord(env, thiz);
+ if (lpRecorder == NULL) {
+ jniThrowException(env, "java/lang/IllegalStateException",
+ "Unable to retrieve AudioRecord pointer for getActiveMicrophones()");
+ return (jint)AUDIO_JAVA_ERROR;
+ }
+
+ jint jStatus = AUDIO_JAVA_SUCCESS;
+ std::vector<media::MicrophoneInfo> activeMicrophones;
+ status_t status = lpRecorder->getActiveMicrophones(&activeMicrophones);
+ if (status != NO_ERROR) {
+ ALOGE_IF(status != NO_ERROR, "AudioRecord::getActiveMicrophones error %d", status);
+ jStatus = nativeToJavaStatus(status);
+ return jStatus;
+ }
+
+ for (size_t i = 0; i < activeMicrophones.size(); i++) {
+ jobject jMicrophoneInfo;
+ jStatus = convertMicrophoneInfoFromNative(env, &jMicrophoneInfo, &activeMicrophones[i]);
+ if (jStatus != AUDIO_JAVA_SUCCESS) {
+ return jStatus;
+ }
+ env->CallBooleanMethod(jActiveMicrophones, gArrayListMethods.add, jMicrophoneInfo);
+ env->DeleteLocalRef(jMicrophoneInfo);
+ }
+ return jStatus;
+}
+
+// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
static const JNINativeMethod gMethods[] = {
// name, signature, funcPtr
@@ -824,6 +872,8 @@
(void *)android_media_AudioRecord_disableDeviceCallback},
{"native_get_timestamp", "(Landroid/media/AudioTimestamp;I)I",
(void *)android_media_AudioRecord_get_timestamp},
+ {"native_get_active_microphones", "(Ljava/util/ArrayList;)I",
+ (void *)android_media_AudioRecord_get_active_microphones},
};
// field names found in android/media/AudioRecord.java
@@ -873,6 +923,10 @@
javaAudioTimestampFields.fieldNanoTime =
GetFieldIDOrDie(env, audioTimestampClass, "nanoTime", "J");
+ jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
+ gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
+ gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
+
return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
}
diff --git a/core/jni/android_media_AudioSystem.cpp b/core/jni/android_media_AudioSystem.cpp
index 376a797..adaff1f 100644
--- a/core/jni/android_media_AudioSystem.cpp
+++ b/core/jni/android_media_AudioSystem.cpp
@@ -21,17 +21,20 @@
#include <utils/Log.h>
#include <sstream>
+#include <vector>
#include <jni.h>
#include <nativehelper/JNIHelp.h>
#include "core_jni_helpers.h"
#include <media/AudioSystem.h>
#include <media/AudioPolicy.h>
+#include <media/MicrophoneInfo.h>
#include <nativehelper/ScopedLocalRef.h>
#include <system/audio.h>
#include <system/audio_policy.h>
#include "android_media_AudioFormat.h"
#include "android_media_AudioErrors.h"
+#include "android_media_MicrophoneInfo.h"
// ----------------------------------------------------------------------------
@@ -143,7 +146,6 @@
jfieldID mSource;
} gAudioAttributesFields;
-
static const char* const kEventHandlerClassPathName =
"android/media/AudioPortEventHandler";
static struct {
@@ -1158,7 +1160,6 @@
return jStatus;
}
-
static jint
android_media_AudioSystem_listAudioPorts(JNIEnv *env, jobject clazz,
jobject jPorts, jintArray jGeneration)
@@ -1789,6 +1790,45 @@
return AudioSystem::isOffloadSupported(format);
}
+static jint
+android_media_AudioSystem_getMicrophones(JNIEnv *env, jobject thiz, jobject jMicrophonesInfo)
+{
+ ALOGV("getMicrophones");
+
+ if (jMicrophonesInfo == NULL) {
+ ALOGE("jMicrophonesInfo NULL MicrophoneInfo ArrayList");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+ if (!env->IsInstanceOf(jMicrophonesInfo, gArrayListClass)) {
+ ALOGE("getMicrophones not an arraylist");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+
+ jint jStatus;
+ std::vector<media::MicrophoneInfo> microphones;
+ status_t status = AudioSystem::getMicrophones(µphones);
+ if (status != NO_ERROR) {
+ ALOGE_IF(status != NO_ERROR, "AudioSystem::getMicrophones error %d", status);
+ jStatus = nativeToJavaStatus(status);
+ return jStatus;
+ }
+ if (microphones.size() == 0) {
+ jStatus = (jint)AUDIO_JAVA_SUCCESS;
+ return jStatus;
+ }
+ for (size_t i = 0; i < microphones.size(); i++) {
+ jobject jMicrophoneInfo;
+ jStatus = convertMicrophoneInfoFromNative(env, &jMicrophoneInfo, µphones[i]);
+ if (jStatus != AUDIO_JAVA_SUCCESS) {
+ return jStatus;
+ }
+ env->CallBooleanMethod(jMicrophonesInfo, gArrayListMethods.add, jMicrophoneInfo);
+ env->DeleteLocalRef(jMicrophoneInfo);
+ }
+
+ return jStatus;
+}
+
// ----------------------------------------------------------------------------
static const JNINativeMethod gMethods[] = {
@@ -1843,6 +1883,7 @@
{"systemReady", "()I", (void *)android_media_AudioSystem_systemReady},
{"getStreamVolumeDB", "(III)F", (void *)android_media_AudioSystem_getStreamVolumeDB},
{"native_is_offload_supported", "(IIII)Z", (void *)android_media_AudioSystem_isOffloadSupported},
+ {"getMicrophones", "(Ljava/util/ArrayList;)I", (void *)android_media_AudioSystem_getMicrophones},
};
diff --git a/core/jni/android_media_AudioTrack.cpp b/core/jni/android_media_AudioTrack.cpp
index afbc579..61a22c1 100644
--- a/core/jni/android_media_AudioTrack.cpp
+++ b/core/jni/android_media_AudioTrack.cpp
@@ -1262,6 +1262,18 @@
return VolumeShaperHelper::convertStateToJobject(env, gVolumeShaperFields, state);
}
+static int android_media_AudioTrack_setPresentation(
+ JNIEnv *env, jobject thiz, jint presentationId, jint programId) {
+ sp<AudioTrack> lpTrack = getAudioTrack(env, thiz);
+ if (lpTrack == NULL) {
+ jniThrowException(env, "java/lang/IllegalStateException",
+ "AudioTrack not initialized");
+ return (jint)AUDIO_JAVA_ERROR;
+ }
+
+ return (jint)lpTrack->selectPresentation((int)presentationId, (int)programId);
+}
+
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
static const JNINativeMethod gMethods[] = {
@@ -1333,6 +1345,7 @@
{"native_getVolumeShaperState",
"(I)Landroid/media/VolumeShaper$State;",
(void *)android_media_AudioTrack_get_volume_shaper_state},
+ {"native_setPresentation", "(II)I", (void *)android_media_AudioTrack_setPresentation},
};
diff --git a/core/jni/android_media_MicrophoneInfo.cpp b/core/jni/android_media_MicrophoneInfo.cpp
new file mode 100644
index 0000000..9198cbe
--- /dev/null
+++ b/core/jni/android_media_MicrophoneInfo.cpp
@@ -0,0 +1,187 @@
+/*
+ * 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_media_MicrophoneInfo.h"
+#include "android_media_AudioErrors.h"
+#include "core_jni_helpers.h"
+
+using namespace android;
+
+static jclass gArrayListClass;
+static jmethodID gArrayListCstor;
+static struct {
+ jmethodID add;
+} gArrayListMethods;
+
+static jclass gFloatClass;
+static jmethodID gFloatCstor;
+
+static jclass gFloatArrayClass;
+
+static jclass gIntegerClass;
+static jmethodID gIntegerCstor;
+
+static jclass gMicrophoneInfoClass;
+static jmethodID gMicrophoneInfoCstor;
+
+static jclass gMicrophoneInfoCoordinateClass;
+static jmethodID gMicrophoneInfoCoordinateCstor;
+
+static jclass gPairClass;
+static jmethodID gPairCstor;
+
+namespace android {
+
+jint convertMicrophoneInfoFromNative(JNIEnv *env, jobject *jMicrophoneInfo,
+ const media::MicrophoneInfo *microphoneInfo)
+{
+ jint jStatus = (jint)AUDIO_JAVA_SUCCESS;
+ jstring jDeviceId = NULL;
+ jstring jAddress = NULL;
+ jobject jGeometricLocation = NULL;
+ jobject jOrientation = NULL;
+ jobject jFrequencyResponses = NULL;
+ jobject jChannelMappings = NULL;
+
+ jDeviceId = env->NewStringUTF(String8(microphoneInfo->getDeviceId()).string());
+ jAddress = env->NewStringUTF(String8(microphoneInfo->getAddress()).string());
+ if (microphoneInfo->getGeometricLocation().size() != 3 ||
+ microphoneInfo->getOrientation().size() != 3) {
+ jStatus = nativeToJavaStatus(BAD_VALUE);
+ goto exit;
+ }
+ jGeometricLocation = env->NewObject(gMicrophoneInfoCoordinateClass,
+ gMicrophoneInfoCoordinateCstor,
+ NULL,
+ microphoneInfo->getGeometricLocation()[0],
+ microphoneInfo->getGeometricLocation()[1],
+ microphoneInfo->getGeometricLocation()[2]);
+ jOrientation = env->NewObject(gMicrophoneInfoCoordinateClass,
+ gMicrophoneInfoCoordinateCstor,
+ NULL,
+ microphoneInfo->getOrientation()[0],
+ microphoneInfo->getOrientation()[1],
+ microphoneInfo->getOrientation()[2]);
+ // Create a list of Pair for frequency response.
+ if (microphoneInfo->getFrequencyResponses().size() != 2 ||
+ microphoneInfo->getFrequencyResponses()[0].size() !=
+ microphoneInfo->getFrequencyResponses()[1].size()) {
+ jStatus = nativeToJavaStatus(BAD_VALUE);
+ goto exit;
+ }
+ jFrequencyResponses = env->NewObject(gArrayListClass, gArrayListCstor);
+ for (size_t i = 0; i < microphoneInfo->getFrequencyResponses()[0].size(); i++) {
+ jobject jFrequency = env->NewObject(gFloatClass, gFloatCstor,
+ microphoneInfo->getFrequencyResponses()[0][i]);
+ jobject jResponse = env->NewObject(gFloatClass, gFloatCstor,
+ microphoneInfo->getFrequencyResponses()[1][i]);
+ jobject jFrequencyResponse = env->NewObject(gPairClass, gPairCstor, jFrequency, jResponse);
+ env->CallBooleanMethod(jFrequencyResponses, gArrayListMethods.add, jFrequencyResponse);
+ env->DeleteLocalRef(jFrequency);
+ env->DeleteLocalRef(jResponse);
+ env->DeleteLocalRef(jFrequencyResponse);
+ }
+ // Create a list of Pair for channel mapping.
+ if (microphoneInfo->getChannelMapping().size() != AUDIO_CHANNEL_COUNT_MAX) {
+ jStatus = nativeToJavaStatus(BAD_VALUE);
+ goto exit;
+ }
+ jChannelMappings = env->NewObject(gArrayListClass, gArrayListCstor);
+ for (size_t i = 0; i < microphoneInfo->getChannelMapping().size(); i++) {
+ int channelMappingType = microphoneInfo->getChannelMapping()[i];
+ if (channelMappingType != AUDIO_MICROPHONE_CHANNEL_MAPPING_UNUSED) {
+ jobject jChannelIndex = env->NewObject(gIntegerClass, gIntegerCstor, i);
+ jobject jChannelMappingType = env->NewObject(gIntegerClass, gIntegerCstor,
+ channelMappingType);
+ jobject jChannelMapping = env->NewObject(gPairClass, gPairCstor,
+ jChannelIndex, jChannelMappingType);
+ env->CallBooleanMethod(jChannelMappings, gArrayListMethods.add, jChannelMapping);
+ env->DeleteLocalRef(jChannelIndex);
+ env->DeleteLocalRef(jChannelMappingType);
+ env->DeleteLocalRef(jChannelMapping);
+ }
+ }
+ *jMicrophoneInfo = env->NewObject(gMicrophoneInfoClass, gMicrophoneInfoCstor, jDeviceId,
+ microphoneInfo->getType(), jAddress,
+ microphoneInfo->getDeviceLocation(),
+ microphoneInfo->getDeviceGroup(),
+ microphoneInfo->getIndexInTheGroup(),
+ jGeometricLocation, jOrientation,
+ jFrequencyResponses, jChannelMappings,
+ microphoneInfo->getSensitivity(),
+ microphoneInfo->getMaxSpl(),
+ microphoneInfo->getMinSpl(),
+ microphoneInfo->getDirectionality());
+
+exit:
+ if (jDeviceId != NULL) {
+ env->DeleteLocalRef(jDeviceId);
+ }
+ if (jAddress != NULL) {
+ env->DeleteLocalRef(jAddress);
+ }
+ if (jFrequencyResponses != NULL) {
+ env->DeleteLocalRef(jFrequencyResponses);
+ }
+ if (jChannelMappings != NULL) {
+ env->DeleteLocalRef(jChannelMappings);
+ }
+ if (jGeometricLocation != NULL) {
+ env->DeleteLocalRef(jGeometricLocation);
+ }
+ if (jOrientation != NULL) {
+ env->DeleteLocalRef(jOrientation);
+ }
+ return jStatus;
+}
+
+}
+
+int register_android_media_MicrophoneInfo(JNIEnv *env)
+{
+ jclass arrayListClass = FindClassOrDie(env, "java/util/ArrayList");
+ gArrayListClass = MakeGlobalRefOrDie(env, arrayListClass);
+ gArrayListCstor = GetMethodIDOrDie(env, arrayListClass, "<init>", "()V");
+ gArrayListMethods.add = GetMethodIDOrDie(env, arrayListClass, "add", "(Ljava/lang/Object;)Z");
+
+ jclass floatClass = FindClassOrDie(env, "java/lang/Float");
+ gFloatClass = MakeGlobalRefOrDie(env, floatClass);
+ gFloatCstor = GetMethodIDOrDie(env, floatClass, "<init>", "(F)V");
+
+ jclass floatArrayClass = FindClassOrDie(env, "[F");
+ gFloatArrayClass = MakeGlobalRefOrDie(env, floatArrayClass);
+
+ jclass integerClass = FindClassOrDie(env, "java/lang/Integer");
+ gIntegerClass = MakeGlobalRefOrDie(env, integerClass);
+ gIntegerCstor = GetMethodIDOrDie(env, integerClass, "<init>", "(I)V");
+
+ jclass microphoneInfoClass = FindClassOrDie(env, "android/media/MicrophoneInfo");
+ gMicrophoneInfoClass = MakeGlobalRefOrDie(env, microphoneInfoClass);
+ gMicrophoneInfoCstor = GetMethodIDOrDie(env, microphoneInfoClass, "<init>",
+ "(Ljava/lang/String;ILjava/lang/String;IIILandroid/media/MicrophoneInfo$Coordinate3F;Landroid/media/MicrophoneInfo$Coordinate3F;Ljava/util/List;Ljava/util/List;FFFI)V");
+
+ jclass microphoneInfoCoordinateClass = FindClassOrDie(
+ env, "android/media/MicrophoneInfo$Coordinate3F");
+ gMicrophoneInfoCoordinateClass = MakeGlobalRefOrDie(env, microphoneInfoCoordinateClass);
+ gMicrophoneInfoCoordinateCstor = GetMethodIDOrDie(env, microphoneInfoCoordinateClass, "<init>",
+ "(Landroid/media/MicrophoneInfo;FFF)V");
+
+ jclass pairClass = FindClassOrDie(env, "android/util/Pair");
+ gPairClass = MakeGlobalRefOrDie(env, pairClass);
+ gPairCstor = GetMethodIDOrDie(env, pairClass, "<init>", "(Ljava/lang/Object;Ljava/lang/Object;)V");
+
+ return 0;
+}
diff --git a/core/jni/android_media_MicrophoneInfo.h b/core/jni/android_media_MicrophoneInfo.h
new file mode 100644
index 0000000..241b6d0
--- /dev/null
+++ b/core/jni/android_media_MicrophoneInfo.h
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+#ifndef ANDROID_MEDIA_MICROPHONEINFO_H
+#define ANDROID_MEDIA_MICROPHONEINFO_H
+
+#include <system/audio.h>
+#include <media/MicrophoneInfo.h>
+
+#include "jni.h"
+
+namespace android {
+
+// Conversion from C++ MicrophoneInfo object to Java MicrophoneInfo object
+
+extern jint convertMicrophoneInfoFromNative(JNIEnv *env, jobject *jMicrophoneInfo,
+ const media::MicrophoneInfo *microphoneInfo);
+} // namespace android
+
+#endif
\ No newline at end of file
diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp
index 37ff8c8..8770d78 100644
--- a/core/jni/android_view_RenderNode.cpp
+++ b/core/jni/android_view_RenderNode.cpp
@@ -174,8 +174,25 @@
return renderNode->stagingProperties().hasShadow();
}
-static jboolean android_view_RenderNode_setShadowColor(jlong renderNodePtr, jint shadowColor) {
- return SET_AND_DIRTY(setShadowColor, static_cast<SkColor>(shadowColor), RenderNode::GENERIC);
+static jboolean android_view_RenderNode_setSpotShadowColor(jlong renderNodePtr, jint shadowColor) {
+ return SET_AND_DIRTY(setSpotShadowColor,
+ static_cast<SkColor>(shadowColor), RenderNode::GENERIC);
+}
+
+static jint android_view_RenderNode_getSpotShadowColor(jlong renderNodePtr) {
+ RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
+ return renderNode->stagingProperties().getSpotShadowColor();
+}
+
+static jboolean android_view_RenderNode_setAmbientShadowColor(jlong renderNodePtr,
+ jint shadowColor) {
+ return SET_AND_DIRTY(setAmbientShadowColor,
+ static_cast<SkColor>(shadowColor), RenderNode::GENERIC);
+}
+
+static jint android_view_RenderNode_getAmbientShadowColor(jlong renderNodePtr) {
+ RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
+ return renderNode->stagingProperties().getAmbientShadowColor();
}
static jboolean android_view_RenderNode_setClipToOutline(jlong renderNodePtr,
@@ -575,7 +592,10 @@
{ "nSetOutlineEmpty", "(J)Z", (void*) android_view_RenderNode_setOutlineEmpty },
{ "nSetOutlineNone", "(J)Z", (void*) android_view_RenderNode_setOutlineNone },
{ "nHasShadow", "(J)Z", (void*) android_view_RenderNode_hasShadow },
- { "nSetShadowColor", "(JI)Z", (void*) android_view_RenderNode_setShadowColor },
+ { "nSetSpotShadowColor", "(JI)Z", (void*) android_view_RenderNode_setSpotShadowColor },
+ { "nGetSpotShadowColor", "(J)I", (void*) android_view_RenderNode_getSpotShadowColor },
+ { "nSetAmbientShadowColor","(JI)Z", (void*) android_view_RenderNode_setAmbientShadowColor },
+ { "nGetAmbientShadowColor","(J)I", (void*) android_view_RenderNode_getAmbientShadowColor },
{ "nSetClipToOutline", "(JZ)Z", (void*) android_view_RenderNode_setClipToOutline },
{ "nSetRevealClip", "(JZFFF)Z", (void*) android_view_RenderNode_setRevealClip },
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index e5ba6d7..43d5b23 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -3029,6 +3029,13 @@
<permission android:name="android.permission.BRIGHTNESS_SLIDER_USAGE"
android:protectionLevel="signature|privileged|development" />
+ <!-- Allows an application to collect ambient light stats.
+ <p>Not for use by third party applications.</p>
+ TODO: Make a system API
+ @hide -->
+ <permission android:name="android.permission.ACCESS_AMBIENT_LIGHT_STATS"
+ android:protectionLevel="signature|privileged|development" />
+
<!-- Allows an application to modify the display brightness configuration
@hide
@SystemApi -->
diff --git a/core/res/res/layout/popup_menu_item_layout.xml b/core/res/res/layout/popup_menu_item_layout.xml
index 3b89f0d..1be915e 100644
--- a/core/res/res/layout/popup_menu_item_layout.xml
+++ b/core/res/res/layout/popup_menu_item_layout.xml
@@ -28,18 +28,18 @@
android:layout_marginBottom="4dip"
android:background="@drawable/list_divider_material" />
- <!-- Icon will be inserted here. -->
-
- <!-- The title and summary have some gap between them,
- and this 'group' should be centered vertically. -->
<LinearLayout
android:id="@+id/content"
- android:layout_width="wrap_content"
+ android:layout_width="match_parent"
android:layout_height="?attr/dropdownListPreferredItemHeight"
android:paddingEnd="16dip"
android:duplicateParentState="true" >
- <LinearLayout
+ <!-- Icon will be inserted here. -->
+
+ <!-- The title and summary have some gap between them,
+ and this 'group' should be centered vertically. -->
+ <RelativeLayout
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
@@ -71,7 +71,7 @@
android:duplicateParentState="true"
android:textAlignment="viewStart" />
- </LinearLayout>
+ </RelativeLayout>
<ImageView
android:id="@+id/submenuarrow"
@@ -81,8 +81,9 @@
android:layout_marginStart="8dp"
android:scaleType="center"
android:visibility="gone" />
- </LinearLayout>
- <!-- Checkbox, and/or radio button will be inserted here. -->
+ <!-- Checkbox, and/or radio button will be inserted here. -->
+
+ </LinearLayout>
</com.android.internal.view.menu.ListMenuItemView>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 0543305..68dad87 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -3036,6 +3036,28 @@
<!-- The title this view should present to accessibility as a pane title.
See {@link android.view.View#setAccessibilityPaneTitle(CharSequence)} -->
<attr name="accessibilityPaneTitle" format="string" />
+
+ <!-- Sets the color of the spot shadow that is drawn when the view has a positive Z or
+ elevation value.
+ <p>
+ By default the shadow color is black. Generally, this color will be opaque so the
+ intensity of the shadow is consistent between different views with different colors.
+ <p>
+ The opacity of the final spot shadow is a function of the shadow caster height, the
+ alpha channel of the outlineSpotShadowColor (typically opaque), and the
+ {@link android.R.attr#spotShadowAlpha} theme attribute. -->
+ <attr name="outlineSpotShadowColor" format="color" />
+
+ <!-- Sets the color of the ambient shadow that is drawn when the view has a positive Z
+ or elevation value.
+ <p>
+ By default the shadow color is black. Generally, this color will be opaque so the
+ intensity of the shadow is consistent between different views with different colors.
+ <p>
+ The opacity of the final ambient shadow is a function of the shadow caster height,
+ the alpha channel of the outlineAmbientShadowColor (typically opaque), and the
+ {@link android.R.attr#ambientShadowAlpha} theme attribute. -->
+ <attr name="outlineAmbientShadowColor" format="color" />
</declare-styleable>
<!-- Attributes that can be assigned to a tag for a particular View. -->
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 30586d1..dee880f 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -2866,6 +2866,8 @@
<public name="lastBaselineToBottomHeight" />
<public name="lineHeight" />
<public name="accessibilityHeading" />
+ <public name="outlineSpotShadowColor" />
+ <public name="outlineAmbientShadowColor" />
</public-group>
<public-group type="style" first-id="0x010302e0">
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 3cde765..224503b 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -3222,19 +3222,23 @@
<string name="dlg_ok">OK</string>
<!-- USB_PREFERENCES: Notification for when the user connected to the charger only. This is the title -->
- <string name="usb_charging_notification_title">USB charging this device</string>
+ <string name="usb_charging_notification_title">Charging this device via USB</string>
<!-- USB_PREFERENCES: Notification for when the user connects the phone to supply power to attached device. This is the title -->
- <string name="usb_supplying_notification_title">USB supplying power to attached device</string>
+ <string name="usb_supplying_notification_title">Charging connected device via USB</string>
<!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in MTP mode. This is the title -->
- <string name="usb_mtp_notification_title">USB for file transfer</string>
+ <string name="usb_mtp_notification_title">USB file transfer turned on</string>
<!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in PTP mode. This is the title -->
- <string name="usb_ptp_notification_title">USB for photo transfer</string>
+ <string name="usb_ptp_notification_title">PTP via USB turned on</string>
+ <!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in Tethering mode. This is the title -->
+ <string name="usb_tether_notification_title">USB tethering turned on</string>
<!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in MIDI mode. This is the title -->
- <string name="usb_midi_notification_title">USB for MIDI</string>
+ <string name="usb_midi_notification_title">MIDI via USB turned on</string>
<!-- USB_PREFERENCES: Notification for when a USB accessory is attached. This is the title -->
- <string name="usb_accessory_notification_title">Connected to a USB accessory</string>
+ <string name="usb_accessory_notification_title">USB accessory mode turned on</string>
<!-- See USB_PREFERENCES. This is the message. -->
<string name="usb_notification_message">Tap for more options.</string>
+ <!-- See USB_PREFERENCES. This is the message when a data mode is turned on (mtp, ptp, midi) and the device is supplying power.. -->
+ <string name="usb_power_notification_message">Charging connected device. Tap for more options.</string>
<!-- USB_PREFERENCES: Notification for when a type-c USB audio accessory is attached but not supported. This is the title -->
<string name="usb_unsupported_audio_accessory_title">Analog audio accessory detected</string>
<!-- Message of notification shown when a type-c USB audio accessory is attached but not supported. -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index a62d49e..a338f89 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2026,8 +2026,10 @@
<java-symbol type="string" name="usb_mtp_notification_title" />
<java-symbol type="string" name="usb_charging_notification_title" />
<java-symbol type="string" name="usb_notification_message" />
+ <java-symbol type="string" name="usb_power_notification_message" />
<java-symbol type="string" name="usb_ptp_notification_title" />
<java-symbol type="string" name="usb_midi_notification_title" />
+ <java-symbol type="string" name="usb_tether_notification_title" />
<java-symbol type="string" name="usb_supplying_notification_title" />
<java-symbol type="string" name="usb_unsupported_audio_accessory_title" />
<java-symbol type="string" name="usb_unsupported_audio_accessory_message" />
diff --git a/core/tests/benchmarks/src/android/os/FileUtilsBenchmark.java b/core/tests/benchmarks/src/android/os/FileUtilsBenchmark.java
new file mode 100644
index 0000000..4f7c924
--- /dev/null
+++ b/core/tests/benchmarks/src/android/os/FileUtilsBenchmark.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package android.os;
+
+import static android.os.FileUtils.copyInternalSendfile;
+import static android.os.FileUtils.copyInternalSplice;
+import static android.os.FileUtils.copyInternalUserspace;
+
+import android.os.FileUtils.MemoryPipe;
+
+import com.google.caliper.BeforeExperiment;
+import com.google.caliper.Param;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+
+public class FileUtilsBenchmark {
+ @Param({"32", "32000", "32000000"})
+ private int mSize;
+
+ private File mSrc;
+ private File mDest;
+
+ private byte[] mData;
+
+ @BeforeExperiment
+ protected void setUp() throws Exception {
+ mSrc = new File("/data/local/tmp/src");
+ mDest = new File("/data/local/tmp/dest");
+
+ mData = new byte[mSize];
+
+ try (FileOutputStream os = new FileOutputStream(mSrc)) {
+ os.write(mData);
+ }
+ }
+
+ public void timeRegularUserspace(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (FileInputStream in = new FileInputStream(mSrc);
+ FileOutputStream out = new FileOutputStream(mDest)) {
+ copyInternalUserspace(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+
+ public void timeRegularSendfile(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (FileInputStream in = new FileInputStream(mSrc);
+ FileOutputStream out = new FileOutputStream(mDest)) {
+ copyInternalSendfile(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+
+ public void timePipeSourceUserspace(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (MemoryPipe in = MemoryPipe.createSource(mData);
+ FileOutputStream out = new FileOutputStream(mDest)) {
+ copyInternalUserspace(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+
+ public void timePipeSourceSplice(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (MemoryPipe in = MemoryPipe.createSource(mData);
+ FileOutputStream out = new FileOutputStream(mDest)) {
+ copyInternalSplice(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+
+ public void timePipeSinkUserspace(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (FileInputStream in = new FileInputStream(mSrc);
+ MemoryPipe out = MemoryPipe.createSink(mData)) {
+ copyInternalUserspace(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+
+ public void timePipeSinkSplice(int reps) throws Exception {
+ for (int i = 0; i < reps; i++) {
+ try (FileInputStream in = new FileInputStream(mSrc);
+ MemoryPipe out = MemoryPipe.createSink(mData)) {
+ copyInternalSplice(in.getFD(), out.getFD(), null, null);
+ }
+ }
+ }
+}
diff --git a/core/tests/coretests/src/android/hardware/display/AmbientBrightnessDayStatsTest.java b/core/tests/coretests/src/android/hardware/display/AmbientBrightnessDayStatsTest.java
new file mode 100644
index 0000000..84409d4
--- /dev/null
+++ b/core/tests/coretests/src/android/hardware/display/AmbientBrightnessDayStatsTest.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.display;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+import android.os.Parcel;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.time.LocalDate;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AmbientBrightnessDayStatsTest {
+
+ @Test
+ public void testAmbientBrightnessDayStatsAdd() {
+ AmbientBrightnessDayStats dayStats = new AmbientBrightnessDayStats(LocalDate.now(),
+ new float[]{0, 1, 10, 100});
+ dayStats.log(0, 1);
+ dayStats.log(0.5f, 1.5f);
+ dayStats.log(50, 12.5f);
+ dayStats.log(2000, 1.24f);
+ dayStats.log(-10, 0.5f);
+ assertEquals(2.5f, dayStats.getStats()[0], 0);
+ assertEquals(0, dayStats.getStats()[1], 0);
+ assertEquals(12.5f, dayStats.getStats()[2], 0);
+ assertEquals(1.24f, dayStats.getStats()[3], 0);
+ }
+
+ @Test
+ public void testAmbientBrightnessDayStatsEquals() {
+ LocalDate today = LocalDate.now();
+ AmbientBrightnessDayStats dayStats1 = new AmbientBrightnessDayStats(today,
+ new float[]{0, 1, 10, 100});
+ AmbientBrightnessDayStats dayStats2 = new AmbientBrightnessDayStats(today,
+ new float[]{0, 1, 10, 100}, new float[4]);
+ AmbientBrightnessDayStats dayStats3 = new AmbientBrightnessDayStats(today,
+ new float[]{0, 1, 10, 100}, new float[]{1, 3, 5, 7});
+ AmbientBrightnessDayStats dayStats4 = new AmbientBrightnessDayStats(today,
+ new float[]{0, 1, 10, 100}, new float[]{1, 3, 5, 0});
+ assertEquals(dayStats1, dayStats2);
+ assertEquals(dayStats1.hashCode(), dayStats2.hashCode());
+ assertNotEquals(dayStats1, dayStats3);
+ assertNotEquals(dayStats1.hashCode(), dayStats3.hashCode());
+ dayStats4.log(100, 7);
+ assertEquals(dayStats3, dayStats4);
+ assertEquals(dayStats3.hashCode(), dayStats4.hashCode());
+ }
+
+ @Test
+ public void testAmbientBrightnessDayStatsIncorrectInit() {
+ try {
+ new AmbientBrightnessDayStats(LocalDate.now(), new float[]{1, 10, 100},
+ new float[]{1, 5, 6, 7});
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ try {
+ new AmbientBrightnessDayStats(LocalDate.now(), new float[]{});
+ } catch (IllegalArgumentException e) {
+ // Expected
+ }
+ }
+
+ @Test
+ public void testParcelUnparcelAmbientBrightnessDayStats() {
+ LocalDate today = LocalDate.now();
+ AmbientBrightnessDayStats stats = new AmbientBrightnessDayStats(today,
+ new float[]{0, 1, 10, 100}, new float[]{1.3f, 2.6f, 5.8f, 10});
+ // Parcel the data
+ Parcel parcel = Parcel.obtain();
+ stats.writeToParcel(parcel, 0);
+ byte[] parceled = parcel.marshall();
+ parcel.recycle();
+ // Unparcel and check that it has not changed
+ parcel = Parcel.obtain();
+ parcel.unmarshall(parceled, 0, parceled.length);
+ parcel.setDataPosition(0);
+ AmbientBrightnessDayStats statsAgain = AmbientBrightnessDayStats.CREATOR.createFromParcel(
+ parcel);
+ assertEquals(stats, statsAgain);
+ }
+}
diff --git a/core/tests/coretests/src/android/os/FileUtilsTest.java b/core/tests/coretests/src/android/os/FileUtilsTest.java
index cd20192..b7220b3 100644
--- a/core/tests/coretests/src/android/os/FileUtilsTest.java
+++ b/core/tests/coretests/src/android/os/FileUtilsTest.java
@@ -21,16 +21,19 @@
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
import static android.text.format.DateUtils.WEEK_IN_MILLIS;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import android.content.Context;
+import android.os.FileUtils.MemoryPipe;
import android.provider.DocumentsContract.Document;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import libcore.io.IoUtils;
+import libcore.io.Streams;
import com.google.android.collect.Sets;
@@ -40,11 +43,13 @@
import org.junit.runner.RunWith;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
+import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.Random;
@RunWith(AndroidJUnit4.class)
public class FileUtilsTest {
@@ -56,6 +61,8 @@
private File mCopyFile;
private File mTarget;
+ private final int[] DATA_SIZES = { 32, 32_000, 32_000_000 };
+
private Context getContext() {
return InstrumentationRegistry.getContext();
}
@@ -80,7 +87,7 @@
@Test
public void testCopyFile() throws Exception {
- stageFile(mTestFile, TEST_DATA);
+ writeFile(mTestFile, TEST_DATA);
assertFalse(mCopyFile.exists());
FileUtils.copyFile(mTestFile, mCopyFile);
assertTrue(mCopyFile.exists());
@@ -97,6 +104,83 @@
}
@Test
+ public void testCopy_FileToFile() throws Exception {
+ for (int size : DATA_SIZES) {
+ final File src = new File(mTarget, "src");
+ final File dest = new File(mTarget, "dest");
+
+ byte[] expected = new byte[size];
+ byte[] actual = new byte[size];
+ new Random().nextBytes(expected);
+ writeFile(src, expected);
+
+ try (FileInputStream in = new FileInputStream(src);
+ FileOutputStream out = new FileOutputStream(dest)) {
+ FileUtils.copy(in, out);
+ }
+
+ actual = readFile(dest);
+ assertArrayEquals(expected, actual);
+ }
+ }
+
+ @Test
+ public void testCopy_FileToPipe() throws Exception {
+ for (int size : DATA_SIZES) {
+ final File src = new File(mTarget, "src");
+
+ byte[] expected = new byte[size];
+ byte[] actual = new byte[size];
+ new Random().nextBytes(expected);
+ writeFile(src, expected);
+
+ try (FileInputStream in = new FileInputStream(src);
+ MemoryPipe out = MemoryPipe.createSink(actual)) {
+ FileUtils.copy(in.getFD(), out.getFD());
+ out.join();
+ }
+
+ assertArrayEquals(expected, actual);
+ }
+ }
+
+ @Test
+ public void testCopy_PipeToFile() throws Exception {
+ for (int size : DATA_SIZES) {
+ final File dest = new File(mTarget, "dest");
+
+ byte[] expected = new byte[size];
+ byte[] actual = new byte[size];
+ new Random().nextBytes(expected);
+
+ try (MemoryPipe in = MemoryPipe.createSource(expected);
+ FileOutputStream out = new FileOutputStream(dest)) {
+ FileUtils.copy(in.getFD(), out.getFD());
+ }
+
+ actual = readFile(dest);
+ assertArrayEquals(expected, actual);
+ }
+ }
+
+ @Test
+ public void testCopy_PipeToPipe() throws Exception {
+ for (int size : DATA_SIZES) {
+ byte[] expected = new byte[size];
+ byte[] actual = new byte[size];
+ new Random().nextBytes(expected);
+
+ try (MemoryPipe in = MemoryPipe.createSource(expected);
+ MemoryPipe out = MemoryPipe.createSink(actual)) {
+ FileUtils.copy(in.getFD(), out.getFD());
+ out.join();
+ }
+
+ assertArrayEquals(expected, actual);
+ }
+ }
+
+ @Test
public void testIsFilenameSafe() throws Exception {
assertTrue(FileUtils.isFilenameSafe(new File("foobar")));
assertTrue(FileUtils.isFilenameSafe(new File("a_b-c=d.e/0,1+23")));
@@ -106,7 +190,7 @@
@Test
public void testReadTextFile() throws Exception {
- stageFile(mTestFile, TEST_DATA);
+ writeFile(mTestFile, TEST_DATA);
assertEquals(TEST_DATA, FileUtils.readTextFile(mTestFile, 0, null));
@@ -127,7 +211,7 @@
@Test
public void testReadTextFileWithZeroLengthFile() throws Exception {
- stageFile(mTestFile, TEST_DATA);
+ writeFile(mTestFile, TEST_DATA);
new FileOutputStream(mTestFile).close(); // Zero out the file
assertEquals("", FileUtils.readTextFile(mTestFile, 0, null));
assertEquals("", FileUtils.readTextFile(mTestFile, 1, "<>"));
@@ -381,12 +465,21 @@
file.setLastModified(System.currentTimeMillis() - age);
}
- private void stageFile(File file, String data) throws Exception {
- FileWriter writer = new FileWriter(file);
- try {
- writer.write(data, 0, data.length());
- } finally {
- writer.close();
+ private void writeFile(File file, String data) throws Exception {
+ writeFile(file, data.getBytes());
+ }
+
+ private void writeFile(File file, byte[] data) throws Exception {
+ try (FileOutputStream out = new FileOutputStream(file)) {
+ out.write(data);
+ }
+ }
+
+ private byte[] readFile(File file) throws Exception {
+ try (FileInputStream in = new FileInputStream(file);
+ ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ Streams.copy(in, out);
+ return out.toByteArray();
}
}
diff --git a/graphics/java/android/graphics/drawable/AnimatedImageDrawable.java b/graphics/java/android/graphics/drawable/AnimatedImageDrawable.java
index bd49b87..27c8fda 100644
--- a/graphics/java/android/graphics/drawable/AnimatedImageDrawable.java
+++ b/graphics/java/android/graphics/drawable/AnimatedImageDrawable.java
@@ -348,7 +348,9 @@
if (mState == null) {
throw new IllegalStateException("called stop on empty AnimatedImageDrawable");
}
- nStop(mState.mNativePtr);
+ if (nStop(mState.mNativePtr)) {
+ postOnAnimationEnd();
+ }
}
// Animatable2 overrides
@@ -365,21 +367,31 @@
nSetOnAnimationEndListener(mState.mNativePtr, this);
}
- mAnimationCallbacks.add(callback);
+ if (!mAnimationCallbacks.contains(callback)) {
+ mAnimationCallbacks.add(callback);
+ }
}
@Override
public boolean unregisterAnimationCallback(@NonNull AnimationCallback callback) {
- if (callback == null || mAnimationCallbacks == null) {
+ if (callback == null || mAnimationCallbacks == null
+ || !mAnimationCallbacks.remove(callback)) {
return false;
}
- return mAnimationCallbacks.remove(callback);
+ if (mAnimationCallbacks.isEmpty()) {
+ clearAnimationCallbacks();
+ }
+
+ return true;
}
@Override
public void clearAnimationCallbacks() {
- mAnimationCallbacks = null;
+ if (mAnimationCallbacks != null) {
+ mAnimationCallbacks = null;
+ nSetOnAnimationEndListener(mState.mNativePtr, null);
+ }
}
private void postOnAnimationStart() {
@@ -413,6 +425,21 @@
return mHandler;
}
+ /**
+ * Called by JNI.
+ *
+ * The JNI code has already posted this to the thread that created the
+ * callback, so no need to post.
+ */
+ @SuppressWarnings("unused")
+ private void onAnimationEnd() {
+ if (mAnimationCallbacks != null) {
+ for (Animatable2.AnimationCallback callback : mAnimationCallbacks) {
+ callback.onAnimationEnd(this);
+ }
+ }
+ }
+
private static native long nCreate(long nativeImageDecoder,
@Nullable ImageDecoder decoder, int width, int height, Rect cropRect)
@@ -432,7 +459,7 @@
@FastNative
private static native boolean nStart(long nativePtr);
@FastNative
- private static native void nStop(long nativePtr);
+ private static native boolean nStop(long nativePtr);
@FastNative
private static native void nSetLoopCount(long nativePtr, int loopCount);
// Pass the drawable down to native so it can call onAnimationEnd.
diff --git a/libs/hwui/RenderProperties.h b/libs/hwui/RenderProperties.h
index 3d2c252..55f4d89 100644
--- a/libs/hwui/RenderProperties.h
+++ b/libs/hwui/RenderProperties.h
@@ -507,12 +507,20 @@
getOutline().getAlpha() != 0.0f;
}
- SkColor getShadowColor() const {
- return mPrimitiveFields.mShadowColor;
+ SkColor getSpotShadowColor() const {
+ return mPrimitiveFields.mSpotShadowColor;
}
- bool setShadowColor(SkColor shadowColor) {
- return RP_SET(mPrimitiveFields.mShadowColor, shadowColor);
+ bool setSpotShadowColor(SkColor shadowColor) {
+ return RP_SET(mPrimitiveFields.mSpotShadowColor, shadowColor);
+ }
+
+ SkColor getAmbientShadowColor() const {
+ return mPrimitiveFields.mAmbientShadowColor;
+ }
+
+ bool setAmbientShadowColor(SkColor shadowColor) {
+ return RP_SET(mPrimitiveFields.mAmbientShadowColor, shadowColor);
}
bool fitsOnLayer() const {
@@ -538,7 +546,8 @@
int mLeft = 0, mTop = 0, mRight = 0, mBottom = 0;
int mWidth = 0, mHeight = 0;
int mClippingFlags = CLIP_TO_BOUNDS;
- SkColor mShadowColor = SK_ColorBLACK;
+ SkColor mSpotShadowColor = SK_ColorBLACK;
+ SkColor mAmbientShadowColor = SK_ColorBLACK;
float mAlpha = 1;
float mTranslationX = 0, mTranslationY = 0, mTranslationZ = 0;
float mElevation = 0;
diff --git a/libs/hwui/hwui/AnimatedImageDrawable.cpp b/libs/hwui/hwui/AnimatedImageDrawable.cpp
index 5356d3b..2bded9b 100644
--- a/libs/hwui/hwui/AnimatedImageDrawable.cpp
+++ b/libs/hwui/hwui/AnimatedImageDrawable.cpp
@@ -48,8 +48,10 @@
return true;
}
-void AnimatedImageDrawable::stop() {
+bool AnimatedImageDrawable::stop() {
+ bool wasRunning = mRunning;
mRunning = false;
+ return wasRunning;
}
bool AnimatedImageDrawable::isRunning() {
@@ -180,7 +182,6 @@
if (finalFrame) {
if (mEndListener) {
mEndListener->onAnimationEnd();
- mEndListener = nullptr;
}
}
}
diff --git a/libs/hwui/hwui/AnimatedImageDrawable.h b/libs/hwui/hwui/AnimatedImageDrawable.h
index 9d84ed5..2fd6f40 100644
--- a/libs/hwui/hwui/AnimatedImageDrawable.h
+++ b/libs/hwui/hwui/AnimatedImageDrawable.h
@@ -68,7 +68,9 @@
// Returns true if the animation was started; false otherwise (e.g. it was
// already running)
bool start();
- void stop();
+ // Returns true if the animation was stopped; false otherwise (e.g. it was
+ // already stopped)
+ bool stop();
bool isRunning();
void setRepetitionCount(int count) { mSkAnimatedImage->setRepetitionCount(count); }
diff --git a/libs/hwui/pipeline/skia/ReorderBarrierDrawables.cpp b/libs/hwui/pipeline/skia/ReorderBarrierDrawables.cpp
index 7b59ccf..25c51f2 100644
--- a/libs/hwui/pipeline/skia/ReorderBarrierDrawables.cpp
+++ b/libs/hwui/pipeline/skia/ReorderBarrierDrawables.cpp
@@ -111,6 +111,10 @@
}
}
+static SkColor multiplyAlpha(SkColor color, float alpha) {
+ return SkColorSetA(color, alpha * SkColorGetA(color));
+}
+
// copied from FrameBuilder::deferShadow
void EndReorderBarrierDrawable::drawShadow(SkCanvas* canvas, RenderNodeDrawable* caster) {
const RenderProperties& casterProperties = caster->getNodeProperties();
@@ -187,9 +191,11 @@
} else {
zParams = SkPoint3::Make(0, 0, casterProperties.getZ());
}
+ SkColor ambientColor = multiplyAlpha(casterProperties.getAmbientShadowColor(), ambientAlpha);
+ SkColor spotColor = multiplyAlpha(casterProperties.getSpotShadowColor(), spotAlpha);
SkShadowUtils::DrawShadow(
canvas, *casterPath, zParams, skiaLightPos, SkiaPipeline::getLightRadius(),
- ambientAlpha, spotAlpha, casterProperties.getShadowColor(),
+ ambientColor, spotColor,
casterAlpha < 1.0f ? SkShadowFlags::kTransparentOccluder_ShadowFlag : 0);
}
diff --git a/location/java/android/location/ILocationManager.aidl b/location/java/android/location/ILocationManager.aidl
index 018db9a..fa3f99a 100644
--- a/location/java/android/location/ILocationManager.aidl
+++ b/location/java/android/location/ILocationManager.aidl
@@ -88,11 +88,6 @@
boolean providerMeetsCriteria(String provider, in Criteria criteria);
ProviderProperties getProviderProperties(String provider);
String getNetworkProviderPackage();
- boolean isProviderEnabled(String provider);
- boolean isProviderEnabledForUser(String provider, int userId);
- boolean setProviderEnabledForUser(String provider, boolean enabled, int userId);
- boolean isLocationEnabledForUser(int userId);
- void setLocationEnabledForUser(boolean enabled, int userId);
void addTestProvider(String name, in ProviderProperties properties, String opPackageName);
void removeTestProvider(String provider, String opPackageName);
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 22fa620..bf51d97 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -48,11 +48,13 @@
import android.os.SystemClock;
import android.os.UserHandle;
import android.provider.Settings;
+import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.util.Slog;
import android.view.KeyEvent;
+import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
@@ -4578,6 +4580,51 @@
}
}
+ /**
+ * Set port id for microphones by matching device type and address.
+ * @hide
+ */
+ public static void setPortIdForMicrophones(ArrayList<MicrophoneInfo> microphones) {
+ AudioDeviceInfo[] devices = getDevicesStatic(AudioManager.GET_DEVICES_INPUTS);
+ for (int i = microphones.size() - 1; i >= 0; i--) {
+ boolean foundPortId = false;
+ for (AudioDeviceInfo device : devices) {
+ if (device.getPort().type() == microphones.get(i).getInternalDeviceType()
+ && TextUtils.equals(device.getAddress(), microphones.get(i).getAddress())) {
+ microphones.get(i).setId(device.getId());
+ foundPortId = true;
+ break;
+ }
+ }
+ if (!foundPortId) {
+ Log.i(TAG, "Failed to find port id for device with type:"
+ + microphones.get(i).getType() + " address:"
+ + microphones.get(i).getAddress());
+ microphones.remove(i);
+ }
+ }
+ }
+
+ /**
+ * Returns a list of {@link MicrophoneInfo} that corresponds to the characteristics
+ * of all available microphones. The list is empty when no microphones are available
+ * on the device. An error during the query will result in an IOException being thrown.
+ *
+ * @return a list that contains all microphones' characteristics
+ * @throws IOException if an error occurs.
+ */
+ public List<MicrophoneInfo> getMicrophones() throws IOException {
+ ArrayList<MicrophoneInfo> microphones = new ArrayList<MicrophoneInfo>();
+ int status = AudioSystem.getMicrophones(microphones);
+ if (status != AudioManager.SUCCESS) {
+ // fail and bail!
+ Log.e(TAG, "getMicrophones failed:" + status);
+ return new ArrayList<MicrophoneInfo>(); // Always return a list.
+ }
+ setPortIdForMicrophones(microphones);
+ return microphones;
+ }
+
// Since we need to calculate the changes since THE LAST NOTIFICATION, and not since the
// (unpredictable) last time updateAudioPortCache() was called by someone, keep a list
// of the ports that exist at the time of the last notification.
diff --git a/media/java/android/media/AudioPresentation.java b/media/java/android/media/AudioPresentation.java
new file mode 100644
index 0000000..4652c18
--- /dev/null
+++ b/media/java/android/media/AudioPresentation.java
@@ -0,0 +1,181 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media;
+
+import android.annotation.IntDef;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+
+/**
+ * The AudioPresentation class encapsulates the information that describes an audio presentation
+ * which is available in next generation audio content.
+ *
+ * Used by {@link MediaExtractor} {@link MediaExtractor#getAudioPresentations(int)} and
+ * {@link AudioTrack} {@link AudioTrack#setPresentation(AudioPresentation)} to query available
+ * presentations and to select one.
+ *
+ * A list of available audio presentations in a media source can be queried using
+ * {@link MediaExtractor#getAudioPresentations(int)}. This list can be presented to a user for
+ * selection.
+ * An AudioPresentation can be passed to an offloaded audio decoder via
+ * {@link AudioTrack#setPresentation(AudioPresentation)} to request decoding of the selected
+ * presentation. An audio stream may contain multiple presentations that differ by language,
+ * accessibility, end point mastering and dialogue enhancement. An audio presentation may also have
+ * a set of description labels in different languages to help the user to make an informed
+ * selection.
+ */
+public final class AudioPresentation {
+ private final int mPresentationId;
+ private final int mProgramId;
+ private final Map<String, String> mLabels;
+ private final String mLanguage;
+
+ /** @hide */
+ @IntDef(
+ value = {
+ MASTERING_NOT_INDICATED,
+ MASTERED_FOR_STEREO,
+ MASTERED_FOR_SURROUND,
+ MASTERED_FOR_3D,
+ MASTERED_FOR_HEADPHONE,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface MasteringIndicationType {}
+
+ private final @MasteringIndicationType int mMasteringIndication;
+ private final boolean mAudioDescriptionAvailable;
+ private final boolean mSpokenSubtitlesAvailable;
+ private final boolean mDialogueEnhancementAvailable;
+
+ /**
+ * No preferred reproduction channel layout.
+ */
+ public static final int MASTERING_NOT_INDICATED = 0;
+ /**
+ * Stereo speaker layout.
+ */
+ public static final int MASTERED_FOR_STEREO = 1;
+ /**
+ * Two-dimensional (e.g. 5.1) speaker layout.
+ */
+ public static final int MASTERED_FOR_SURROUND = 2;
+ /**
+ * Three-dimensional (e.g. 5.1.2) speaker layout.
+ */
+ public static final int MASTERED_FOR_3D = 3;
+ /**
+ * Prerendered for headphone playback.
+ */
+ public static final int MASTERED_FOR_HEADPHONE = 4;
+
+ AudioPresentation(int presentationId,
+ int programId,
+ Map<String, String> labels,
+ String language,
+ @MasteringIndicationType int masteringIndication,
+ boolean audioDescriptionAvailable,
+ boolean spokenSubtitlesAvailable,
+ boolean dialogueEnhancementAvailable) {
+ this.mPresentationId = presentationId;
+ this.mProgramId = programId;
+ this.mLanguage = language;
+ this.mMasteringIndication = masteringIndication;
+ this.mAudioDescriptionAvailable = audioDescriptionAvailable;
+ this.mSpokenSubtitlesAvailable = spokenSubtitlesAvailable;
+ this.mDialogueEnhancementAvailable = dialogueEnhancementAvailable;
+
+ this.mLabels = new HashMap<String, String>(labels);
+ }
+
+ /**
+ * The framework uses this presentation id to select an audio presentation rendered by a
+ * decoder. Presentation id is typically sequential, but does not have to be.
+ * @hide
+ */
+ public int getPresentationId() {
+ return mPresentationId;
+ }
+
+ /**
+ * The framework uses this program id to select an audio presentation rendered by a decoder.
+ * Program id can be used to further uniquely identify the presentation to a decoder.
+ * @hide
+ */
+ public int getProgramId() {
+ return mProgramId;
+ }
+
+ /**
+ * @return a map of available text labels for this presentation. Each label is indexed by its
+ * locale corresponding to the language code as specified by ISO 639-2 [42]. Either ISO 639-2/B
+ * or ISO 639-2/T could be used.
+ */
+ public Map<Locale, String> getLabels() {
+ Map<Locale, String> localeLabels = new HashMap<>();
+ for (Map.Entry<String, String> entry : mLabels.entrySet()) {
+ localeLabels.put(new Locale(entry.getKey()), entry.getValue());
+ }
+ return localeLabels;
+ }
+
+ /**
+ * @return the locale corresponding to audio presentation's ISO 639-1/639-2 language code.
+ */
+ public Locale getLocale() {
+ return new Locale(mLanguage);
+ }
+
+ /**
+ * @return the mastering indication of the audio presentation.
+ * See {@link #MASTERING_NOT_INDICATED}, {@link #MASTERED_FOR_STEREO},
+ * {@link #MASTERED_FOR_SURROUND}, {@link #MASTERED_FOR_3D}, {@link #MASTERED_FOR_HEADPHONE}
+ */
+ @MasteringIndicationType
+ public int getMasteringIndication() {
+ return mMasteringIndication;
+ }
+
+ /**
+ * Indicates whether an audio description for the visually impaired is available.
+ * @return {@code true} if audio description is available.
+ */
+ public boolean hasAudioDescription() {
+ return mAudioDescriptionAvailable;
+ }
+
+ /**
+ * Indicates whether spoken subtitles for the visually impaired are available.
+ * @return {@code true} if spoken subtitles are available.
+ */
+ public boolean hasSpokenSubtitles() {
+ return mSpokenSubtitlesAvailable;
+ }
+
+ /**
+ * Indicates whether dialogue enhancement is available.
+ * @return {@code true} if dialogue enhancement is available.
+ */
+ public boolean hasDialogueEnhancement() {
+ return mDialogueEnhancementAvailable;
+ }
+}
diff --git a/media/java/android/media/AudioRecord.java b/media/java/android/media/AudioRecord.java
index eb6e830..d0963cb 100644
--- a/media/java/android/media/AudioRecord.java
+++ b/media/java/android/media/AudioRecord.java
@@ -16,12 +16,15 @@
package android.media;
+import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;
+import java.util.ArrayList;
+import java.util.List;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -35,6 +38,7 @@
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
@@ -1601,6 +1605,32 @@
}
}
+ //--------------------------------------------------------------------------
+ // Microphone information
+ //--------------------
+ /**
+ * Returns a lists of {@link MicrophoneInfo} representing the active microphones.
+ * By querying channel mapping for each active microphone, developer can know how
+ * the microphone is used by each channels or a capture stream.
+ * Note that the information about the active microphones may change during a recording.
+ * See {@link AudioManager#registerAudioDeviceCallback} to be notified of changes
+ * in the audio devices, querying the active microphones then will return the latest
+ * information.
+ *
+ * @return a lists of {@link MicrophoneInfo} representing the active microphones.
+ * @throws IOException if an error occurs
+ */
+ public List<MicrophoneInfo> getActiveMicrophones() throws IOException {
+ ArrayList<MicrophoneInfo> activeMicrophones = new ArrayList<>();
+ int status = native_get_active_microphones(activeMicrophones);
+ if (status != AudioManager.SUCCESS) {
+ Log.e(TAG, "getActiveMicrophones failed:" + status);
+ return new ArrayList<MicrophoneInfo>();
+ }
+ AudioManager.setPortIdForMicrophones(activeMicrophones);
+ return activeMicrophones;
+ }
+
//---------------------------------------------------------
// Interface definitions
//--------------------
@@ -1746,6 +1776,9 @@
private native final int native_get_timestamp(@NonNull AudioTimestamp outTimestamp,
@AudioTimestamp.Timebase int timebase);
+ private native final int native_get_active_microphones(
+ ArrayList<MicrophoneInfo> activeMicrophones);
+
//---------------------------------------------------------
// Utility methods
//------------------
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index dcd37da..be9fcb8 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -827,6 +827,8 @@
private static native boolean native_is_offload_supported(int encoding, int sampleRate,
int channelMask, int channelIndexMask);
+ public static native int getMicrophones(ArrayList<MicrophoneInfo> microphonesInfo);
+
// Items shared with audio service
/**
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 4e9ce8e..8e822a5 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -2008,6 +2008,25 @@
}
/**
+ * Sets the audio presentation.
+ * If the audio presentation is invalid then {@link #ERROR_BAD_VALUE} will be returned.
+ * If a multi-stream decoder (MSD) is not present, or the format does not support
+ * multiple presentations, then {@link #ERROR_INVALID_OPERATION} will be returned.
+ * @param presentation see {@link AudioPresentation}. In particular, id should be set.
+ * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE},
+ * {@link #ERROR_INVALID_OPERATION}
+ * @throws IllegalArgumentException if the audio presentation is null.
+ * @throws IllegalStateException if track is not initialized.
+ */
+ public int setPresentation(@NonNull AudioPresentation presentation) {
+ if (presentation == null) {
+ throw new IllegalArgumentException("audio presentation is null");
+ }
+ return native_setPresentation(presentation.getPresentationId(),
+ presentation.getProgramId());
+ }
+
+ /**
* Sets the initialization state of the instance. This method was originally intended to be used
* in an AudioTrack subclass constructor to set a subclass-specific post-initialization state.
* However, subclasses of AudioTrack are no longer recommended, so this method is obsolete.
@@ -3245,6 +3264,7 @@
@NonNull VolumeShaper.Operation operation);
private native @Nullable VolumeShaper.State native_getVolumeShaperState(int id);
+ private native final int native_setPresentation(int presentationId, int programId);
//---------------------------------------------------------
// Utility methods
diff --git a/media/java/android/media/MediaBrowser2.java b/media/java/android/media/MediaBrowser2.java
index 5ad4313..5cb8313 100644
--- a/media/java/android/media/MediaBrowser2.java
+++ b/media/java/android/media/MediaBrowser2.java
@@ -19,7 +19,6 @@
import android.annotation.CallbackExecutor;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.annotation.SystemApi;
import android.content.Context;
import android.media.update.ApiLoader;
import android.media.update.MediaBrowser2Provider;
@@ -41,14 +40,14 @@
*/
public static class BrowserCallback extends MediaController2.ControllerCallback {
/**
- * Called with the result of {@link #getBrowserRoot(Bundle)}.
+ * Called with the result of {@link #getLibraryRoot(Bundle)}.
* <p>
- * {@code rootMediaId} and {@code rootExtra} can be {@code null} if the browser root isn't
+ * {@code rootMediaId} and {@code rootExtra} can be {@code null} if the library root isn't
* available.
*
* @param rootHints rootHints that you previously requested.
- * @param rootMediaId media id of the browser root. Can be {@code null}
- * @param rootExtra extra of the browser root. Can be {@code null}
+ * @param rootMediaId media id of the library root. Can be {@code null}
+ * @param rootExtra extra of the library root. Can be {@code null}
*/
public void onGetRootResult(Bundle rootHints, @Nullable String rootMediaId,
@Nullable Bundle rootExtra) { }
@@ -114,8 +113,15 @@
.createMediaBrowser2(context, this, token, executor, (BrowserCallback) callback);
}
- public void getBrowserRoot(Bundle rootHints) {
- mProvider.getBrowserRoot_impl(rootHints);
+ /**
+ * Get the library root. Result would be sent back asynchronously with the
+ * {@link BrowserCallback#onGetRootResult(Bundle, String, Bundle)}.
+ *
+ * @param rootHints hint for the root
+ * @see BrowserCallback#onGetRootResult(Bundle, String, Bundle)
+ */
+ public void getLibraryRoot(Bundle rootHints) {
+ mProvider.getLibraryRoot_impl(rootHints);
}
/**
diff --git a/media/java/android/media/MediaExtractor.java b/media/java/android/media/MediaExtractor.java
index 174d6a3..4919eeb 100644
--- a/media/java/android/media/MediaExtractor.java
+++ b/media/java/android/media/MediaExtractor.java
@@ -22,6 +22,7 @@
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
+import android.media.AudioPresentation;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaHTTPService;
@@ -40,6 +41,7 @@
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.UUID;
@@ -396,6 +398,17 @@
}
/**
+ * Get the list of available audio presentations for the track.
+ * @param trackIndex index of the track.
+ * @return a list of available audio presentations for a given valid audio track index.
+ * The list will be empty if the source does not contain any audio presentations.
+ */
+ @NonNull
+ public List<AudioPresentation> getAudioPresentations(int trackIndex) {
+ return new ArrayList<AudioPresentation>();
+ }
+
+ /**
* Get the PSSH info if present.
* @return a map of uuid-to-bytes, with the uuid specifying
* the crypto scheme, and the bytes being the data specific to that scheme.
diff --git a/media/java/android/media/MediaLibraryService2.java b/media/java/android/media/MediaLibraryService2.java
index a901c68..f88f9f2 100644
--- a/media/java/android/media/MediaLibraryService2.java
+++ b/media/java/android/media/MediaLibraryService2.java
@@ -25,6 +25,7 @@
import android.media.MediaSession2.BuilderBase;
import android.media.MediaSession2.ControllerInfo;
import android.media.update.ApiLoader;
+import android.media.update.MediaLibraryService2Provider.LibraryRootProvider;
import android.media.update.MediaLibraryService2Provider.MediaLibrarySessionProvider;
import android.media.update.MediaSession2Provider;
import android.media.update.MediaSessionService2Provider;
@@ -116,15 +117,15 @@
*
* @param controllerInfo information of the controller requesting access to browse media.
* @param rootHints An optional bundle of service-specific arguments to send
- * to the media browser service when connecting and retrieving the
+ * to the media library service when connecting and retrieving the
* root id for browsing, or null if none. The contents of this
* bundle may affect the information returned when browsing.
- * @return The {@link BrowserRoot} for accessing this app's content or null.
- * @see BrowserRoot#EXTRA_RECENT
- * @see BrowserRoot#EXTRA_OFFLINE
- * @see BrowserRoot#EXTRA_SUGGESTED
+ * @return The {@link LibraryRoot} for accessing this app's content or null.
+ * @see LibraryRoot#EXTRA_RECENT
+ * @see LibraryRoot#EXTRA_OFFLINE
+ * @see LibraryRoot#EXTRA_SUGGESTED
*/
- public @Nullable BrowserRoot onGetRoot(@NonNull ControllerInfo controllerInfo,
+ public @Nullable LibraryRoot onGetRoot(@NonNull ControllerInfo controllerInfo,
@Nullable Bundle rootHints) {
return null;
}
@@ -237,17 +238,17 @@
public @NonNull abstract MediaLibrarySession onCreateSession(String sessionId);
/**
- * Contains information that the browser service needs to send to the client
- * when first connected.
+ * Contains information that the library service needs to send to the client when
+ * {@link MediaBrowser2#getLibraryRoot(Bundle)} is called.
*/
- public static final class BrowserRoot {
+ public static final class LibraryRoot {
/**
- * The lookup key for a boolean that indicates whether the browser service should return a
- * browser root for recently played media items.
+ * The lookup key for a boolean that indicates whether the library service should return a
+ * librar root for recently played media items.
*
- * <p>When creating a media browser for a given media browser service, this key can be
+ * <p>When creating a media browser for a given media library service, this key can be
* supplied as a root hint for retrieving media items that are recently played.
- * If the media browser service can provide such media items, the implementation must return
+ * If the media library service can provide such media items, the implementation must return
* the key in the root hint when
* {@link MediaLibrarySessionCallback#onGetRoot(ControllerInfo, Bundle)} is called back.
*
@@ -259,13 +260,13 @@
public static final String EXTRA_RECENT = "android.media.extra.RECENT";
/**
- * The lookup key for a boolean that indicates whether the browser service should return a
- * browser root for offline media items.
+ * The lookup key for a boolean that indicates whether the library service should return a
+ * library root for offline media items.
*
- * <p>When creating a media browser for a given media browser service, this key can be
+ * <p>When creating a media browser for a given media library service, this key can be
* supplied as a root hint for retrieving media items that are can be played without an
* internet connection.
- * If the media browser service can provide such media items, the implementation must return
+ * If the media library service can provide such media items, the implementation must return
* the key in the root hint when
* {@link MediaLibrarySessionCallback#onGetRoot(ControllerInfo, Bundle)} is called back.
*
@@ -277,14 +278,14 @@
public static final String EXTRA_OFFLINE = "android.media.extra.OFFLINE";
/**
- * The lookup key for a boolean that indicates whether the browser service should return a
- * browser root for suggested media items.
+ * The lookup key for a boolean that indicates whether the library service should return a
+ * library root for suggested media items.
*
- * <p>When creating a media browser for a given media browser service, this key can be
- * supplied as a root hint for retrieving the media items suggested by the media browser
+ * <p>When creating a media browser for a given media library service, this key can be
+ * supplied as a root hint for retrieving the media items suggested by the media library
* service. The list of media items is considered ordered by relevance, first being the top
* suggestion.
- * If the media browser service can provide such media items, the implementation must return
+ * If the media library service can provide such media items, the implementation must return
* the key in the root hint when
* {@link MediaLibrarySessionCallback#onGetRoot(ControllerInfo, Bundle)} is called back.
*
@@ -295,35 +296,31 @@
*/
public static final String EXTRA_SUGGESTED = "android.media.extra.SUGGESTED";
- final private String mRootId;
- final private Bundle mExtras;
+ private final LibraryRootProvider mProvider;
/**
- * Constructs a browser root.
+ * Constructs a library root.
* @param rootId The root id for browsing.
- * @param extras Any extras about the browser service.
+ * @param extras Any extras about the library service.
*/
- public BrowserRoot(@NonNull String rootId, @Nullable Bundle extras) {
- if (rootId == null) {
- throw new IllegalArgumentException("The root id in BrowserRoot cannot be null. " +
- "Use null for BrowserRoot instead.");
- }
- mRootId = rootId;
- mExtras = extras;
+ public LibraryRoot(@NonNull Context context,
+ @NonNull String rootId, @Nullable Bundle extras) {
+ mProvider = ApiLoader.getProvider(context).createMediaLibraryService2LibraryRoot(
+ context, this, rootId, extras);
}
/**
* Gets the root id for browsing.
*/
public String getRootId() {
- return mRootId;
+ return mProvider.getRootId_impl();
}
/**
- * Gets any extras about the browser service.
+ * Gets any extras about the library service.
*/
public Bundle getExtras() {
- return mExtras;
+ return mProvider.getExtras_impl();
}
}
}
diff --git a/media/java/android/media/MediaRecorder.java b/media/java/android/media/MediaRecorder.java
index 78477f7..62240ce 100644
--- a/media/java/android/media/MediaRecorder.java
+++ b/media/java/android/media/MediaRecorder.java
@@ -25,6 +25,7 @@
import android.os.Looper;
import android.os.Message;
import android.os.PersistableBundle;
+import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
import android.view.Surface;
@@ -34,6 +35,8 @@
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.List;
import com.android.internal.annotations.GuardedBy;
@@ -1406,6 +1409,31 @@
private native final int native_getRoutedDeviceId();
private native final void native_enableDeviceCallback(boolean enabled);
+ //--------------------------------------------------------------------------
+ // Microphone information
+ //--------------------
+ /**
+ * Return A lists of {@link MicrophoneInfo} representing the active microphones.
+ * By querying channel mapping for each active microphone, developer can know how
+ * the microphone is used by each channels or a capture stream.
+ *
+ * @return a lists of {@link MicrophoneInfo} representing the active microphones
+ * @throws IOException if an error occurs
+ */
+ public List<MicrophoneInfo> getActiveMicrophones() throws IOException {
+ ArrayList<MicrophoneInfo> activeMicrophones = new ArrayList<>();
+ int status = native_getActiveMicrophones(activeMicrophones);
+ if (status != AudioManager.SUCCESS) {
+ Log.e(TAG, "getActiveMicrophones failed:" + status);
+ return new ArrayList<MicrophoneInfo>();
+ }
+ AudioManager.setPortIdForMicrophones(activeMicrophones);
+ return activeMicrophones;
+ }
+
+ private native final int native_getActiveMicrophones(
+ ArrayList<MicrophoneInfo> activeMicrophones);
+
/**
* Called from native code when an interesting event happens. This method
* just uses the EventHandler system to post the event back to the main app thread.
diff --git a/media/java/android/media/MediaSession2.java b/media/java/android/media/MediaSession2.java
index acf9615..5670bd8 100644
--- a/media/java/android/media/MediaSession2.java
+++ b/media/java/android/media/MediaSession2.java
@@ -31,6 +31,7 @@
import android.media.update.ApiLoader;
import android.media.update.MediaSession2Provider;
import android.media.update.MediaSession2Provider.BuilderBaseProvider;
+import android.media.update.MediaSession2Provider.CommandButtonProvider;
import android.media.update.MediaSession2Provider.CommandGroupProvider;
import android.media.update.MediaSession2Provider.CommandProvider;
import android.media.update.MediaSession2Provider.ControllerInfoProvider;
@@ -768,32 +769,15 @@
* <p>
* It's up to the controller's decision to respect or ignore this customization request.
*/
- // TODO(jaewan): Move this to updatable.
public static class CommandButton {
- private static final String KEY_COMMAND
- = "android.media.media_session2.command_button.command";
- private static final String KEY_ICON_RES_ID
- = "android.media.media_session2.command_button.icon_res_id";
- private static final String KEY_DISPLAY_NAME
- = "android.media.media_session2.command_button.display_name";
- private static final String KEY_EXTRA
- = "android.media.media_session2.command_button.extra";
- private static final String KEY_ENABLED
- = "android.media.media_session2.command_button.enabled";
+ private final CommandButtonProvider mProvider;
- private Command mCommand;
- private int mIconResId;
- private String mDisplayName;
- private Bundle mExtra;
- private boolean mEnabled;
-
- private CommandButton(@Nullable Command command, int iconResId,
- @Nullable String displayName, Bundle extra, boolean enabled) {
- mCommand = command;
- mIconResId = iconResId;
- mDisplayName = displayName;
- mExtra = extra;
- mEnabled = enabled;
+ /**
+ * @hide
+ */
+ @SystemApi
+ public CommandButton(CommandButtonProvider provider) {
+ mProvider = provider;
}
/**
@@ -803,7 +787,7 @@
* @return command or {@code null}
*/
public @Nullable Command getCommand() {
- return mCommand;
+ return mProvider.getCommand_impl();
}
/**
@@ -813,7 +797,7 @@
* @return resource id of the icon. Can be {@code 0}.
*/
public int getIconResId() {
- return mIconResId;
+ return mProvider.getIconResId_impl();
}
/**
@@ -823,7 +807,7 @@
* @return custom display name. Can be {@code null} or empty.
*/
public @Nullable String getDisplayName() {
- return mDisplayName;
+ return mProvider.getDisplayName_impl();
}
/**
@@ -832,7 +816,7 @@
* @return
*/
public @Nullable Bundle getExtra() {
- return mExtra;
+ return mProvider.getExtra_impl();
}
/**
@@ -841,92 +825,50 @@
* @return {@code true} if enabled. {@code false} otherwise.
*/
public boolean isEnabled() {
- return mEnabled;
+ return mProvider.isEnabled_impl();
}
/**
* @hide
*/
- // TODO(jaewan): @SystemApi
- public @NonNull Bundle toBundle() {
- Bundle bundle = new Bundle();
- bundle.putBundle(KEY_COMMAND, mCommand.toBundle());
- bundle.putInt(KEY_ICON_RES_ID, mIconResId);
- bundle.putString(KEY_DISPLAY_NAME, mDisplayName);
- bundle.putBundle(KEY_EXTRA, mExtra);
- bundle.putBoolean(KEY_ENABLED, mEnabled);
- return bundle;
- }
-
- /**
- * @hide
- */
- // TODO(jaewan): @SystemApi
- public static @Nullable CommandButton fromBundle(Context context, Bundle bundle) {
- Builder builder = new Builder();
- builder.setCommand(Command.fromBundle(context, bundle.getBundle(KEY_COMMAND)));
- builder.setIconResId(bundle.getInt(KEY_ICON_RES_ID, 0));
- builder.setDisplayName(bundle.getString(KEY_DISPLAY_NAME));
- builder.setExtra(bundle.getBundle(KEY_EXTRA));
- builder.setEnabled(bundle.getBoolean(KEY_ENABLED));
- try {
- return builder.build();
- } catch (IllegalStateException e) {
- // Malformed or version mismatch. Return null for now.
- return null;
- }
+ @SystemApi
+ public CommandButtonProvider getProvider() {
+ return mProvider;
}
/**
* Builder for {@link CommandButton}.
*/
public static class Builder {
- private Command mCommand;
- private int mIconResId;
- private String mDisplayName;
- private Bundle mExtra;
- private boolean mEnabled;
+ private final CommandButtonProvider.BuilderProvider mProvider;
- public Builder() {
- mEnabled = true;
+ public Builder(@NonNull Context context) {
+ mProvider = ApiLoader.getProvider(context)
+ .createMediaSession2CommandButtonBuilder(context, this);
}
public Builder setCommand(Command command) {
- mCommand = command;
- return this;
+ return mProvider.setCommand_impl(command);
}
public Builder setIconResId(int resId) {
- mIconResId = resId;
- return this;
+ return mProvider.setIconResId_impl(resId);
}
public Builder setDisplayName(String displayName) {
- mDisplayName = displayName;
- return this;
+ return mProvider.setDisplayName_impl(displayName);
}
public Builder setEnabled(boolean enabled) {
- mEnabled = enabled;
- return this;
+ return mProvider.setEnabled_impl(enabled);
}
public Builder setExtra(Bundle extra) {
- mExtra = extra;
- return this;
+ return mProvider.setExtra_impl(extra);
}
public CommandButton build() {
- if (mEnabled && mCommand == null) {
- throw new IllegalStateException("Enabled button needs Command"
- + " for controller to invoke the command");
- }
- if (mCommand != null && mCommand.getCommandCode() == COMMAND_CODE_CUSTOM
- && (mIconResId == 0 || TextUtils.isEmpty(mDisplayName))) {
- throw new IllegalStateException("Custom commands needs icon and"
- + " and name to display");
- }
- return new CommandButton(mCommand, mIconResId, mDisplayName, mExtra, mEnabled);
+ return mProvider.build_impl();
}
}
}
diff --git a/media/java/android/media/MediaSessionService2.java b/media/java/android/media/MediaSessionService2.java
index 6b2de06..0b5dddf 100644
--- a/media/java/android/media/MediaSessionService2.java
+++ b/media/java/android/media/MediaSessionService2.java
@@ -21,10 +21,12 @@
import android.annotation.Nullable;
import android.app.Notification;
import android.app.Service;
+import android.content.Context;
import android.content.Intent;
import android.media.MediaSession2.ControllerInfo;
import android.media.update.ApiLoader;
import android.media.update.MediaSessionService2Provider;
+import android.media.update.MediaSessionService2Provider.MediaNotificationProvider;
import android.os.IBinder;
/**
@@ -165,7 +167,6 @@
* @param state playback state
* @return a {@link MediaNotification}. If it's {@code null}, notification wouldn't be shown.
*/
- // TODO(jaewan): Also add metadata
public MediaNotification onUpdateNotification(PlaybackState2 state) {
return mProvider.onUpdateNotification_impl(state);
}
@@ -204,31 +205,31 @@
* foreground service to keep playback running in the background. It's highly recommended to
* show media style notification here.
*/
- // TODO(jaewan): Should we also move this to updatable?
public static class MediaNotification {
- public final int id;
- public final Notification notification;
-
- private MediaNotification(int id, @NonNull Notification notification) {
- this.id = id;
- this.notification = notification;
- }
+ private final MediaNotificationProvider mProvider;
/**
- * Create a {@link MediaNotification}.
+ * Default constructor
*
+ * @param context context
* @param notificationId notification id to be used for
* {@link android.app.NotificationManager#notify(int, Notification)}.
* @param notification a notification to make session service foreground service. Media
* style notification is recommended here.
- * @return
*/
- public static MediaNotification create(int notificationId,
- @NonNull Notification notification) {
- if (notification == null) {
- throw new IllegalArgumentException("Notification cannot be null");
- }
- return new MediaNotification(notificationId, notification);
+ public MediaNotification(@NonNull Context context,
+ int notificationId, @NonNull Notification notification) {
+ mProvider = ApiLoader.getProvider(context)
+ .createMediaSessionService2MediaNotification(
+ context, this, notificationId, notification);
+ }
+
+ public int getNotificationId() {
+ return mProvider.getNotificationId_impl();
+ }
+
+ public Notification getNotification() {
+ return mProvider.getNotification_impl();
}
}
}
diff --git a/media/java/android/media/MicrophoneInfo.java b/media/java/android/media/MicrophoneInfo.java
new file mode 100644
index 0000000..21f9171
--- /dev/null
+++ b/media/java/android/media/MicrophoneInfo.java
@@ -0,0 +1,342 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.media;
+
+import android.annotation.IntDef;
+import android.util.Pair;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.List;
+
+/**
+ * Class providing information on a microphone. It indicates the location and orientation of the
+ * microphone on the device as well as useful information like frequency response and sensitivity.
+ * It can be used by applications implementing special pre processing effects like noise suppression
+ * of beam forming that need to know about precise microphone characteristics in order to adapt
+ * their algorithms.
+ */
+public final class MicrophoneInfo {
+
+ /**
+ * A microphone that the location is unknown.
+ */
+ public static final int LOCATION_UNKNOWN = 0;
+
+ /**
+ * A microphone that locate on main body of the device.
+ */
+ public static final int LOCATION_MAINBODY = 1;
+
+ /**
+ * A microphone that locate on a movable main body of the device.
+ */
+ public static final int LOCATION_MAINBODY_MOVABLE = 2;
+
+ /**
+ * A microphone that locate on a peripheral.
+ */
+ public static final int LOCATION_PERIPHERAL = 3;
+
+ /**
+ * Unknown microphone directionality.
+ */
+ public static final int DIRECTIONALITY_UNKNOW = 0;
+
+ /**
+ * Microphone directionality type: omni.
+ */
+ public static final int DIRECTIONALITY_OMNI = 1;
+
+ /**
+ * Microphone directionality type: bi-directional.
+ */
+ public static final int DIRECTIONALITY_BI_DIRECTIONAL = 2;
+
+ /**
+ * Microphone directionality type: cardioid.
+ */
+ public static final int DIRECTIONALITY_CARDIOID = 3;
+
+ /**
+ * Microphone directionality type: hyper cardioid.
+ */
+ public static final int DIRECTIONALITY_HYPER_CARDIOID = 4;
+
+ /**
+ * Microphone directionality type: super cardioid.
+ */
+ public static final int DIRECTIONALITY_SUPER_CARDIOID = 5;
+
+ /**
+ * The channel contains raw audio from this microphone.
+ */
+ public static final int CHANNEL_MAPPING_DIRECT = 1;
+
+ /**
+ * The channel contains processed audio from this microphone and possibly another microphone.
+ */
+ public static final int CHANNEL_MAPPING_PROCESSED = 2;
+
+ /** @hide */
+ @IntDef(flag = true, prefix = { "LOCATION_" }, value = {
+ LOCATION_UNKNOWN,
+ LOCATION_MAINBODY,
+ LOCATION_MAINBODY_MOVABLE,
+ LOCATION_PERIPHERAL,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface MicrophoneLocation {}
+
+ /** @hide */
+ @IntDef(flag = true, prefix = { "DIRECTIONALITY_" }, value = {
+ DIRECTIONALITY_UNKNOW,
+ DIRECTIONALITY_OMNI,
+ DIRECTIONALITY_BI_DIRECTIONAL,
+ DIRECTIONALITY_CARDIOID,
+ DIRECTIONALITY_HYPER_CARDIOID,
+ DIRECTIONALITY_SUPER_CARDIOID,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface MicrophoneDirectionality {}
+
+ private Coordinate3F mPosition;
+ private Coordinate3F mOrientation;
+ private String mDeviceId;
+ private String mAddress;
+ private List<Pair<Float, Float>> mFrequencyResponse;
+ private List<Pair<Integer, Integer>> mChannelMapping;
+ private float mMaxSpl;
+ private float mMinSpl;
+ private float mSensitivity;
+ private int mLocation;
+ private int mGroup; /* Usually 0 will be used for main body. */
+ private int mIndexInTheGroup;
+ private int mPortId; /* mPortId will correspond to the id in AudioPort */
+ private int mType;
+ private int mDirectionality;
+
+ MicrophoneInfo(String deviceId, int type, String address, int location,
+ int group, int indexInTheGroup, Coordinate3F position,
+ Coordinate3F orientation, List<Pair<Float, Float>> frequencyResponse,
+ List<Pair<Integer, Integer>> channelMapping, float sensitivity, float maxSpl,
+ float minSpl, int directionality) {
+ mDeviceId = deviceId;
+ mType = type;
+ mAddress = address;
+ mLocation = location;
+ mGroup = group;
+ mIndexInTheGroup = indexInTheGroup;
+ mPosition = position;
+ mOrientation = orientation;
+ mFrequencyResponse = frequencyResponse;
+ mChannelMapping = channelMapping;
+ mSensitivity = sensitivity;
+ mMaxSpl = maxSpl;
+ mMinSpl = minSpl;
+ mDirectionality = directionality;
+ }
+
+ /**
+ * Returns alphanumeric code that uniquely identifies the device.
+ *
+ * @return the description of the microphone
+ */
+ public String getDescription() {
+ return mDeviceId;
+ }
+
+ /**
+ * Returns The system unique device ID that corresponds to the id
+ * returned by {@link AudioDeviceInfo#getId()}.
+ *
+ * @return the microphone's id
+ */
+ public int getId() {
+ return mPortId;
+ }
+
+ /**
+ * @hide
+ * Returns the internal device type (e.g AudioSystem.DEVICE_IN_BUILTIN_MIC).
+ * The internal device type could be used when getting microphone's port id
+ * by matching type and address.
+ *
+ * @return the internal device type
+ */
+ public int getInternalDeviceType() {
+ return mType;
+ }
+
+ /**
+ * Returns the device type identifier of the microphone (e.g AudioDeviceInfo.TYPE_BUILTIN_MIC).
+ *
+ * @return the device type of the microphone
+ */
+ public int getType() {
+ return AudioDeviceInfo.convertInternalDeviceToDeviceType(mType);
+ }
+
+ /**
+ * @hide
+ * Returns The "address" string of the microphone that corresponds to the
+ * address returned by {@link AudioDeviceInfo#getAddress()}
+ * @return the address of the microphone
+ */
+ public String getAddress() {
+ return mAddress;
+ }
+
+ /**
+ * Returns the location of the microphone. The return value is
+ * one of {@link #LOCATION_UNKNOWN}, {@link #LOCATION_MAINBODY},
+ * {@link #LOCATION_MAINBODY_MOVABLE}, or {@link #LOCATION_PERIPHERAL}.
+ *
+ * @return the location of the microphone
+ */
+ public @MicrophoneLocation int getLocation() {
+ return mLocation;
+ }
+
+ /**
+ * Returns A device group id that can be used to group together microphones on the same
+ * peripheral, attachments or logical groups. Main body is usually group 0.
+ *
+ * @return the group of the microphone
+ */
+ public int getGroup() {
+ return mGroup;
+ }
+
+ /**
+ * Returns unique index for device within its group.
+ *
+ * @return the microphone's index in its group
+ */
+ public int getIndexInTheGroup() {
+ return mIndexInTheGroup;
+ }
+
+ /**
+ * Returns A {@link Coordinate3F} object that represents the geometric location of microphone
+ * in meters, from botton-left-back corner of appliance. X-axis, Y-axis and Z-axis show
+ * as the x, y, z values.
+ *
+ * @return the geometric location of the microphone
+ */
+ public Coordinate3F getPosition() {
+ return mPosition;
+ }
+
+ /**
+ * Returns A {@link Coordinate3F} object that represents the orientation of microphone.
+ * X-axis, Y-axis and Z-axis show as the x, y, z value. The orientation will be normalized
+ * such as sqrt(x^2 + y^2 + z^2) equals 1.
+ *
+ * @return the orientation of the microphone
+ */
+ public Coordinate3F getOrientation() {
+ return mOrientation;
+ }
+
+ /**
+ * Returns a {@link android.util.Pair} list of frequency responses.
+ * For every {@link android.util.Pair} in the list, the first value represents frequency in Hz,
+ * and the second value represents response in dB.
+ *
+ * @return the frequency response of the microphone
+ */
+ public List<Pair<Float, Float>> getFrequencyResponse() {
+ return mFrequencyResponse;
+ }
+
+ /**
+ * Returns a {@link android.util.Pair} list for channel mapping, which indicating how this
+ * microphone is used by each channels or a capture stream. For each {@link android.util.Pair},
+ * the first value is channel index, the second value is channel mapping type, which could be
+ * either {@link #CHANNEL_MAPPING_DIRECT} or {@link #CHANNEL_MAPPING_PROCESSED}.
+ * If a channel has contributions from more than one microphone, it is likely the HAL
+ * did some extra processing to combine the sources, but this is to be inferred by the user.
+ * Empty list when the MicrophoneInfo is returned by AudioManager.getMicrophones().
+ * At least one entry when the MicrophoneInfo is returned by AudioRecord.getActiveMicrophones().
+ *
+ * @return a {@link android.util.Pair} list for channel mapping
+ */
+ public List<Pair<Integer, Integer>> getChannelMapping() {
+ return mChannelMapping;
+ }
+
+ /**
+ * Returns the level in dBFS produced by a 1000Hz tone at 94 dB SPL.
+ *
+ * @return the sensitivity of the microphone
+ */
+ public float getSensitivity() {
+ return mSensitivity;
+ }
+
+ /**
+ * Returns the level in dB of the maximum SPL supported by the device at 1000Hz.
+ *
+ * @return the maximum level in dB
+ */
+ public float getMaxSpl() {
+ return mMaxSpl;
+ }
+
+ /**
+ * Returns the level in dB of the minimum SPL that can be registered by the device at 1000Hz.
+ *
+ * @return the minimum level in dB
+ */
+ public float getMinSpl() {
+ return mMinSpl;
+ }
+
+ /**
+ * Returns the directionality of microphone. The return value is one of
+ * {@link #DIRECTIONALITY_UNKNOW}, {@link #DIRECTIONALITY_OMNI},
+ * {@link #DIRECTIONALITY_BI_DIRECTIONAL}, {@link #DIRECTIONALITY_CARDIOID},
+ * {@link #DIRECTIONALITY_HYPER_CARDIOID}, or {@link #DIRECTIONALITY_SUPER_CARDIOID}.
+ *
+ * @return the directionality of microphone
+ */
+ public @MicrophoneDirectionality int getDirectionality() {
+ return mDirectionality;
+ }
+
+ /**
+ * Set the port id for the device.
+ * @hide
+ */
+ public void setId(int portId) {
+ mPortId = portId;
+ }
+
+ /* A class containing three float value to represent a 3D coordinate */
+ public class Coordinate3F {
+ public final float x;
+ public final float y;
+ public final float z;
+
+ Coordinate3F(float x, float y, float z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+ }
+}
diff --git a/media/java/android/media/RingtoneManager.java b/media/java/android/media/RingtoneManager.java
index 3eb9d52..fefa1ed 100644
--- a/media/java/android/media/RingtoneManager.java
+++ b/media/java/android/media/RingtoneManager.java
@@ -28,11 +28,13 @@
import android.content.ContentUris;
import android.content.Context;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.UserInfo;
import android.database.Cursor;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Environment;
+import android.os.FileUtils;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.Process;
@@ -47,22 +49,17 @@
import com.android.internal.database.SortCursor;
-import libcore.io.Streams;
-
import java.io.Closeable;
import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
-import static android.content.ContentProvider.maybeAddUserId;
-import static android.content.pm.PackageManager.NameNotFoundException;
-
/**
* RingtoneManager provides access to ringtones, notification, and other types
* of sounds. It manages querying the different media providers and combines the
@@ -855,7 +852,7 @@
final Uri cacheUri = getCacheForType(type, context.getUserId());
try (InputStream in = openRingtone(context, ringtoneUri);
OutputStream out = resolver.openOutputStream(cacheUri)) {
- Streams.copy(in, out);
+ FileUtils.copy(in, out);
} catch (IOException e) {
Log.w(TAG, "Failed to cache ringtone: " + e);
}
@@ -960,7 +957,7 @@
// Copy contents to external ringtone storage. Throws IOException if the copy fails.
try (final InputStream input = mContext.getContentResolver().openInputStream(fileUri);
final OutputStream output = new FileOutputStream(outFile)) {
- Streams.copy(input, output);
+ FileUtils.copy(input, output);
}
// Tell MediaScanner about the new file. Wait for it to assign a {@link Uri}.
diff --git a/media/java/android/media/update/MediaBrowser2Provider.java b/media/java/android/media/update/MediaBrowser2Provider.java
index 67680c7..17256a8 100644
--- a/media/java/android/media/update/MediaBrowser2Provider.java
+++ b/media/java/android/media/update/MediaBrowser2Provider.java
@@ -23,7 +23,7 @@
* @hide
*/
public interface MediaBrowser2Provider extends MediaController2Provider {
- void getBrowserRoot_impl(Bundle rootHints);
+ void getLibraryRoot_impl(Bundle rootHints);
void subscribe_impl(String parentId, Bundle options);
void unsubscribe_impl(String parentId, Bundle options);
diff --git a/media/java/android/media/update/MediaLibraryService2Provider.java b/media/java/android/media/update/MediaLibraryService2Provider.java
index 87f509a..923551a 100644
--- a/media/java/android/media/update/MediaLibraryService2Provider.java
+++ b/media/java/android/media/update/MediaLibraryService2Provider.java
@@ -33,4 +33,9 @@
void notifyChildrenChanged_impl(ControllerInfo controller, String parentId, Bundle options);
void notifyChildrenChanged_impl(String parentId, Bundle options);
}
+
+ interface LibraryRootProvider {
+ String getRootId_impl();
+ Bundle getExtras_impl();
+ }
}
diff --git a/media/java/android/media/update/MediaSession2Provider.java b/media/java/android/media/update/MediaSession2Provider.java
index da4d0c7..9abf34a 100644
--- a/media/java/android/media/update/MediaSession2Provider.java
+++ b/media/java/android/media/update/MediaSession2Provider.java
@@ -24,6 +24,7 @@
import android.media.MediaSession2;
import android.media.MediaSession2.Command;
import android.media.MediaSession2.CommandButton;
+import android.media.MediaSession2.CommandButton.Builder;
import android.media.MediaSession2.CommandGroup;
import android.media.MediaSession2.ControllerInfo;
import android.media.MediaSession2.PlaylistParams;
@@ -82,6 +83,23 @@
Bundle toBundle_impl();
}
+ interface CommandButtonProvider {
+ Command getCommand_impl();
+ int getIconResId_impl();
+ String getDisplayName_impl();
+ Bundle getExtra_impl();
+ boolean isEnabled_impl();
+
+ interface BuilderProvider {
+ Builder setCommand_impl(Command command);
+ Builder setIconResId_impl(int resId);
+ Builder setDisplayName_impl(String displayName);
+ Builder setEnabled_impl(boolean enabled);
+ Builder setExtra_impl(Bundle extra);
+ CommandButton build_impl();
+ }
+ }
+
interface ControllerInfoProvider {
String getPackageName_impl();
int getUid_impl();
diff --git a/media/java/android/media/update/MediaSessionService2Provider.java b/media/java/android/media/update/MediaSessionService2Provider.java
index 9455da7..42e7587 100644
--- a/media/java/android/media/update/MediaSessionService2Provider.java
+++ b/media/java/android/media/update/MediaSessionService2Provider.java
@@ -17,6 +17,7 @@
package android.media.update;
import android.annotation.SystemApi;
+import android.app.Notification;
import android.content.Intent;
import android.media.MediaSession2;
import android.media.MediaSessionService2.MediaNotification;
@@ -33,4 +34,9 @@
// Service
void onCreate_impl();
IBinder onBind_impl(Intent intent);
+
+ interface MediaNotificationProvider {
+ int getNotificationId_impl();
+ Notification getNotification_impl();
+ }
}
diff --git a/media/java/android/media/update/StaticProvider.java b/media/java/android/media/update/StaticProvider.java
index 922b452..862a402 100644
--- a/media/java/android/media/update/StaticProvider.java
+++ b/media/java/android/media/update/StaticProvider.java
@@ -17,6 +17,7 @@
package android.media.update;
import android.annotation.Nullable;
+import android.app.Notification;
import android.content.Context;
import android.media.DataSourceDesc;
import android.media.MediaBrowser2;
@@ -25,25 +26,31 @@
import android.media.MediaController2.ControllerCallback;
import android.media.MediaItem2;
import android.media.MediaLibraryService2;
+import android.media.MediaLibraryService2.LibraryRoot;
import android.media.MediaLibraryService2.MediaLibrarySession;
import android.media.MediaLibraryService2.MediaLibrarySessionBuilder;
import android.media.MediaLibraryService2.MediaLibrarySessionCallback;
import android.media.MediaMetadata2;
import android.media.MediaPlayerInterface;
import android.media.MediaSession2;
+import android.media.MediaSession2.CommandButton.Builder;
import android.media.MediaSession2.PlaylistParams;
import android.media.MediaSession2.SessionCallback;
import android.media.MediaSessionService2;
+import android.media.MediaSessionService2.MediaNotification;
import android.media.PlaybackState2;
import android.media.Rating2;
import android.media.SessionPlayer2;
import android.media.SessionToken2;
import android.media.VolumeProvider2;
+import android.media.update.MediaLibraryService2Provider.LibraryRootProvider;
import android.media.update.MediaSession2Provider.BuilderBaseProvider;
+import android.media.update.MediaSession2Provider.CommandButtonProvider.BuilderProvider;
import android.media.update.MediaSession2Provider.CommandGroupProvider;
import android.media.update.MediaSession2Provider.CommandProvider;
import android.media.update.MediaSession2Provider.ControllerInfoProvider;
import android.media.update.MediaSession2Provider.PlaylistParamsProvider;
+import android.media.update.MediaSessionService2Provider.MediaNotificationProvider;
import android.os.Bundle;
import android.os.IInterface;
import android.util.AttributeSet;
@@ -79,6 +86,7 @@
PlaylistParams playlistParams, int repeatMode, int shuffleMode,
MediaMetadata2 playlistMetadata);
PlaylistParams fromBundle_PlaylistParams(Context context, Bundle bundle);
+ BuilderProvider createMediaSession2CommandButtonBuilder(Context context, Builder builder);
BuilderBaseProvider<MediaSession2, SessionCallback> createMediaSession2Builder(
Context context, MediaSession2.Builder instance, MediaPlayerInterface player);
@@ -89,12 +97,16 @@
SessionToken2 token, Executor executor, BrowserCallback callback);
MediaSessionService2Provider createMediaSessionService2(MediaSessionService2 instance);
+ MediaNotificationProvider createMediaSessionService2MediaNotification(Context context,
+ MediaNotification mediaNotification, int notificationId, Notification notification);
MediaSessionService2Provider createMediaLibraryService2(MediaLibraryService2 instance);
BuilderBaseProvider<MediaLibrarySession, MediaLibrarySessionCallback>
createMediaLibraryService2Builder(
Context context, MediaLibrarySessionBuilder instance, MediaPlayerInterface player,
Executor callbackExecutor, MediaLibrarySessionCallback callback);
+ LibraryRootProvider createMediaLibraryService2LibraryRoot(Context context, LibraryRoot instance,
+ String rootId, Bundle extras);
SessionToken2Provider createSessionToken2(Context context, SessionToken2 instance,
String packageName, String serviceName, int uid);
diff --git a/media/jni/android_media_AudioPresentation.h b/media/jni/android_media_AudioPresentation.h
new file mode 100644
index 0000000..71b8dac
--- /dev/null
+++ b/media/jni/android_media_AudioPresentation.h
@@ -0,0 +1,173 @@
+/*
+ * Copyright 2018, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ANDROID_MEDIA_AUDIO_PRESENTATION_H_
+#define _ANDROID_MEDIA_AUDIO_PRESENTATION_H_
+
+#include "jni.h"
+
+#include <media/AudioPresentationInfo.h>
+#include <media/stagefright/foundation/ADebug.h>
+#include <media/stagefright/foundation/AMessage.h>
+
+#include <nativehelper/ScopedLocalRef.h>
+
+namespace android {
+
+struct JAudioPresentationInfo {
+ struct fields_t {
+ jclass clazz;
+ jmethodID constructID;
+
+ // list parameters
+ jclass listclazz;
+ jmethodID listConstructId;
+ jmethodID listAddId;
+
+ void init(JNIEnv *env) {
+ jclass lclazz = env->FindClass("android/media/AudioPresentation");
+ if (lclazz == NULL) {
+ return;
+ }
+
+ clazz = (jclass)env->NewGlobalRef(lclazz);
+ if (clazz == NULL) {
+ return;
+ }
+
+ constructID = env->GetMethodID(clazz, "<init>",
+ "(IILjava/util/Map;Ljava/lang/String;IZZZ)V");
+ env->DeleteLocalRef(lclazz);
+
+ // list objects
+ jclass llistclazz = env->FindClass("java/util/ArrayList");
+ CHECK(llistclazz != NULL);
+ listclazz = static_cast<jclass>(env->NewGlobalRef(llistclazz));
+ CHECK(listclazz != NULL);
+ listConstructId = env->GetMethodID(listclazz, "<init>", "()V");
+ CHECK(listConstructId != NULL);
+ listAddId = env->GetMethodID(listclazz, "add", "(Ljava/lang/Object;)Z");
+ CHECK(listAddId != NULL);
+ env->DeleteLocalRef(llistclazz);
+ }
+
+ void exit(JNIEnv *env) {
+ env->DeleteGlobalRef(clazz);
+ clazz = NULL;
+ env->DeleteGlobalRef(listclazz);
+ listclazz = NULL;
+ }
+ };
+
+ static status_t ConvertMessageToMap(JNIEnv *env, const sp<AMessage> &msg, jobject *map) {
+ ScopedLocalRef<jclass> hashMapClazz(env, env->FindClass("java/util/HashMap"));
+
+ if (hashMapClazz.get() == NULL) {
+ return -EINVAL;
+ }
+ jmethodID hashMapConstructID =
+ env->GetMethodID(hashMapClazz.get(), "<init>", "()V");
+
+ if (hashMapConstructID == NULL) {
+ return -EINVAL;
+ }
+ jmethodID hashMapPutID =
+ env->GetMethodID(
+ hashMapClazz.get(),
+ "put",
+ "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+
+ if (hashMapPutID == NULL) {
+ return -EINVAL;
+ }
+
+ jobject hashMap = env->NewObject(hashMapClazz.get(), hashMapConstructID);
+
+ for (size_t i = 0; i < msg->countEntries(); ++i) {
+ AMessage::Type valueType;
+ const char *key = msg->getEntryNameAt(i, &valueType);
+
+ if (!strncmp(key, "android._", 9)) {
+ // don't expose private keys (starting with android._)
+ continue;
+ }
+
+ jobject valueObj = NULL;
+
+ AString val;
+ CHECK(msg->findString(key, &val));
+
+ valueObj = env->NewStringUTF(val.c_str());
+
+ if (valueObj != NULL) {
+ jstring keyObj = env->NewStringUTF(key);
+
+ env->CallObjectMethod(hashMap, hashMapPutID, keyObj, valueObj);
+
+ env->DeleteLocalRef(keyObj); keyObj = NULL;
+ env->DeleteLocalRef(valueObj); valueObj = NULL;
+ }
+ }
+
+ *map = hashMap;
+
+ return OK;
+ }
+
+ jobject asJobject(JNIEnv *env, const fields_t& fields, const AudioPresentationInfo &info) {
+ jobject list = env->NewObject(fields.listclazz, fields.listConstructId);
+
+ for (size_t i = 0; i < info.countPresentations(); ++i) {
+ const sp<AudioPresentation> &ap = info.getPresentation(i);
+ jobject jLabelObject;
+
+ sp<AMessage> labelMessage = new AMessage();
+ for (size_t i = 0; i < ap->mLabels.size(); ++i) {
+ labelMessage->setString(ap->mLabels.keyAt(i).string(),
+ ap->mLabels.valueAt(i).string());
+ }
+ if (ConvertMessageToMap(env, labelMessage, &jLabelObject) != OK) {
+ return NULL;
+ }
+ jstring jLanguage = env->NewStringUTF(ap->mLanguage.string());
+
+ jobject jValueObj = env->NewObject(fields.clazz, fields.constructID,
+ static_cast<jint>(ap->mPresentationId),
+ static_cast<jint>(ap->mProgramId),
+ jLabelObject,
+ jLanguage,
+ static_cast<jint>(ap->mMasteringIndication),
+ static_cast<jboolean>((ap->mAudioDescriptionAvailable == 1) ?
+ 1 : 0),
+ static_cast<jboolean>((ap->mSpokenSubtitlesAvailable == 1) ?
+ 1 : 0),
+ static_cast<jboolean>((ap->mDialogueEnhancementAvailable == 1) ?
+ 1 : 0));
+ if (jValueObj == NULL) {
+ env->DeleteLocalRef(jLanguage); jLanguage = NULL;
+ return NULL;
+ }
+
+ env->CallBooleanMethod(list, fields.listAddId, jValueObj);
+ env->DeleteLocalRef(jValueObj); jValueObj = NULL;
+ env->DeleteLocalRef(jLanguage); jLanguage = NULL;
+ }
+ return list;
+ }
+};
+} // namespace android
+
+#endif // _ANDROID_MEDIA_AUDIO_PRESENTATION_H_
diff --git a/media/jni/android_media_MediaRecorder.cpp b/media/jni/android_media_MediaRecorder.cpp
index d2bc174..b3a8b21 100644
--- a/media/jni/android_media_MediaRecorder.cpp
+++ b/media/jni/android_media_MediaRecorder.cpp
@@ -20,6 +20,7 @@
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
+#include <vector>
//#define LOG_NDEBUG 0
#define LOG_TAG "MediaRecorderJNI"
@@ -29,6 +30,7 @@
#include <camera/Camera.h>
#include <media/mediarecorder.h>
#include <media/MediaAnalyticsItem.h>
+#include <media/MicrophoneInfo.h>
#include <media/stagefright/PersistentSurface.h>
#include <utils/threads.h>
@@ -36,7 +38,9 @@
#include "jni.h"
#include <nativehelper/JNIHelp.h>
+#include "android_media_AudioErrors.h"
#include "android_media_MediaMetricsJNI.h"
+#include "android_media_MicrophoneInfo.h"
#include "android_runtime/AndroidRuntime.h"
#include <system/audio.h>
@@ -61,6 +65,12 @@
};
static fields_t fields;
+struct ArrayListFields {
+ jmethodID add;
+ jclass classId;
+};
+static ArrayListFields gArrayListFields;
+
static Mutex sLock;
// ----------------------------------------------------------------------------
@@ -565,6 +575,13 @@
if (fields.post_event == NULL) {
return;
}
+
+ clazz = env->FindClass("java/util/ArrayList");
+ if (clazz == NULL) {
+ return;
+ }
+ gArrayListFields.add = env->GetMethodID(clazz, "add", "(Ljava/lang/Object;)Z");
+ gArrayListFields.classId = static_cast<jclass>(env->NewGlobalRef(clazz));
}
@@ -707,6 +724,45 @@
process_media_recorder_call(env, mr->enableAudioDeviceCallback(enabled),
"java/lang/RuntimeException", "enableDeviceCallback failed.");
}
+
+static jint
+android_media_MediaRecord_getActiveMicrophones(JNIEnv *env,
+ jobject thiz, jobject jActiveMicrophones) {
+ if (jActiveMicrophones == NULL) {
+ ALOGE("jActiveMicrophones is null");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+ if (!env->IsInstanceOf(jActiveMicrophones, gArrayListFields.classId)) {
+ ALOGE("getActiveMicrophones not an arraylist");
+ return (jint)AUDIO_JAVA_BAD_VALUE;
+ }
+
+ sp<MediaRecorder> mr = getMediaRecorder(env, thiz);
+ if (mr == NULL) {
+ jniThrowException(env, "java/lang/IllegalStateException", NULL);
+ return (jint)AUDIO_JAVA_NO_INIT;
+ }
+
+ jint jStatus = AUDIO_JAVA_SUCCESS;
+ std::vector<media::MicrophoneInfo> activeMicrophones;
+ status_t status = mr->getActiveMicrophones(&activeMicrophones);
+ if (status != NO_ERROR) {
+ ALOGE_IF(status != NO_ERROR, "MediaRecorder::getActiveMicrophones error %d", status);
+ jStatus = nativeToJavaStatus(status);
+ return jStatus;
+ }
+
+ for (size_t i = 0; i < activeMicrophones.size(); i++) {
+ jobject jMicrophoneInfo;
+ jStatus = convertMicrophoneInfoFromNative(env, &jMicrophoneInfo, &activeMicrophones[i]);
+ if (jStatus != AUDIO_JAVA_SUCCESS) {
+ return jStatus;
+ }
+ env->CallBooleanMethod(jActiveMicrophones, gArrayListFields.add, jMicrophoneInfo);
+ env->DeleteLocalRef(jMicrophoneInfo);
+ }
+ return jStatus;
+}
// ----------------------------------------------------------------------------
static const JNINativeMethod gMethods[] = {
@@ -742,7 +798,9 @@
{"native_setInputDevice", "(I)Z", (void *)android_media_MediaRecorder_setInputDevice},
{"native_getRoutedDeviceId", "()I", (void *)android_media_MediaRecorder_getRoutedDeviceId},
- {"native_enableDeviceCallback", "(Z)V", (void *)android_media_MediaRecorder_enableDeviceCallback},
+ {"native_enableDeviceCallback", "(Z)V", (void *)android_media_MediaRecorder_enableDeviceCallback},
+
+ {"native_getActiveMicrophones", "(Ljava/util/ArrayList;)I", (void *)android_media_MediaRecord_getActiveMicrophones},
};
// This function only registers the native methods, and is called from
diff --git a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
index 8b01aef..9f165bc 100644
--- a/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
+++ b/packages/DefaultContainerService/src/com/android/defcontainer/DefaultContainerService.java
@@ -30,6 +30,7 @@
import android.content.res.ObbScanner;
import android.os.Binder;
import android.os.Environment.UserEnvironment;
+import android.os.FileUtils;
import android.os.IBinder;
import android.os.ParcelFileDescriptor;
import android.os.Process;
@@ -43,7 +44,6 @@
import com.android.internal.util.ArrayUtils;
import libcore.io.IoUtils;
-import libcore.io.Streams;
import java.io.File;
import java.io.FileInputStream;
@@ -260,7 +260,7 @@
in = new FileInputStream(sourcePath);
out = new ParcelFileDescriptor.AutoCloseOutputStream(
target.open(targetName, ParcelFileDescriptor.MODE_READ_WRITE));
- Streams.copy(in, out);
+ FileUtils.copy(in, out);
} finally {
IoUtils.closeQuietly(out);
IoUtils.closeQuietly(in);
diff --git a/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixin.java b/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixin.java
index 7983896..c23f226 100644
--- a/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixin.java
+++ b/packages/SettingsLib/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixin.java
@@ -17,21 +17,20 @@
package com.android.settingslib.core.instrumentation;
import android.app.Activity;
-import android.content.Context;
+import android.arch.lifecycle.Lifecycle.Event;
+import android.arch.lifecycle.LifecycleObserver;
+import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Intent;
import android.os.SystemClock;
import com.android.internal.logging.nano.MetricsProto;
-import com.android.settingslib.core.lifecycle.LifecycleObserver;
-import com.android.settingslib.core.lifecycle.events.OnPause;
-import com.android.settingslib.core.lifecycle.events.OnResume;
import static com.android.settingslib.core.instrumentation.Instrumentable.METRICS_CATEGORY_UNKNOWN;
/**
* Logs visibility change of a fragment.
*/
-public class VisibilityLoggerMixin implements LifecycleObserver, OnResume, OnPause {
+public class VisibilityLoggerMixin implements LifecycleObserver {
private static final String TAG = "VisibilityLoggerMixin";
@@ -55,7 +54,7 @@
mMetricsFeature = metricsFeature;
}
- @Override
+ @OnLifecycleEvent(Event.ON_RESUME)
public void onResume() {
mVisibleTimestamp = SystemClock.elapsedRealtime();
if (mMetricsFeature != null && mMetricsCategory != METRICS_CATEGORY_UNKNOWN) {
@@ -63,7 +62,7 @@
}
}
- @Override
+ @OnLifecycleEvent(Event.ON_PAUSE)
public void onPause() {
mVisibleTimestamp = 0;
if (mMetricsFeature != null && mMetricsCategory != METRICS_CATEGORY_UNKNOWN) {
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixinTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixinTest.java
index a264886..1ab6afe 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixinTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/core/instrumentation/VisibilityLoggerMixinTest.java
@@ -18,6 +18,7 @@
import static com.android.settingslib.core.instrumentation.Instrumentable.METRICS_CATEGORY_UNKNOWN;
import static org.mockito.ArgumentMatchers.nullable;
+import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
@@ -30,6 +31,8 @@
import android.content.Context;
import android.content.Intent;
+import android.os.Bundle;
+import android.support.v4.app.FragmentActivity;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settingslib.SettingsLibRobolectricTestRunner;
import com.android.settingslib.TestConfig;
@@ -39,6 +42,8 @@
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.robolectric.Robolectric;
+import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
@@ -110,6 +115,30 @@
.hidden(nullable(Context.class), anyInt());
}
+ @Test
+ public void activityShouldBecomeVisibleAndHide() {
+ ActivityController<TestActivity> ac = Robolectric.buildActivity(TestActivity.class);
+ TestActivity testActivity = ac.get();
+ MockitoAnnotations.initMocks(testActivity);
+ ac.create().start().resume();
+ verify(testActivity.mMetricsFeatureProvider, times(1)).visible(any(), anyInt(), anyInt());
+ ac.pause().stop().destroy();
+ verify(testActivity.mMetricsFeatureProvider, times(1)).hidden(any(), anyInt());
+ }
+
+ public static class TestActivity extends FragmentActivity {
+ @Mock
+ MetricsFeatureProvider mMetricsFeatureProvider;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ VisibilityLoggerMixin mixin = new VisibilityLoggerMixin(
+ TestInstrumentable.TEST_METRIC, mMetricsFeatureProvider);
+ getLifecycle().addObserver(mixin);
+ super.onCreate(savedInstanceState);
+ }
+ }
+
private final class TestInstrumentable implements Instrumentable {
public static final int TEST_METRIC = 12345;
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index 7428149..1dc8e46 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -87,7 +87,6 @@
private static final HashSet<String> mValidTables = new HashSet<String>();
- private static final String DATABASE_JOURNAL_SUFFIX = "-journal";
private static final String DATABASE_BACKUP_SUFFIX = "-backup";
private static final String TABLE_SYSTEM = "system";
@@ -148,12 +147,7 @@
}
File databaseFile = mContext.getDatabasePath(getDatabaseName());
if (databaseFile.exists()) {
- databaseFile.delete();
- }
- File databaseJournalFile = mContext.getDatabasePath(getDatabaseName()
- + DATABASE_JOURNAL_SUFFIX);
- if (databaseJournalFile.exists()) {
- databaseJournalFile.delete();
+ SQLiteDatabase.deleteDatabase(databaseFile);
}
}
diff --git a/packages/SystemUI/res/drawable/qs_footer_drag_handle.xml b/packages/SystemUI/res/drawable/qs_footer_drag_handle.xml
new file mode 100644
index 0000000..509cd1f
--- /dev/null
+++ b/packages/SystemUI/res/drawable/qs_footer_drag_handle.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+<shape
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:shape="rectangle" >
+ <solid
+ android:color="#e5e5e5" />
+ <corners android:radius="2dp" />
+</shape>
diff --git a/packages/SystemUI/res/layout/qs_footer_impl.xml b/packages/SystemUI/res/layout/qs_footer_impl.xml
index 9f6a946..100c2aa 100644
--- a/packages/SystemUI/res/layout/qs_footer_impl.xml
+++ b/packages/SystemUI/res/layout/qs_footer_impl.xml
@@ -25,87 +25,121 @@
android:baselineAligned="false"
android:clickable="false"
android:clipChildren="false"
- android:clipToPadding="false"
- android:paddingTop="0dp"
- android:gravity="center_vertical"
- android:orientation="horizontal">
+ android:clipToPadding="false">
+
+ <View
+ android:id="@+id/qs_footer_divider"
+ android:layout_width="match_parent"
+ android:layout_height="1dp"
+ android:layout_gravity="top"
+ android:background="?android:attr/dividerHorizontal"/>
<LinearLayout
android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginStart="16dp"
+ android:layout_height="match_parent"
+ android:layout_marginTop="1dp"
+ android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
- android:gravity="end">
+ android:layout_gravity="center_vertical"
+ android:gravity="end" >
- <com.android.keyguard.CarrierText
- android:id="@+id/qs_carrier_text"
+ <LinearLayout
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="1" >
+ <!-- Add an extra 8dp margin before carrier text without shifting it right -->
+ <android.widget.Space
+ android:layout_width="8dp"
+ android:layout_height="match_parent" />
+
+ <com.android.keyguard.CarrierText
+ android:id="@+id/qs_carrier_text"
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="1"
+ android:gravity="center_vertical|start"
+ android:ellipsize="marquee"
+ android:textAppearance="?android:attr/textAppearanceSmall"
+ android:textColor="?android:attr/textColorPrimary"
+ android:textDirection="locale"
+ android:singleLine="true" />
+ </LinearLayout>
+
+ <FrameLayout
+ android:layout_width="24dp"
+ android:layout_height="match_parent" >
+ <View
+ android:id="@+id/qs_drag_handle_view"
+ android:layout_width="match_parent"
+ android:layout_height="4dp"
+ android:layout_marginTop="28dp"
+ android:background="@drawable/qs_footer_drag_handle" />
+ </FrameLayout>
+
+ <LinearLayout
+ android:id="@+id/qs_footer_actions_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
- android:gravity="center_vertical|start"
- android:ellipsize="marquee"
- android:textAppearance="?android:attr/textAppearanceSmall"
- android:textColor="?android:attr/textColorPrimary"
- android:textDirection="locale"
- android:singleLine="true" />
-
- <com.android.systemui.statusbar.phone.MultiUserSwitch
- android:id="@+id/multi_user_switch"
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:layout_alignParentEnd="true"
- android:background="@drawable/ripple_drawable"
- android:focusable="true">
-
- <ImageView
- android:id="@+id/multi_user_avatar"
- android:layout_width="@dimen/multi_user_avatar_expanded_size"
- android:layout_height="@dimen/multi_user_avatar_expanded_size"
- android:layout_gravity="center"
- android:scaleType="centerInside"/>
- </com.android.systemui.statusbar.phone.MultiUserSwitch>
-
- <com.android.systemui.statusbar.AlphaOptimizedImageView
- android:id="@android:id/edit"
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:background="?android:attr/selectableItemBackgroundBorderless"
- android:clickable="true"
- android:clipToPadding="false"
- android:contentDescription="@string/accessibility_quick_settings_edit"
- android:focusable="true"
- android:padding="16dp"
- android:src="@drawable/ic_mode_edit"
- android:tint="?android:attr/colorForeground"/>
-
- <com.android.systemui.statusbar.AlphaOptimizedFrameLayout
- android:id="@+id/settings_button_container"
- android:layout_width="48dp"
- android:layout_height="48dp"
- android:clipChildren="false"
- android:clipToPadding="false">
-
- <com.android.systemui.statusbar.phone.SettingsButton
- android:id="@+id/settings_button"
- style="@android:style/Widget.Material.Button.Borderless"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
+ android:gravity="end" >
+ <com.android.systemui.statusbar.phone.MultiUserSwitch
+ android:id="@+id/multi_user_switch"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:layout_alignParentEnd="true"
android:background="@drawable/ripple_drawable"
- android:contentDescription="@string/accessibility_quick_settings_settings"
- android:src="@drawable/ic_settings_16dp"
- android:tint="?android:attr/colorForeground"/>
+ android:focusable="true">
+
+ <ImageView
+ android:id="@+id/multi_user_avatar"
+ android:layout_width="@dimen/multi_user_avatar_expanded_size"
+ android:layout_height="@dimen/multi_user_avatar_expanded_size"
+ android:layout_gravity="center"
+ android:scaleType="centerInside"/>
+ </com.android.systemui.statusbar.phone.MultiUserSwitch>
<com.android.systemui.statusbar.AlphaOptimizedImageView
- android:id="@+id/tuner_icon"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingStart="36dp"
- android:paddingEnd="4dp"
- android:src="@drawable/tuner"
- android:tint="?android:attr/textColorTertiary"
- android:visibility="invisible"/>
+ android:id="@android:id/edit"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:background="?android:attr/selectableItemBackgroundBorderless"
+ android:clickable="true"
+ android:clipToPadding="false"
+ android:contentDescription="@string/accessibility_quick_settings_edit"
+ android:focusable="true"
+ android:padding="16dp"
+ android:src="@drawable/ic_mode_edit"
+ android:tint="?android:attr/colorForeground"/>
- </com.android.systemui.statusbar.AlphaOptimizedFrameLayout>
+ <com.android.systemui.statusbar.AlphaOptimizedFrameLayout
+ android:id="@+id/settings_button_container"
+ android:layout_width="48dp"
+ android:layout_height="48dp"
+ android:clipChildren="false"
+ android:clipToPadding="false">
+
+ <com.android.systemui.statusbar.phone.SettingsButton
+ android:id="@+id/settings_button"
+ style="@android:style/Widget.Material.Button.Borderless"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@drawable/ripple_drawable"
+ android:contentDescription="@string/accessibility_quick_settings_settings"
+ android:src="@drawable/ic_settings_16dp"
+ android:tint="?android:attr/colorForeground"/>
+
+ <com.android.systemui.statusbar.AlphaOptimizedImageView
+ android:id="@+id/tuner_icon"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:paddingStart="36dp"
+ android:paddingEnd="4dp"
+ android:src="@drawable/tuner"
+ android:tint="?android:attr/textColorTertiary"
+ android:visibility="invisible"/>
+
+ </com.android.systemui.statusbar.AlphaOptimizedFrameLayout>
+ </LinearLayout>
</LinearLayout>
</com.android.systemui.qs.QSFooterImpl>
diff --git a/packages/SystemUI/res/layout/volume_dialog.xml b/packages/SystemUI/res/layout/volume_dialog.xml
index 117cd14..53dff05 100644
--- a/packages/SystemUI/res/layout/volume_dialog.xml
+++ b/packages/SystemUI/res/layout/volume_dialog.xml
@@ -59,6 +59,7 @@
android:gravity="center"
android:layout_gravity="end"
android:translationZ="8dp"
+ android:clickable="true"
android:orientation="vertical" >
<TextView
@@ -76,7 +77,7 @@
android:id="@+id/ringer_icon"
style="@style/VolumeButtons"
android:background="?android:selectableItemBackgroundBorderless"
- android:layout_width="@dimen/volume_button_size"
+ android:layout_width="@dimen/volume_dialog_panel_width"
android:layout_height="@dimen/volume_button_size"
android:tint="?android:attr/colorAccent"
android:soundEffectsEnabled="false" />
diff --git a/packages/SystemUI/res/layout/volume_dialog_row.xml b/packages/SystemUI/res/layout/volume_dialog_row.xml
index 3e80085..a9e5adf 100644
--- a/packages/SystemUI/res/layout/volume_dialog_row.xml
+++ b/packages/SystemUI/res/layout/volume_dialog_row.xml
@@ -63,6 +63,7 @@
android:background="?android:selectableItemBackgroundBorderless"
android:contentDescription="@string/accessibility_output_chooser"
style="@style/VolumeButtons"
+ android:clickable="false"
android:layout_centerVertical="true"
android:src="@drawable/ic_swap"
android:soundEffectsEnabled="false" />
@@ -70,7 +71,7 @@
</LinearLayout>
<FrameLayout
android:id="@+id/volume_row_slider_frame"
- android:padding="10dp"
+ android:padding="0dp"
android:layout_width="@dimen/volume_dialog_panel_width"
android:layout_height="150dp">
<SeekBar
@@ -80,8 +81,6 @@
android:layout_width="150dp"
android:layout_height="@dimen/volume_dialog_panel_width"
android:layout_gravity="center"
- android:focusable="true"
- android:focusableInTouchMode="true"
android:rotation="270" />
</FrameLayout>
@@ -91,6 +90,7 @@
android:padding="10dp"
android:layout_width="@dimen/volume_button_size"
android:layout_height="@dimen/volume_button_size"
+ android:background="?android:selectableItemBackgroundBorderless"
android:soundEffectsEnabled="false" />
</LinearLayout>
\ No newline at end of file
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index 1cc1cc8..ae910fe 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -124,7 +124,7 @@
<!-- Tiles native to System UI. Order should match "quick_settings_tiles_default" -->
<string name="quick_settings_tiles_stock" translatable="false">
- wifi,cell,battery,dnd,flashlight,rotation,bt,airplane,location,hotspot,inversion,saver,work,cast,night
+ wifi,cell,battery,dnd,flashlight,rotation,bt,airplane,location,hotspot,inversion,saver,work,cast,night,alarm
</string>
<!-- The tiles to display in QuickSettings -->
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 72615ce..5557f8e 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -739,6 +739,8 @@
<string name="quick_settings_wifi_on_label">Wi-Fi On</string>
<!-- QuickSettings: Wifi detail panel, text when there are no items [CHAR LIMIT=NONE] -->
<string name="quick_settings_wifi_detail_empty_text">No Wi-Fi networks available</string>
+ <!-- QuickSettings: Alarm title [CHAR LIMIT=NONE] -->
+ <string name="quick_settings_alarm_title">Alarm</string>
<!-- QuickSettings: Cast title [CHAR LIMIT=NONE] -->
<string name="quick_settings_cast_title">Cast</string>
<!-- QuickSettings: Cast detail panel, status text when casting [CHAR LIMIT=NONE] -->
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 8501519..653e500 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -707,10 +707,6 @@
&& !mLockPatternUtils.isLockScreenDisabled(
KeyguardUpdateMonitor.getCurrentUser()),
mSecondaryDisplayShowing, true /* forceCallbacks */);
- } else {
- // The system's keyguard is disabled or missing.
- setShowingLocked(mLockPatternUtils.isSecure(KeyguardUpdateMonitor.getCurrentUser()),
- mSecondaryDisplayShowing, true);
}
mStatusBarKeyguardViewManager =
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
index b43e99b..e661fa7 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
@@ -44,6 +44,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
+import com.android.settingslib.utils.ThreadUtils;
import com.android.systemui.Dependency;
import com.android.systemui.R;
import com.android.systemui.SystemUI;
@@ -242,7 +243,9 @@
}
// Show the correct version of low battery warning if needed
- maybeShowBatteryWarning(plugged, oldPlugged, oldBucket, bucket);
+ ThreadUtils.postOnBackgroundThread(() -> {
+ maybeShowBatteryWarning(plugged, oldPlugged, oldBucket, bucket);
+ });
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
mScreenOffTime = SystemClock.elapsedRealtime();
diff --git a/packages/SystemUI/src/com/android/systemui/qs/AutoAddTracker.java b/packages/SystemUI/src/com/android/systemui/qs/AutoAddTracker.java
index f960dc5..2a2bc09 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/AutoAddTracker.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/AutoAddTracker.java
@@ -51,10 +51,11 @@
public AutoAddTracker(Context context) {
mContext = context;
mAutoAdded = new ArraySet<>(getAdded());
+ // TODO: remove migration code and shared preferences keys after P release
for (String[] convertPref : CONVERT_PREFS) {
if (Prefs.getBoolean(context, convertPref[0], false)) {
setTileAdded(convertPref[1]);
- Prefs.putBoolean(context, convertPref[0], false);
+ Prefs.remove(context, convertPref[0]);
}
}
mContext.getContentResolver().registerContentObserver(
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
index 92475da..9c87e1b 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFooterImpl.java
@@ -75,6 +75,7 @@
private boolean mListening;
private boolean mShowEmergencyCallsOnly;
+ private View mDivider;
protected MultiUserSwitch mMultiUserSwitch;
private ImageView mMultiUserAvatar;
@@ -84,6 +85,8 @@
protected View mEdit;
private TouchAnimator mAnimator;
+ private View mActionsContainer;
+
public QSFooterImpl(Context context, AttributeSet attrs) {
super(context, attrs);
}
@@ -91,8 +94,7 @@
@Override
protected void onFinishInflate() {
super.onFinishInflate();
- Resources res = getResources();
-
+ mDivider = findViewById(R.id.qs_footer_divider);
mEdit = findViewById(android.R.id.edit);
mEdit.setOnClickListener(view ->
Dependency.get(ActivityStarter.class).postQSRunnableDismissingKeyguard(() ->
@@ -107,6 +109,8 @@
mMultiUserSwitch = findViewById(R.id.multi_user_switch);
mMultiUserAvatar = mMultiUserSwitch.findViewById(R.id.multi_user_avatar);
+ mActionsContainer = findViewById(R.id.qs_footer_actions_container);
+
// RenderThread is doing more harm than good when touching the header (to expand quick
// settings), so disable it for this view
((RippleDrawable) mSettingsButton.getBackground()).setForceSoftware(true);
@@ -158,10 +162,9 @@
@Nullable
private TouchAnimator createSettingsAlphaAnimator() {
return new TouchAnimator.Builder()
- .addFloat(mEdit, "alpha", 0, 1)
- .addFloat(mMultiUserSwitch, "alpha", 0, 1)
+ .addFloat(mDivider, "alpha", 0, 1)
.addFloat(mCarrierText, "alpha", 0, 1)
- .addFloat(mSettingsButton, "alpha", 0, 1)
+ .addFloat(mActionsContainer, "alpha", 0, 1)
.build();
}
@@ -269,6 +272,11 @@
@Override
public void onClick(View v) {
+ // Don't do anything until view are unhidden
+ if (!mExpanded) {
+ return;
+ }
+
if (v == mSettingsButton) {
if (!Dependency.get(DeviceProvisionedController.class).isCurrentUserSetup()) {
// If user isn't setup just unlock the device and dump them back at SUW.
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
index 669439d..d8e1051 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSFragment.java
@@ -69,7 +69,7 @@
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
Bundle savedInstanceState) {
- inflater =inflater.cloneInContext(new ContextThemeWrapper(getContext(), R.style.qs_theme));
+ inflater = inflater.cloneInContext(new ContextThemeWrapper(getContext(), R.style.qs_theme));
return inflater.inflate(R.layout.qs_panel, container, false);
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSFactoryImpl.java b/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSFactoryImpl.java
index 77c3bfa..bf9746e 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSFactoryImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/tileimpl/QSFactoryImpl.java
@@ -23,6 +23,7 @@
import com.android.systemui.plugins.qs.QSTileView;
import com.android.systemui.qs.external.CustomTile;
import com.android.systemui.qs.tiles.AirplaneModeTile;
+import com.android.systemui.qs.tiles.AlarmTile;
import com.android.systemui.qs.tiles.BatterySaverTile;
import com.android.systemui.qs.tiles.BluetoothTile;
import com.android.systemui.qs.tiles.CastTile;
@@ -69,6 +70,7 @@
else if (tileSpec.equals("saver")) return new DataSaverTile(mHost);
else if (tileSpec.equals("night")) return new NightDisplayTile(mHost);
else if (tileSpec.equals("nfc")) return new NfcTile(mHost);
+ else if (tileSpec.equals("alarm")) return new AlarmTile(mHost);
// Intent tiles.
else if (tileSpec.startsWith(IntentTile.PREFIX)) return IntentTile.create(mHost, tileSpec);
else if (tileSpec.startsWith(CustomTile.PREFIX)) return CustomTile.create(mHost, tileSpec);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/AlarmTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/AlarmTile.java
new file mode 100644
index 0000000..ff3fe73
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/AlarmTile.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.systemui.qs.tiles;
+
+import static android.service.quicksettings.Tile.STATE_ACTIVE;
+import static android.service.quicksettings.Tile.STATE_UNAVAILABLE;
+
+import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.QS_ALARM;
+import static com.android.systemui.keyguard.KeyguardSliceProvider.formatNextAlarm;
+
+import android.app.AlarmManager.AlarmClockInfo;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.provider.AlarmClock;
+
+import com.android.systemui.Dependency;
+import com.android.systemui.R;
+import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.qs.QSTileHost;
+import com.android.systemui.qs.tileimpl.QSTileImpl;
+import com.android.systemui.statusbar.policy.NextAlarmController;
+import com.android.systemui.statusbar.policy.NextAlarmController.NextAlarmChangeCallback;
+
+public class AlarmTile extends QSTileImpl implements NextAlarmChangeCallback {
+ private final NextAlarmController mController;
+ private String mNextAlarm;
+ private PendingIntent mIntent;
+
+ public AlarmTile(QSTileHost host) {
+ super(host);
+ mController = Dependency.get(NextAlarmController.class);
+ }
+
+ @Override
+ public State newTileState() {
+ return new BooleanState();
+ }
+
+ @Override
+ protected void handleClick() {
+ if (mIntent != null) {
+ Dependency.get(ActivityStarter.class).postStartActivityDismissingKeyguard(mIntent);
+ }
+ }
+
+ @Override
+ protected void handleUpdateState(State state, Object arg) {
+ state.state = mNextAlarm != null ? STATE_ACTIVE : STATE_UNAVAILABLE;
+ state.label = getTileLabel();
+ state.secondaryLabel = mNextAlarm;
+ state.icon = ResourceIcon.get(R.drawable.stat_sys_alarm);
+ ((BooleanState) state).value = mNextAlarm != null;
+ }
+
+ @Override
+ public void onNextAlarmChanged(AlarmClockInfo nextAlarm) {
+ if (nextAlarm != null) {
+ mNextAlarm = formatNextAlarm(mContext, nextAlarm);
+ mIntent = nextAlarm.getShowIntent();
+ } else {
+ mNextAlarm = null;
+ mIntent = null;
+ }
+ refreshState();
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return QS_ALARM;
+ }
+
+ @Override
+ public Intent getLongClickIntent() {
+ return new Intent(AlarmClock.ACTION_SET_ALARM);
+ }
+
+ @Override
+ protected void handleSetListening(boolean listening) {
+ if (listening) {
+ mController.addCallback(this);
+ } else {
+ mController.removeCallback(this);
+ }
+ }
+
+ @Override
+ public CharSequence getTileLabel() {
+ return mContext.getString(R.string.status_bar_alarm);
+ }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
index 8325df7..cad956c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShelf.java
@@ -802,10 +802,6 @@
updateRelativeOffset();
}
- public void setDarkOffsetX(int offsetX) {
- mShelfIcons.setDarkOffsetX(offsetX);
- }
-
private class ShelfState extends ExpandableViewState {
private float openedAmount;
private boolean hasItemsInStableShelf;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
index 3dfb913..3ebeb4d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java
@@ -379,7 +379,7 @@
// Because space is usually constrained in the auto use-case, there should not be a
// pinned notification when the shade has been expanded. Ensure this by removing all heads-
// up notifications.
- mHeadsUpManager.releaseAllImmediately();
+ mHeadsUpManager.removeAllHeadsUpEntries();
super.animateExpandNotificationsPanel();
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/RowInflaterTask.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/RowInflaterTask.java
index 3491f81..c214171 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/RowInflaterTask.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/RowInflaterTask.java
@@ -18,6 +18,7 @@
import android.content.Context;
import android.support.v4.view.AsyncLayoutInflater;
+import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
@@ -30,15 +31,23 @@
* An inflater task that asynchronously inflates a ExpandableNotificationRow
*/
public class RowInflaterTask implements InflationTask, AsyncLayoutInflater.OnInflateFinishedListener {
+
+ private static final String TAG = "RowInflaterTask";
+ private static final boolean TRACE_ORIGIN = true;
+
private RowInflationFinishedListener mListener;
private NotificationData.Entry mEntry;
private boolean mCancelled;
+ private Throwable mInflateOrigin;
/**
* Inflates a new notificationView. This should not be called twice on this object
*/
public void inflate(Context context, ViewGroup parent, NotificationData.Entry entry,
RowInflationFinishedListener listener) {
+ if (TRACE_ORIGIN) {
+ mInflateOrigin = new Throwable("inflate requested here");
+ }
mListener = listener;
AsyncLayoutInflater inflater = new AsyncLayoutInflater(context);
mEntry = entry;
@@ -54,8 +63,16 @@
@Override
public void onInflateFinished(View view, int resid, ViewGroup parent) {
if (!mCancelled) {
- mEntry.onInflationTaskFinished();
- mListener.onInflationFinished((ExpandableNotificationRow) view);
+ try {
+ mEntry.onInflationTaskFinished();
+ mListener.onInflationFinished((ExpandableNotificationRow) view);
+ } catch (Throwable t) {
+ if (mInflateOrigin != null) {
+ Log.e(TAG, "Error in inflation finished listener: " + t, mInflateOrigin);
+ t.addSuppressed(mInflateOrigin);
+ }
+ throw t;
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
index 36f9f6b..b220686 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/AutoTileManager.java
@@ -14,16 +14,13 @@
package com.android.systemui.statusbar.phone;
+import android.app.AlarmManager.AlarmClockInfo;
import android.content.Context;
import android.os.Handler;
-import android.os.Looper;
import android.provider.Settings.Secure;
-
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.app.ColorDisplayController;
import com.android.systemui.Dependency;
-import com.android.systemui.Prefs;
-import com.android.systemui.Prefs.Key;
import com.android.systemui.qs.AutoAddTracker;
import com.android.systemui.qs.QSTileHost;
import com.android.systemui.qs.SecureSetting;
@@ -31,27 +28,37 @@
import com.android.systemui.statusbar.policy.DataSaverController.Listener;
import com.android.systemui.statusbar.policy.HotspotController;
import com.android.systemui.statusbar.policy.HotspotController.Callback;
+import com.android.systemui.statusbar.policy.NextAlarmController;
+import com.android.systemui.statusbar.policy.NextAlarmController.NextAlarmChangeCallback;
/**
* Manages which tiles should be automatically added to QS.
*/
public class AutoTileManager {
-
public static final String HOTSPOT = "hotspot";
public static final String SAVER = "saver";
public static final String INVERSION = "inversion";
public static final String WORK = "work";
public static final String NIGHT = "night";
+ public static final String ALARM = "alarm";
+
private final Context mContext;
private final QSTileHost mHost;
private final Handler mHandler;
private final AutoAddTracker mAutoTracker;
public AutoTileManager(Context context, QSTileHost host) {
- mAutoTracker = new AutoAddTracker(context);
+ this(context, new AutoAddTracker(context), host,
+ new Handler(Dependency.get(Dependency.BG_LOOPER)));
+ }
+
+ @VisibleForTesting
+ AutoTileManager(Context context, AutoAddTracker autoAddTracker, QSTileHost host,
+ Handler handler) {
+ mAutoTracker = autoAddTracker;
mContext = context;
mHost = host;
- mHandler = new Handler((Looper) Dependency.get(Dependency.BG_LOOPER));
+ mHandler = handler;
if (!mAutoTracker.isAdded(HOTSPOT)) {
Dependency.get(HotspotController.class).addCallback(mHotspotCallback);
}
@@ -76,20 +83,25 @@
if (!mAutoTracker.isAdded(WORK)) {
Dependency.get(ManagedProfileController.class).addCallback(mProfileCallback);
}
-
if (!mAutoTracker.isAdded(NIGHT)
- && ColorDisplayController.isAvailable(mContext)) {
+ && ColorDisplayController.isAvailable(mContext)) {
Dependency.get(ColorDisplayController.class).setListener(mColorDisplayCallback);
}
+ if (!mAutoTracker.isAdded(ALARM)) {
+ Dependency.get(NextAlarmController.class).addCallback(mNextAlarmChangeCallback);
+ }
}
public void destroy() {
- mColorsSetting.setListening(false);
+ if (mColorsSetting != null) {
+ mColorsSetting.setListening(false);
+ }
mAutoTracker.destroy();
Dependency.get(HotspotController.class).removeCallback(mHotspotCallback);
Dependency.get(DataSaverController.class).removeCallback(mDataSaverListener);
Dependency.get(ManagedProfileController.class).removeCallback(mProfileCallback);
Dependency.get(ColorDisplayController.class).setListener(null);
+ Dependency.get(NextAlarmController.class).removeCallback(mNextAlarmChangeCallback);
}
private final ManagedProfileController.Callback mProfileCallback =
@@ -138,6 +150,19 @@
}
};
+ private final NextAlarmChangeCallback mNextAlarmChangeCallback = new NextAlarmChangeCallback() {
+ @Override
+ public void onNextAlarmChanged(AlarmClockInfo nextAlarm) {
+ if (mAutoTracker.isAdded(ALARM)) return;
+ if (nextAlarm != null) {
+ mHost.addTile(ALARM);
+ mAutoTracker.setTileAdded(ALARM);
+ mHandler.post(() -> Dependency.get(NextAlarmController.class)
+ .removeCallback(mNextAlarmChangeCallback));
+ }
+ }
+ };
+
@VisibleForTesting
final ColorDisplayController.Callback mColorDisplayCallback =
new ColorDisplayController.Callback() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
deleted file mode 100644
index c45c538..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhone.java
+++ /dev/null
@@ -1,455 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.phone;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.content.res.Resources;
-import android.support.v4.util.ArraySet;
-import android.util.Log;
-import android.util.Pools;
-import android.view.View;
-import android.view.ViewTreeObserver;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.systemui.Dumpable;
-import com.android.systemui.statusbar.ExpandableNotificationRow;
-import com.android.systemui.statusbar.NotificationData;
-import com.android.systemui.statusbar.StatusBarState;
-import com.android.systemui.statusbar.notification.VisualStabilityManager;
-import com.android.systemui.statusbar.policy.HeadsUpManager;
-import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.HashSet;
-import java.util.Stack;
-
-/**
- * A implementation of HeadsUpManager for phone and car.
- */
-public class HeadsUpManagerPhone extends HeadsUpManager implements Dumpable,
- ViewTreeObserver.OnComputeInternalInsetsListener, VisualStabilityManager.Callback,
- OnHeadsUpChangedListener {
- private static final String TAG = "HeadsUpManagerPhone";
- private static final boolean DEBUG = false;
-
- private final View mStatusBarWindowView;
- private final int mStatusBarHeight;
- private final NotificationGroupManager mGroupManager;
- private final StatusBar mBar;
- private final VisualStabilityManager mVisualStabilityManager;
-
- private boolean mReleaseOnExpandFinish;
- private boolean mTrackingHeadsUp;
- private HashSet<String> mSwipedOutKeys = new HashSet<>();
- private HashSet<NotificationData.Entry> mEntriesToRemoveAfterExpand = new HashSet<>();
- private ArraySet<NotificationData.Entry> mEntriesToRemoveWhenReorderingAllowed
- = new ArraySet<>();
- private boolean mIsExpanded;
- private int[] mTmpTwoArray = new int[2];
- private boolean mHeadsUpGoingAway;
- private boolean mWaitingOnCollapseWhenGoingAway;
- private boolean mIsObserving;
- private int mStatusBarState;
-
- private final Pools.Pool<HeadsUpEntryPhone> mEntryPool = new Pools.Pool<HeadsUpEntryPhone>() {
- private Stack<HeadsUpEntryPhone> mPoolObjects = new Stack<>();
-
- @Override
- public HeadsUpEntryPhone acquire() {
- if (!mPoolObjects.isEmpty()) {
- return mPoolObjects.pop();
- }
- return new HeadsUpEntryPhone();
- }
-
- @Override
- public boolean release(@NonNull HeadsUpEntryPhone instance) {
- instance.reset();
- mPoolObjects.push(instance);
- return true;
- }
- };
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Constructor:
-
- public HeadsUpManagerPhone(@NonNull final Context context, @NonNull View statusBarWindowView,
- @NonNull NotificationGroupManager groupManager, @NonNull StatusBar bar,
- @NonNull VisualStabilityManager visualStabilityManager) {
- super(context);
-
- mStatusBarWindowView = statusBarWindowView;
- mGroupManager = groupManager;
- mBar = bar;
- mVisualStabilityManager = visualStabilityManager;
-
- Resources resources = mContext.getResources();
- mStatusBarHeight = resources.getDimensionPixelSize(
- com.android.internal.R.dimen.status_bar_height);
-
- addListener(new OnHeadsUpChangedListener() {
- @Override
- public void onHeadsUpPinnedModeChanged(boolean hasPinnedNotification) {
- if (DEBUG) Log.w(TAG, "onHeadsUpPinnedModeChanged");
- updateTouchableRegionListener();
- }
- });
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Public methods:
-
- /**
- * Decides whether a click is invalid for a notification, i.e it has not been shown long enough
- * that a user might have consciously clicked on it.
- *
- * @param key the key of the touched notification
- * @return whether the touch is invalid and should be discarded
- */
- public boolean shouldSwallowClick(@NonNull String key) {
- HeadsUpManager.HeadsUpEntry entry = getHeadsUpEntry(key);
- if (entry != null && mClock.currentTimeMillis() < entry.postTime) {
- return true;
- }
- return false;
- }
-
- public void onExpandingFinished() {
- if (mReleaseOnExpandFinish) {
- releaseAllImmediately();
- mReleaseOnExpandFinish = false;
- } else {
- for (NotificationData.Entry entry : mEntriesToRemoveAfterExpand) {
- if (isHeadsUp(entry.key)) {
- // Maybe the heads-up was removed already
- removeHeadsUpEntry(entry);
- }
- }
- }
- mEntriesToRemoveAfterExpand.clear();
- }
-
- /**
- * Sets the tracking-heads-up flag. If the flag is true, HeadsUpManager doesn't remove the entry
- * from the list even after a Heads Up Notification is gone.
- */
- public void setTrackingHeadsUp(boolean trackingHeadsUp) {
- mTrackingHeadsUp = trackingHeadsUp;
- }
-
- /**
- * Notify that the status bar panel gets expanded or collapsed.
- *
- * @param isExpanded True to notify expanded, false to notify collapsed.
- */
- public void setIsPanelExpanded(boolean isExpanded) {
- if (isExpanded != mIsExpanded) {
- mIsExpanded = isExpanded;
- if (isExpanded) {
- // make sure our state is sane
- mWaitingOnCollapseWhenGoingAway = false;
- mHeadsUpGoingAway = false;
- updateTouchableRegionListener();
- }
- }
- }
-
- /**
- * Set the current state of the statusbar.
- */
- public void setStatusBarState(int statusBarState) {
- mStatusBarState = statusBarState;
- }
-
- /**
- * Set that we are exiting the headsUp pinned mode, but some notifications might still be
- * animating out. This is used to keep the touchable regions in a sane state.
- */
- public void setHeadsUpGoingAway(boolean headsUpGoingAway) {
- if (headsUpGoingAway != mHeadsUpGoingAway) {
- mHeadsUpGoingAway = headsUpGoingAway;
- if (!headsUpGoingAway) {
- waitForStatusBarLayout();
- }
- updateTouchableRegionListener();
- }
- }
-
- /**
- * Notifies that a remote input textbox in notification gets active or inactive.
- * @param entry The entry of the target notification.
- * @param remoteInputActive True to notify active, False to notify inactive.
- */
- public void setRemoteInputActive(
- @NonNull NotificationData.Entry entry, boolean remoteInputActive) {
- HeadsUpEntryPhone headsUpEntry = getHeadsUpEntryPhone(entry.key);
- if (headsUpEntry != null && headsUpEntry.remoteInputActive != remoteInputActive) {
- headsUpEntry.remoteInputActive = remoteInputActive;
- if (remoteInputActive) {
- headsUpEntry.removeAutoRemovalCallbacks();
- } else {
- headsUpEntry.updateEntry(false /* updatePostTime */);
- }
- }
- }
-
- @VisibleForTesting
- public void removeMinimumDisplayTimeForTesting() {
- mMinimumDisplayTime = 1;
- mHeadsUpNotificationDecay = 1;
- mTouchAcceptanceDelay = 1;
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // HeadsUpManager public methods overrides:
-
- @Override
- public boolean isTrackingHeadsUp() {
- return mTrackingHeadsUp;
- }
-
- @Override
- public void snooze() {
- super.snooze();
- mReleaseOnExpandFinish = true;
- }
-
- /**
- * React to the removal of the notification in the heads up.
- *
- * @return true if the notification was removed and false if it still needs to be kept around
- * for a bit since it wasn't shown long enough
- */
- @Override
- public boolean removeNotification(@NonNull String key, boolean ignoreEarliestRemovalTime) {
- if (wasShownLongEnough(key) || ignoreEarliestRemovalTime) {
- return super.removeNotification(key, ignoreEarliestRemovalTime);
- } else {
- HeadsUpEntryPhone entry = getHeadsUpEntryPhone(key);
- entry.removeAsSoonAsPossible();
- return false;
- }
- }
-
- public void addSwipedOutNotification(@NonNull String key) {
- mSwipedOutKeys.add(key);
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Dumpable overrides:
-
- @Override
- public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- pw.println("HeadsUpManagerPhone state:");
- dumpInternal(fd, pw, args);
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // ViewTreeObserver.OnComputeInternalInsetsListener overrides:
-
- /**
- * Overridden from TreeObserver.
- */
- @Override
- public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo info) {
- if (mIsExpanded || mBar.isBouncerShowing()) {
- // The touchable region is always the full area when expanded
- return;
- }
- if (hasPinnedHeadsUp()) {
- ExpandableNotificationRow topEntry = getTopEntry().row;
- if (topEntry.isChildInGroup()) {
- final ExpandableNotificationRow groupSummary
- = mGroupManager.getGroupSummary(topEntry.getStatusBarNotification());
- if (groupSummary != null) {
- topEntry = groupSummary;
- }
- }
- topEntry.getLocationOnScreen(mTmpTwoArray);
- int minX = mTmpTwoArray[0];
- int maxX = mTmpTwoArray[0] + topEntry.getWidth();
- int maxY = topEntry.getIntrinsicHeight();
-
- info.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
- info.touchableRegion.set(minX, 0, maxX, maxY);
- } else if (mHeadsUpGoingAway || mWaitingOnCollapseWhenGoingAway) {
- info.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
- info.touchableRegion.set(0, 0, mStatusBarWindowView.getWidth(), mStatusBarHeight);
- }
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // VisualStabilityManager.Callback overrides:
-
- @Override
- public void onReorderingAllowed() {
- mBar.getNotificationScrollLayout().setHeadsUpGoingAwayAnimationsAllowed(false);
- for (NotificationData.Entry entry : mEntriesToRemoveWhenReorderingAllowed) {
- if (isHeadsUp(entry.key)) {
- // Maybe the heads-up was removed already
- removeHeadsUpEntry(entry);
- }
- }
- mEntriesToRemoveWhenReorderingAllowed.clear();
- mBar.getNotificationScrollLayout().setHeadsUpGoingAwayAnimationsAllowed(true);
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // HeadsUpManager utility (protected) methods overrides:
-
- @Override
- protected HeadsUpEntry createHeadsUpEntry() {
- return mEntryPool.acquire();
- }
-
- @Override
- protected void releaseHeadsUpEntry(HeadsUpEntry entry) {
- mEntryPool.release((HeadsUpEntryPhone) entry);
- }
-
- @Override
- protected boolean shouldHeadsUpBecomePinned(NotificationData.Entry entry) {
- return mStatusBarState != StatusBarState.KEYGUARD && !mIsExpanded
- || super.shouldHeadsUpBecomePinned(entry);
- }
-
- @Override
- protected void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
- super.dumpInternal(fd, pw, args);
- pw.print(" mStatusBarState="); pw.println(mStatusBarState);
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Protected utility methods:
-
- @Nullable
- protected HeadsUpEntryPhone getHeadsUpEntryPhone(@NonNull String key) {
- return (HeadsUpEntryPhone) getHeadsUpEntry(key);
- }
-
- @Nullable
- protected HeadsUpEntryPhone getTopHeadsUpEntryPhone() {
- return (HeadsUpEntryPhone) getTopHeadsUpEntry();
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Private utility methods:
-
- private boolean wasShownLongEnough(@NonNull String key) {
- if (mSwipedOutKeys.contains(key)) {
- // We always instantly dismiss views being manually swiped out.
- mSwipedOutKeys.remove(key);
- return true;
- }
-
- HeadsUpEntryPhone headsUpEntry = getHeadsUpEntryPhone(key);
- HeadsUpEntryPhone topEntry = getTopHeadsUpEntryPhone();
- if (headsUpEntry != topEntry) {
- return true;
- }
- return headsUpEntry.wasShownLongEnough();
- }
-
- /**
- * We need to wait on the whole panel to collapse, before we can remove the touchable region
- * listener.
- */
- private void waitForStatusBarLayout() {
- mWaitingOnCollapseWhenGoingAway = true;
- mStatusBarWindowView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
- @Override
- public void onLayoutChange(View v, int left, int top, int right, int bottom,
- int oldLeft,
- int oldTop, int oldRight, int oldBottom) {
- if (mStatusBarWindowView.getHeight() <= mStatusBarHeight) {
- mStatusBarWindowView.removeOnLayoutChangeListener(this);
- mWaitingOnCollapseWhenGoingAway = false;
- updateTouchableRegionListener();
- }
- }
- });
- }
-
- private void updateTouchableRegionListener() {
- boolean shouldObserve = hasPinnedHeadsUp() || mHeadsUpGoingAway
- || mWaitingOnCollapseWhenGoingAway;
- if (shouldObserve == mIsObserving) {
- return;
- }
- if (shouldObserve) {
- mStatusBarWindowView.getViewTreeObserver().addOnComputeInternalInsetsListener(this);
- mStatusBarWindowView.requestLayout();
- } else {
- mStatusBarWindowView.getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
- }
- mIsObserving = shouldObserve;
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // HeadsUpEntryPhone:
-
- protected class HeadsUpEntryPhone extends HeadsUpManager.HeadsUpEntry {
- public void setEntry(@NonNull final NotificationData.Entry entry) {
- Runnable removeHeadsUpRunnable = () -> {
- if (!mVisualStabilityManager.isReorderingAllowed()) {
- mEntriesToRemoveWhenReorderingAllowed.add(entry);
- mVisualStabilityManager.addReorderingAllowedCallback(
- HeadsUpManagerPhone.this);
- } else if (!mTrackingHeadsUp) {
- removeHeadsUpEntry(entry);
- } else {
- mEntriesToRemoveAfterExpand.add(entry);
- }
- };
-
- super.setEntry(entry, removeHeadsUpRunnable);
- }
-
- public boolean wasShownLongEnough() {
- return earliestRemovaltime < mClock.currentTimeMillis();
- }
-
- @Override
- public void updateEntry(boolean updatePostTime) {
- super.updateEntry(updatePostTime);
-
- if (mEntriesToRemoveAfterExpand.contains(entry)) {
- mEntriesToRemoveAfterExpand.remove(entry);
- }
- if (mEntriesToRemoveWhenReorderingAllowed.contains(entry)) {
- mEntriesToRemoveWhenReorderingAllowed.remove(entry);
- }
- }
-
- @Override
- public void expanded(boolean expanded) {
- if (this.expanded == expanded) {
- return;
- }
-
- this.expanded = expanded;
- if (expanded) {
- removeAutoRemovalCallbacks();
- } else {
- updateEntry(false /* updatePostTime */);
- }
- }
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpTouchHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpTouchHelper.java
index 2bfdefe..c85571c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpTouchHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/HeadsUpTouchHelper.java
@@ -23,7 +23,7 @@
import com.android.systemui.Gefingerpoken;
import com.android.systemui.statusbar.ExpandableNotificationRow;
import com.android.systemui.statusbar.ExpandableView;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
/**
@@ -31,7 +31,7 @@
*/
public class HeadsUpTouchHelper implements Gefingerpoken {
- private HeadsUpManagerPhone mHeadsUpManager;
+ private HeadsUpManager mHeadsUpManager;
private NotificationStackScrollLayout mStackScroller;
private int mTrackingPointer;
private float mTouchSlop;
@@ -43,7 +43,7 @@
private NotificationPanelView mPanel;
private ExpandableNotificationRow mPickedChild;
- public HeadsUpTouchHelper(HeadsUpManagerPhone headsUpManager,
+ public HeadsUpTouchHelper(HeadsUpManager headsUpManager,
NotificationStackScrollLayout stackScroller,
NotificationPanelView notificationPanelView) {
mHeadsUpManager = headsUpManager;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
index de6ecac..e04ba83 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationBarView.java
@@ -304,7 +304,7 @@
}
}
}
- return mRecentsAnimationStarted || mGestureHelper.onInterceptTouchEvent(event);
+ return mGestureHelper.onInterceptTouchEvent(event) || mRecentsAnimationStarted;
}
public void abortCurrentGesture() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
index 91cae0a..5cf4c4c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconContainer.java
@@ -120,7 +120,6 @@
private boolean mDisallowNextAnimation;
private boolean mAnimationsEnabled = true;
private ArrayMap<String, ArrayList<StatusBarIcon>> mReplacingIcons;
- private int mDarkOffsetX;
// Keep track of the last visible icon so collapsed container can report on its location
private IconState mLastVisibleIconState;
@@ -378,14 +377,6 @@
iconState.xTranslation = getWidth() - iconState.xTranslation - view.getWidth();
}
}
-
- if (mDark && mDarkOffsetX != 0) {
- for (int i = 0; i < childCount; i++) {
- View view = getChildAt(i);
- IconState iconState = mIconStates.get(view);
- iconState.xTranslation += mDarkOffsetX;
- }
- }
}
private float getLayoutEnd() {
@@ -534,10 +525,6 @@
mAnimationsEnabled = enabled;
}
- public void setDarkOffsetX(int offsetX) {
- mDarkOffsetX = offsetX;
- }
-
public void setReplacingIcons(ArrayMap<String, ArrayList<StatusBarIcon>> replacingIcons) {
mReplacingIcons = replacingIcons;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 2111d2e..cd2e77a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -47,6 +47,7 @@
import android.view.WindowInsets;
import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;
+
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.keyguard.KeyguardStatusView;
@@ -67,15 +68,14 @@
import com.android.systemui.statusbar.NotificationShelf;
import com.android.systemui.statusbar.StatusBarState;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
-import com.android.systemui.statusbar.notification.NotificationUtils;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
import com.android.systemui.statusbar.policy.OnHeadsUpChangedListener;
import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
import com.android.systemui.statusbar.stack.StackStateAnimator;
-import java.util.Collection;
import java.util.List;
+import java.util.Collection;
public class NotificationPanelView extends PanelView implements
ExpandableView.OnHeightChangedListener,
@@ -482,7 +482,7 @@
mTopPaddingAdjustment = mClockPositionResult.stackScrollerPaddingAdjustment;
}
mNotificationStackScroller.setIntrinsicPadding(stackScrollerPadding);
- mNotificationStackScroller.setDarkShelfOffsetX(mClockPositionResult.clockX);
+ mNotificationStackScroller.setAntiBurnInOffsetX(mClockPositionResult.clockX);
mKeyguardBottomArea.setBurnInXOffset(mClockPositionResult.clockX);
requestScrollerTopPaddingUpdate(animate);
}
@@ -1571,7 +1571,7 @@
private void updatePanelExpanded() {
boolean isExpanded = !isFullyCollapsed();
if (mPanelExpanded != isExpanded) {
- mHeadsUpManager.setIsPanelExpanded(isExpanded);
+ mHeadsUpManager.setIsExpanded(isExpanded);
mStatusBar.setPanelExpanded(isExpanded);
mPanelExpanded = isExpanded;
}
@@ -2338,7 +2338,7 @@
}
@Override
- public void setHeadsUpManager(HeadsUpManagerPhone headsUpManager) {
+ public void setHeadsUpManager(HeadsUpManager headsUpManager) {
super.setHeadsUpManager(headsUpManager);
mHeadsUpTouchHelper = new HeadsUpTouchHelper(headsUpManager, mNotificationStackScroller,
this);
@@ -2630,8 +2630,8 @@
}
}
- public void setPulsing(boolean pulsing) {
- mKeyguardStatusView.setPulsing(pulsing);
+ public void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> pulsing) {
+ mKeyguardStatusView.setPulsing(pulsing != null);
positionClockAndNotifications();
mNotificationStackScroller.setPulsing(pulsing, mKeyguardStatusView.getLocationOnScreen()[1]
+ mKeyguardStatusView.getClockBottom());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
index 6daabed..2b7e474 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PanelView.java
@@ -50,7 +50,7 @@
import com.android.systemui.doze.DozeLog;
import com.android.systemui.statusbar.FlingAnimationUtils;
import com.android.systemui.statusbar.StatusBarState;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -75,7 +75,7 @@
}
protected StatusBar mStatusBar;
- protected HeadsUpManagerPhone mHeadsUpManager;
+ protected HeadsUpManager mHeadsUpManager;
private float mPeekHeight;
private float mHintDistance;
@@ -1252,7 +1252,7 @@
*/
protected abstract int getClearAllHeight();
- public void setHeadsUpManager(HeadsUpManagerPhone headsUpManager) {
+ public void setHeadsUpManager(HeadsUpManager headsUpManager) {
mHeadsUpManager = headsUpManager;
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
index 116e3f9..426268b 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java
@@ -208,7 +208,6 @@
import com.android.systemui.statusbar.notification.AboveShelfObserver;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.UnlockMethodCache.OnUnlockMethodChangedListener;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.BatteryController.BatteryStateChangeCallback;
@@ -220,7 +219,6 @@
import com.android.systemui.statusbar.policy.DeviceProvisionedController.DeviceProvisionedListener;
import com.android.systemui.statusbar.policy.ExtensionController;
import com.android.systemui.statusbar.policy.HeadsUpManager;
-import com.android.systemui.statusbar.policy.HeadsUpUtil;
import com.android.systemui.statusbar.policy.KeyguardMonitor;
import com.android.systemui.statusbar.policy.KeyguardMonitorImpl;
import com.android.systemui.statusbar.policy.KeyguardUserSwitcher;
@@ -804,14 +802,15 @@
.commit();
mIconController = Dependency.get(StatusBarIconController.class);
- mHeadsUpManager = new HeadsUpManagerPhone(context, mStatusBarWindow, mGroupManager, this,
- mVisualStabilityManager);
+ mHeadsUpManager = new HeadsUpManager(context, mStatusBarWindow, mGroupManager);
+ mHeadsUpManager.setBar(this);
mHeadsUpManager.addListener(this);
mHeadsUpManager.addListener(mNotificationPanel);
mHeadsUpManager.addListener(mGroupManager);
mHeadsUpManager.addListener(mVisualStabilityManager);
mNotificationPanel.setHeadsUpManager(mHeadsUpManager);
mGroupManager.setHeadsUpManager(mHeadsUpManager);
+ mHeadsUpManager.setVisualStabilityManager(mVisualStabilityManager);
putComponent(HeadsUpManager.class, mHeadsUpManager);
mEntryManager.setUpWithPresenter(this, mStackScroller, this, mHeadsUpManager);
@@ -1342,8 +1341,7 @@
@Override
public void onPerformRemoveNotification(StatusBarNotification n) {
- if (mStackScroller.hasPulsingNotifications() &&
- !mHeadsUpManager.hasHeadsUpNotifications()) {
+ if (mStackScroller.hasPulsingNotifications() && mHeadsUpManager.getAllEntries().isEmpty()) {
// We were showing a pulse for a notification, but no notifications are pulsing anymore.
// Finish the pulse.
mDozeScrimController.pulseOutNow();
@@ -2092,8 +2090,9 @@
}
public void maybeEscalateHeadsUp() {
- mHeadsUpManager.getAllEntries().forEach(entry -> {
- final StatusBarNotification sbn = entry.notification;
+ Collection<HeadsUpManager.HeadsUpEntry> entries = mHeadsUpManager.getAllEntries();
+ for (HeadsUpManager.HeadsUpEntry entry : entries) {
+ final StatusBarNotification sbn = entry.entry.notification;
final Notification notification = sbn.getNotification();
if (notification.fullScreenIntent != null) {
if (DEBUG) {
@@ -2103,11 +2102,11 @@
EventLog.writeEvent(EventLogTags.SYSUI_HEADS_UP_ESCALATION,
sbn.getKey());
notification.fullScreenIntent.send();
- entry.notifyFullScreenIntentLaunched();
+ entry.entry.notifyFullScreenIntentLaunched();
} catch (PendingIntent.CanceledException e) {
}
}
- });
+ }
mHeadsUpManager.releaseAllImmediately();
}
@@ -4637,22 +4636,24 @@
@Override
public void onPulseStarted() {
callback.onPulseStarted();
- if (mHeadsUpManager.hasHeadsUpNotifications()) {
+ Collection<HeadsUpManager.HeadsUpEntry> pulsingEntries =
+ mHeadsUpManager.getAllEntries();
+ if (!pulsingEntries.isEmpty()) {
// Only pulse the stack scroller if there's actually something to show.
// Otherwise just show the always-on screen.
- setPulsing(true);
+ setPulsing(pulsingEntries);
}
}
@Override
public void onPulseFinished() {
callback.onPulseFinished();
- setPulsing(false);
+ setPulsing(null);
}
- private void setPulsing(boolean pulsing) {
+ private void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> pulsing) {
mNotificationPanel.setPulsing(pulsing);
- mVisualStabilityManager.setPulsing(pulsing);
+ mVisualStabilityManager.setPulsing(pulsing != null);
mIgnoreTouchWhilePulsing = false;
}
}, reason);
@@ -4800,7 +4801,7 @@
// for heads up notifications
- protected HeadsUpManagerPhone mHeadsUpManager;
+ protected HeadsUpManager mHeadsUpManager;
private AboveShelfObserver mAboveShelfObserver;
@@ -4903,7 +4904,7 @@
// Release the HUN notification to the shade.
if (isPresenterFullyCollapsed()) {
- HeadsUpUtil.setIsClickedHeadsUpNotification(row, true);
+ HeadsUpManager.setIsClickedNotification(row, true);
}
//
// In most cases, when FLAG_AUTO_CANCEL is set, the notification will
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
index a2b896d..53dfb24 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpManager.java
@@ -16,68 +16,118 @@
package com.android.systemui.statusbar.policy;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
import android.content.Context;
import android.content.res.Resources;
import android.database.ContentObserver;
-import android.os.SystemClock;
import android.os.Handler;
import android.os.Looper;
-import android.util.ArrayMap;
+import android.os.SystemClock;
import android.provider.Settings;
+import android.support.v4.util.ArraySet;
+import android.util.ArrayMap;
import android.util.Log;
+import android.util.Pools;
+import android.view.View;
+import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityEvent;
import com.android.internal.logging.MetricsLogger;
import com.android.systemui.R;
import com.android.systemui.statusbar.ExpandableNotificationRow;
import com.android.systemui.statusbar.NotificationData;
+import com.android.systemui.statusbar.StatusBarState;
+import com.android.systemui.statusbar.notification.VisualStabilityManager;
+import com.android.systemui.statusbar.phone.NotificationGroupManager;
+import com.android.systemui.statusbar.phone.StatusBar;
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import java.util.Iterator;
-import java.util.stream.Stream;
+import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Stack;
/**
* A manager which handles heads up notifications which is a special mode where
* they simply peek from the top of the screen.
*/
-public class HeadsUpManager {
+public class HeadsUpManager implements ViewTreeObserver.OnComputeInternalInsetsListener,
+ VisualStabilityManager.Callback {
private static final String TAG = "HeadsUpManager";
private static final boolean DEBUG = false;
private static final String SETTING_HEADS_UP_SNOOZE_LENGTH_MS = "heads_up_snooze_length_ms";
+ private static final int TAG_CLICKED_NOTIFICATION = R.id.is_clicked_heads_up_tag;
- protected final Clock mClock = new Clock();
- protected final Context mContext;
- protected final HashSet<OnHeadsUpChangedListener> mListeners = new HashSet<>();
- protected final Handler mHandler = new Handler(Looper.getMainLooper());
+ private final int mHeadsUpNotificationDecay;
+ private final int mMinimumDisplayTime;
- protected int mHeadsUpNotificationDecay;
- protected int mMinimumDisplayTime;
- protected int mTouchAcceptanceDelay;
- protected int mSnoozeLengthMs;
- protected boolean mHasPinnedNotification;
- protected int mUser;
-
- private final HashMap<String, HeadsUpEntry> mHeadsUpEntries = new HashMap<>();
+ private final int mTouchAcceptanceDelay;
private final ArrayMap<String, Long> mSnoozedPackages;
- private final ContentObserver mSettingsObserver;
+ private final HashSet<OnHeadsUpChangedListener> mListeners = new HashSet<>();
+ private final int mDefaultSnoozeLengthMs;
+ private final Handler mHandler = new Handler(Looper.getMainLooper());
+ private final Pools.Pool<HeadsUpEntry> mEntryPool = new Pools.Pool<HeadsUpEntry>() {
- public HeadsUpManager(@NonNull final Context context) {
+ private Stack<HeadsUpEntry> mPoolObjects = new Stack<>();
+
+ @Override
+ public HeadsUpEntry acquire() {
+ if (!mPoolObjects.isEmpty()) {
+ return mPoolObjects.pop();
+ }
+ return new HeadsUpEntry();
+ }
+
+ @Override
+ public boolean release(HeadsUpEntry instance) {
+ instance.reset();
+ mPoolObjects.push(instance);
+ return true;
+ }
+ };
+
+ private final View mStatusBarWindowView;
+ private final int mStatusBarHeight;
+ private final Context mContext;
+ private final NotificationGroupManager mGroupManager;
+ private StatusBar mBar;
+ private int mSnoozeLengthMs;
+ private ContentObserver mSettingsObserver;
+ private HashMap<String, HeadsUpEntry> mHeadsUpEntries = new HashMap<>();
+ private HashSet<String> mSwipedOutKeys = new HashSet<>();
+ private int mUser;
+ private Clock mClock;
+ private boolean mReleaseOnExpandFinish;
+ private boolean mTrackingHeadsUp;
+ private HashSet<NotificationData.Entry> mEntriesToRemoveAfterExpand = new HashSet<>();
+ private ArraySet<NotificationData.Entry> mEntriesToRemoveWhenReorderingAllowed
+ = new ArraySet<>();
+ private boolean mIsExpanded;
+ private boolean mHasPinnedNotification;
+ private int[] mTmpTwoArray = new int[2];
+ private boolean mHeadsUpGoingAway;
+ private boolean mWaitingOnCollapseWhenGoingAway;
+ private boolean mIsObserving;
+ private boolean mRemoteInputActive;
+ private float mExpandedHeight;
+ private VisualStabilityManager mVisualStabilityManager;
+ private int mStatusBarState;
+
+ public HeadsUpManager(final Context context, View statusBarWindowView,
+ NotificationGroupManager groupManager) {
mContext = context;
- Resources resources = context.getResources();
- mMinimumDisplayTime = resources.getInteger(R.integer.heads_up_notification_minimum_time);
- mHeadsUpNotificationDecay = resources.getInteger(R.integer.heads_up_notification_decay);
+ Resources resources = mContext.getResources();
mTouchAcceptanceDelay = resources.getInteger(R.integer.touch_acceptance_delay);
mSnoozedPackages = new ArrayMap<>();
- int defaultSnoozeLengthMs =
- resources.getInteger(R.integer.heads_up_default_snooze_length_ms);
+ mDefaultSnoozeLengthMs = resources.getInteger(R.integer.heads_up_default_snooze_length_ms);
+ mSnoozeLengthMs = mDefaultSnoozeLengthMs;
+ mMinimumDisplayTime = resources.getInteger(R.integer.heads_up_notification_minimum_time);
+ mHeadsUpNotificationDecay = resources.getInteger(R.integer.heads_up_notification_decay);
+ mClock = new Clock();
mSnoozeLengthMs = Settings.Global.getInt(context.getContentResolver(),
- SETTING_HEADS_UP_SNOOZE_LENGTH_MS, defaultSnoozeLengthMs);
+ SETTING_HEADS_UP_SNOOZE_LENGTH_MS, mDefaultSnoozeLengthMs);
mSettingsObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
@@ -92,26 +142,47 @@
context.getContentResolver().registerContentObserver(
Settings.Global.getUriFor(SETTING_HEADS_UP_SNOOZE_LENGTH_MS), false,
mSettingsObserver);
+ mStatusBarWindowView = statusBarWindowView;
+ mGroupManager = groupManager;
+ mStatusBarHeight = resources.getDimensionPixelSize(
+ com.android.internal.R.dimen.status_bar_height);
}
- /**
- * Adds an OnHeadUpChangedListener to observe events.
- */
- public void addListener(@NonNull OnHeadsUpChangedListener listener) {
+ private void updateTouchableRegionListener() {
+ boolean shouldObserve = mHasPinnedNotification || mHeadsUpGoingAway
+ || mWaitingOnCollapseWhenGoingAway;
+ if (shouldObserve == mIsObserving) {
+ return;
+ }
+ if (shouldObserve) {
+ mStatusBarWindowView.getViewTreeObserver().addOnComputeInternalInsetsListener(this);
+ mStatusBarWindowView.requestLayout();
+ } else {
+ mStatusBarWindowView.getViewTreeObserver().removeOnComputeInternalInsetsListener(this);
+ }
+ mIsObserving = shouldObserve;
+ }
+
+ public void setBar(StatusBar bar) {
+ mBar = bar;
+ }
+
+ public void addListener(OnHeadsUpChangedListener listener) {
mListeners.add(listener);
}
- /**
- * Removes the OnHeadUpChangedListener from the observer list.
- */
- public void removeListener(@NonNull OnHeadsUpChangedListener listener) {
+ public void removeListener(OnHeadsUpChangedListener listener) {
mListeners.remove(listener);
}
+ public StatusBar getBar() {
+ return mBar;
+ }
+
/**
* Called when posting a new notification to the heads up.
*/
- public void showNotification(@NonNull NotificationData.Entry headsUp) {
+ public void showNotification(NotificationData.Entry headsUp) {
if (DEBUG) Log.v(TAG, "showNotification");
addHeadsUpEntry(headsUp);
updateNotification(headsUp, true);
@@ -121,7 +192,7 @@
/**
* Called when updating or posting a notification to the heads up.
*/
- public void updateNotification(@NonNull NotificationData.Entry headsUp, boolean alert) {
+ public void updateNotification(NotificationData.Entry headsUp, boolean alert) {
if (DEBUG) Log.v(TAG, "updateNotification");
headsUp.row.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
@@ -133,13 +204,14 @@
// with the groupmanager
return;
}
- headsUpEntry.updateEntry(true /* updatePostTime */);
+ headsUpEntry.updateEntry();
setEntryPinned(headsUpEntry, shouldHeadsUpBecomePinned(headsUp));
}
}
- private void addHeadsUpEntry(@NonNull NotificationData.Entry entry) {
- HeadsUpEntry headsUpEntry = createHeadsUpEntry();
+ private void addHeadsUpEntry(NotificationData.Entry entry) {
+ HeadsUpEntry headsUpEntry = mEntryPool.acquire();
+
// This will also add the entry to the sortedList
headsUpEntry.setEntry(entry);
mHeadsUpEntries.put(entry.key, headsUpEntry);
@@ -151,17 +223,16 @@
entry.row.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
- protected boolean shouldHeadsUpBecomePinned(@NonNull NotificationData.Entry entry) {
- return hasFullScreenIntent(entry);
+ private boolean shouldHeadsUpBecomePinned(NotificationData.Entry entry) {
+ return mStatusBarState != StatusBarState.KEYGUARD
+ && !mIsExpanded || hasFullScreenIntent(entry);
}
- protected boolean hasFullScreenIntent(@NonNull NotificationData.Entry entry) {
+ private boolean hasFullScreenIntent(NotificationData.Entry entry) {
return entry.notification.getNotification().fullScreenIntent != null;
}
- protected void setEntryPinned(
- @NonNull HeadsUpManager.HeadsUpEntry headsUpEntry, boolean isPinned) {
- if (DEBUG) Log.v(TAG, "setEntryPinned: " + isPinned);
+ private void setEntryPinned(HeadsUpEntry headsUpEntry, boolean isPinned) {
ExpandableNotificationRow row = headsUpEntry.entry.row;
if (row.isPinned() != isPinned) {
row.setPinned(isPinned);
@@ -176,35 +247,33 @@
}
}
- protected void removeHeadsUpEntry(NotificationData.Entry entry) {
+ private void removeHeadsUpEntry(NotificationData.Entry entry) {
HeadsUpEntry remove = mHeadsUpEntries.remove(entry.key);
- onHeadsUpEntryRemoved(remove);
- releaseHeadsUpEntry(remove);
- }
-
- protected void onHeadsUpEntryRemoved(HeadsUpEntry remove) {
- NotificationData.Entry entry = remove.entry;
entry.row.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
entry.row.setHeadsUp(false);
setEntryPinned(remove, false /* isPinned */);
for (OnHeadsUpChangedListener listener : mListeners) {
listener.onHeadsUpStateChanged(entry, false);
}
+ mEntryPool.release(remove);
}
- protected void updatePinnedMode() {
+ public void removeAllHeadsUpEntries() {
+ for (String key : mHeadsUpEntries.keySet()) {
+ removeHeadsUpEntry(mHeadsUpEntries.get(key).entry);
+ }
+ }
+
+ private void updatePinnedMode() {
boolean hasPinnedNotification = hasPinnedNotificationInternal();
if (hasPinnedNotification == mHasPinnedNotification) {
return;
}
- if (DEBUG) {
- Log.v(TAG, "Pinned mode changed: " + mHasPinnedNotification + " -> " +
- hasPinnedNotification);
- }
mHasPinnedNotification = hasPinnedNotification;
if (mHasPinnedNotification) {
MetricsLogger.count(mContext, "note_peek", 1);
}
+ updateTouchableRegionListener();
for (OnHeadsUpChangedListener listener : mListeners) {
listener.onHeadsUpPinnedModeChanged(hasPinnedNotification);
}
@@ -216,36 +285,47 @@
* @return true if the notification was removed and false if it still needs to be kept around
* for a bit since it wasn't shown long enough
*/
- public boolean removeNotification(@NonNull String key, boolean ignoreEarliestRemovalTime) {
- if (DEBUG) Log.v(TAG, "removeNotification");
- releaseImmediately(key);
- return true;
+ public boolean removeNotification(String key, boolean ignoreEarliestRemovalTime) {
+ if (DEBUG) Log.v(TAG, "remove");
+ if (wasShownLongEnough(key) || ignoreEarliestRemovalTime) {
+ releaseImmediately(key);
+ return true;
+ } else {
+ getHeadsUpEntry(key).removeAsSoonAsPossible();
+ return false;
+ }
}
- /**
- * Returns if the given notification is in the Heads Up Notification list or not.
- */
+ private boolean wasShownLongEnough(String key) {
+ HeadsUpEntry headsUpEntry = getHeadsUpEntry(key);
+ HeadsUpEntry topEntry = getTopEntry();
+ if (mSwipedOutKeys.contains(key)) {
+ // We always instantly dismiss views being manually swiped out.
+ mSwipedOutKeys.remove(key);
+ return true;
+ }
+ if (headsUpEntry != topEntry) {
+ return true;
+ }
+ return headsUpEntry.wasShownLongEnough();
+ }
+
public boolean isHeadsUp(String key) {
return mHeadsUpEntries.containsKey(key);
}
/**
- * Pushes any current Heads Up notification down into the shade.
+ * Push any current Heads Up notification down into the shade.
*/
public void releaseAllImmediately() {
if (DEBUG) Log.v(TAG, "releaseAllImmediately");
- Iterator<HeadsUpEntry> iterator = mHeadsUpEntries.values().iterator();
- while (iterator.hasNext()) {
- HeadsUpEntry entry = iterator.next();
- iterator.remove();
- onHeadsUpEntryRemoved(entry);
+ ArrayList<String> keys = new ArrayList<>(mHeadsUpEntries.keySet());
+ for (String key : keys) {
+ releaseImmediately(key);
}
}
- /**
- * Pushes the given Heads Up notification down into the shade.
- */
- public void releaseImmediately(@NonNull String key) {
+ public void releaseImmediately(String key) {
HeadsUpEntry headsUpEntry = getHeadsUpEntry(key);
if (headsUpEntry == null) {
return;
@@ -254,14 +334,11 @@
removeHeadsUpEntry(shadeEntry);
}
- /**
- * Returns if the given notification is snoozed or not.
- */
- public boolean isSnoozed(@NonNull String packageName) {
+ public boolean isSnoozed(String packageName) {
final String key = snoozeKey(packageName, mUser);
Long snoozedUntil = mSnoozedPackages.get(key);
if (snoozedUntil != null) {
- if (snoozedUntil > mClock.currentTimeMillis()) {
+ if (snoozedUntil > SystemClock.elapsedRealtime()) {
if (DEBUG) Log.v(TAG, key + " snoozed");
return true;
}
@@ -270,61 +347,33 @@
return false;
}
- /**
- * Snoozes all current Heads Up Notifications.
- */
public void snooze() {
for (String key : mHeadsUpEntries.keySet()) {
HeadsUpEntry entry = mHeadsUpEntries.get(key);
String packageName = entry.entry.notification.getPackageName();
mSnoozedPackages.put(snoozeKey(packageName, mUser),
- mClock.currentTimeMillis() + mSnoozeLengthMs);
+ SystemClock.elapsedRealtime() + mSnoozeLengthMs);
}
+ mReleaseOnExpandFinish = true;
}
- private static String snoozeKey(@NonNull String packageName, int user) {
+ private static String snoozeKey(String packageName, int user) {
return user + "," + packageName;
}
- protected HeadsUpEntry getHeadsUpEntry(@NonNull String key) {
+ private HeadsUpEntry getHeadsUpEntry(String key) {
return mHeadsUpEntries.get(key);
}
- /**
- * Returns the entry of given Heads Up Notification.
- *
- * @param key Key of heads up notification
- */
- public NotificationData.Entry getEntry(@NonNull String key) {
- HeadsUpEntry entry = mHeadsUpEntries.get(key);
- return entry != null ? entry.entry : null;
+ public NotificationData.Entry getEntry(String key) {
+ return mHeadsUpEntries.get(key).entry;
}
- /**
- * Returns the stream of all current Heads Up Notifications.
- */
- @NonNull
- public Stream<NotificationData.Entry> getAllEntries() {
- return mHeadsUpEntries.values().stream().map(headsUpEntry -> headsUpEntry.entry);
+ public Collection<HeadsUpEntry> getAllEntries() {
+ return mHeadsUpEntries.values();
}
- /**
- * Returns the top Heads Up Notification, which appeares to show at first.
- */
- @Nullable
- public NotificationData.Entry getTopEntry() {
- HeadsUpEntry topEntry = getTopHeadsUpEntry();
- return (topEntry != null) ? topEntry.entry : null;
- }
-
- /**
- * Returns if any heads up notification is available or not.
- */
- public boolean hasHeadsUpNotifications() {
- return !mHeadsUpEntries.isEmpty();
- }
-
- protected HeadsUpEntry getTopHeadsUpEntry() {
+ public HeadsUpEntry getTopEntry() {
if (mHeadsUpEntries.isEmpty()) {
return null;
}
@@ -338,21 +387,56 @@
}
/**
- * Sets the current user.
+ * Decides whether a click is invalid for a notification, i.e it has not been shown long enough
+ * that a user might have consciously clicked on it.
+ *
+ * @param key the key of the touched notification
+ * @return whether the touch is invalid and should be discarded
*/
+ public boolean shouldSwallowClick(String key) {
+ HeadsUpEntry entry = mHeadsUpEntries.get(key);
+ if (entry != null && mClock.currentTimeMillis() < entry.postTime) {
+ return true;
+ }
+ return false;
+ }
+
+ public void onComputeInternalInsets(ViewTreeObserver.InternalInsetsInfo info) {
+ if (mIsExpanded || mBar.isBouncerShowing()) {
+ // The touchable region is always the full area when expanded
+ return;
+ }
+ if (mHasPinnedNotification) {
+ ExpandableNotificationRow topEntry = getTopEntry().entry.row;
+ if (topEntry.isChildInGroup()) {
+ final ExpandableNotificationRow groupSummary
+ = mGroupManager.getGroupSummary(topEntry.getStatusBarNotification());
+ if (groupSummary != null) {
+ topEntry = groupSummary;
+ }
+ }
+ topEntry.getLocationOnScreen(mTmpTwoArray);
+ int minX = mTmpTwoArray[0];
+ int maxX = mTmpTwoArray[0] + topEntry.getWidth();
+ int maxY = topEntry.getIntrinsicHeight();
+
+ info.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
+ info.touchableRegion.set(minX, 0, maxX, maxY);
+ } else if (mHeadsUpGoingAway || mWaitingOnCollapseWhenGoingAway) {
+ info.setTouchableInsets(ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION);
+ info.touchableRegion.set(0, 0, mStatusBarWindowView.getWidth(), mStatusBarHeight);
+ }
+ }
+
public void setUser(int user) {
mUser = user;
}
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("HeadsUpManager state:");
- dumpInternal(fd, pw, args);
- }
-
- protected void dumpInternal(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.print(" mTouchAcceptanceDelay="); pw.println(mTouchAcceptanceDelay);
pw.print(" mSnoozeLengthMs="); pw.println(mSnoozeLengthMs);
- pw.print(" now="); pw.println(mClock.currentTimeMillis());
+ pw.print(" now="); pw.println(SystemClock.elapsedRealtime());
pw.print(" mUser="); pw.println(mUser);
for (HeadsUpEntry entry: mHeadsUpEntries.values()) {
pw.print(" HeadsUpEntry="); pw.println(entry.entry);
@@ -365,9 +449,6 @@
}
}
- /**
- * Returns if there are any pinned Heads Up Notifications or not.
- */
public boolean hasPinnedHeadsUp() {
return mHasPinnedNotification;
}
@@ -383,8 +464,14 @@
}
/**
- * Unpins all pinned Heads Up Notifications.
+ * Notifies that a notification was swiped out and will be removed.
+ *
+ * @param key the notification key
*/
+ public void addSwipedOutNotification(String key) {
+ mSwipedOutKeys.add(key);
+ }
+
public void unpinAll() {
for (String key : mHeadsUpEntries.keySet()) {
HeadsUpEntry entry = mHeadsUpEntries.get(key);
@@ -394,13 +481,60 @@
}
}
- /**
- * Returns the value of the tracking-heads-up flag. See the doc of {@code setTrackingHeadsUp} as
- * well.
- */
+ public void onExpandingFinished() {
+ if (mReleaseOnExpandFinish) {
+ releaseAllImmediately();
+ mReleaseOnExpandFinish = false;
+ } else {
+ for (NotificationData.Entry entry : mEntriesToRemoveAfterExpand) {
+ if (isHeadsUp(entry.key)) {
+ // Maybe the heads-up was removed already
+ removeHeadsUpEntry(entry);
+ }
+ }
+ }
+ mEntriesToRemoveAfterExpand.clear();
+ }
+
+ public void setTrackingHeadsUp(boolean trackingHeadsUp) {
+ mTrackingHeadsUp = trackingHeadsUp;
+ }
+
public boolean isTrackingHeadsUp() {
- // Might be implemented in subclass.
- return false;
+ return mTrackingHeadsUp;
+ }
+
+ public void setIsExpanded(boolean isExpanded) {
+ if (isExpanded != mIsExpanded) {
+ mIsExpanded = isExpanded;
+ if (isExpanded) {
+ // make sure our state is sane
+ mWaitingOnCollapseWhenGoingAway = false;
+ mHeadsUpGoingAway = false;
+ updateTouchableRegionListener();
+ }
+ }
+ }
+
+ /**
+ * @return the height of the top heads up notification when pinned. This is different from the
+ * intrinsic height, which also includes whether the notification is system expanded and
+ * is mainly used when dragging down from a heads up notification.
+ */
+ public int getTopHeadsUpPinnedHeight() {
+ HeadsUpEntry topEntry = getTopEntry();
+ if (topEntry == null || topEntry.entry == null) {
+ return 0;
+ }
+ ExpandableNotificationRow row = topEntry.entry.row;
+ if (row.isChildInGroup()) {
+ final ExpandableNotificationRow groupSummary
+ = mGroupManager.getGroupSummary(row.getStatusBarNotification());
+ if (groupSummary != null) {
+ row = groupSummary;
+ }
+ }
+ return row.getPinnedHeadsUpHeight();
}
/**
@@ -419,67 +553,147 @@
}
/**
- * Sets an entry to be expanded and therefore stick in the heads up area if it's pinned
- * until it's collapsed again.
+ * Set that we are exiting the headsUp pinned mode, but some notifications might still be
+ * animating out. This is used to keep the touchable regions in a sane state.
*/
+ public void setHeadsUpGoingAway(boolean headsUpGoingAway) {
+ if (headsUpGoingAway != mHeadsUpGoingAway) {
+ mHeadsUpGoingAway = headsUpGoingAway;
+ if (!headsUpGoingAway) {
+ waitForStatusBarLayout();
+ }
+ updateTouchableRegionListener();
+ }
+ }
+
+ /**
+ * We need to wait on the whole panel to collapse, before we can remove the touchable region
+ * listener.
+ */
+ private void waitForStatusBarLayout() {
+ mWaitingOnCollapseWhenGoingAway = true;
+ mStatusBarWindowView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
+ @Override
+ public void onLayoutChange(View v, int left, int top, int right, int bottom,
+ int oldLeft,
+ int oldTop, int oldRight, int oldBottom) {
+ if (mStatusBarWindowView.getHeight() <= mStatusBarHeight) {
+ mStatusBarWindowView.removeOnLayoutChangeListener(this);
+ mWaitingOnCollapseWhenGoingAway = false;
+ updateTouchableRegionListener();
+ }
+ }
+ });
+ }
+
+ public static void setIsClickedNotification(View child, boolean clicked) {
+ child.setTag(TAG_CLICKED_NOTIFICATION, clicked ? true : null);
+ }
+
+ public static boolean isClickedHeadsUpNotification(View child) {
+ Boolean clicked = (Boolean) child.getTag(TAG_CLICKED_NOTIFICATION);
+ return clicked != null && clicked;
+ }
+
+ public void setRemoteInputActive(NotificationData.Entry entry, boolean remoteInputActive) {
+ HeadsUpEntry headsUpEntry = mHeadsUpEntries.get(entry.key);
+ if (headsUpEntry != null && headsUpEntry.remoteInputActive != remoteInputActive) {
+ headsUpEntry.remoteInputActive = remoteInputActive;
+ if (remoteInputActive) {
+ headsUpEntry.removeAutoRemovalCallbacks();
+ } else {
+ headsUpEntry.updateEntry(false /* updatePostTime */);
+ }
+ }
+ }
/**
* Set an entry to be expanded and therefore stick in the heads up area if it's pinned
* until it's collapsed again.
*/
- public void setExpanded(@NonNull NotificationData.Entry entry, boolean expanded) {
- HeadsUpManager.HeadsUpEntry headsUpEntry = mHeadsUpEntries.get(entry.key);
- if (headsUpEntry != null && entry.row.isPinned()) {
- headsUpEntry.expanded(expanded);
+ public void setExpanded(NotificationData.Entry entry, boolean expanded) {
+ HeadsUpEntry headsUpEntry = mHeadsUpEntries.get(entry.key);
+ if (headsUpEntry != null && headsUpEntry.expanded != expanded && entry.row.isPinned()) {
+ headsUpEntry.expanded = expanded;
+ if (expanded) {
+ headsUpEntry.removeAutoRemovalCallbacks();
+ } else {
+ headsUpEntry.updateEntry(false /* updatePostTime */);
+ }
}
}
- @NonNull
- protected HeadsUpEntry createHeadsUpEntry() {
- return new HeadsUpEntry();
+ @Override
+ public void onReorderingAllowed() {
+ mBar.getNotificationScrollLayout().setHeadsUpGoingAwayAnimationsAllowed(false);
+ for (NotificationData.Entry entry : mEntriesToRemoveWhenReorderingAllowed) {
+ if (isHeadsUp(entry.key)) {
+ // Maybe the heads-up was removed already
+ removeHeadsUpEntry(entry);
+ }
+ }
+ mEntriesToRemoveWhenReorderingAllowed.clear();
+ mBar.getNotificationScrollLayout().setHeadsUpGoingAwayAnimationsAllowed(true);
}
- protected void releaseHeadsUpEntry(@NonNull HeadsUpEntry entry) {
- // Do nothing for HeadsUpEntry.
+ public void setVisualStabilityManager(VisualStabilityManager visualStabilityManager) {
+ mVisualStabilityManager = visualStabilityManager;
+ }
+
+ public void setStatusBarState(int statusBarState) {
+ mStatusBarState = statusBarState;
}
/**
* This represents a notification and how long it is in a heads up mode. It also manages its
* lifecycle automatically when created.
*/
- protected class HeadsUpEntry implements Comparable<HeadsUpEntry> {
- @Nullable public NotificationData.Entry entry;
+ public class HeadsUpEntry implements Comparable<HeadsUpEntry> {
+ public NotificationData.Entry entry;
public long postTime;
- public boolean remoteInputActive;
public long earliestRemovaltime;
+ private Runnable mRemoveHeadsUpRunnable;
+ public boolean remoteInputActive;
public boolean expanded;
- private Runnable mRemoveHeadsUpRunnable;
-
- public void setEntry(@Nullable final NotificationData.Entry entry) {
- setEntry(entry, null);
- }
-
- public void setEntry(@Nullable final NotificationData.Entry entry,
- @Nullable Runnable removeHeadsUpRunnable) {
+ public void setEntry(final NotificationData.Entry entry) {
this.entry = entry;
- this.mRemoveHeadsUpRunnable = removeHeadsUpRunnable;
// The actual post time will be just after the heads-up really slided in
postTime = mClock.currentTimeMillis() + mTouchAcceptanceDelay;
- updateEntry(true /* updatePostTime */);
+ mRemoveHeadsUpRunnable = new Runnable() {
+ @Override
+ public void run() {
+ if (!mVisualStabilityManager.isReorderingAllowed()) {
+ mEntriesToRemoveWhenReorderingAllowed.add(entry);
+ mVisualStabilityManager.addReorderingAllowedCallback(HeadsUpManager.this);
+ } else if (!mTrackingHeadsUp) {
+ removeHeadsUpEntry(entry);
+ } else {
+ mEntriesToRemoveAfterExpand.add(entry);
+ }
+ }
+ };
+ updateEntry();
+ }
+
+ public void updateEntry() {
+ updateEntry(true);
}
public void updateEntry(boolean updatePostTime) {
- if (DEBUG) Log.v(TAG, "updateEntry");
-
long currentTime = mClock.currentTimeMillis();
earliestRemovaltime = currentTime + mMinimumDisplayTime;
if (updatePostTime) {
postTime = Math.max(postTime, currentTime);
}
removeAutoRemovalCallbacks();
-
+ if (mEntriesToRemoveAfterExpand.contains(entry)) {
+ mEntriesToRemoveAfterExpand.remove(entry);
+ }
+ if (mEntriesToRemoveWhenReorderingAllowed.contains(entry)) {
+ mEntriesToRemoveWhenReorderingAllowed.remove(entry);
+ }
if (!isSticky()) {
long finishTime = postTime + mHeadsUpNotificationDecay;
long removeDelay = Math.max(finishTime - currentTime, mMinimumDisplayTime);
@@ -493,7 +707,7 @@
}
@Override
- public int compareTo(@NonNull HeadsUpEntry o) {
+ public int compareTo(HeadsUpEntry o) {
boolean isPinned = entry.row.isPinned();
boolean otherPinned = o.entry.row.isPinned();
if (isPinned && !otherPinned) {
@@ -520,29 +734,26 @@
: -1;
}
- public void expanded(boolean expanded) {
- this.expanded = expanded;
- }
-
- public void reset() {
- entry = null;
- expanded = false;
- remoteInputActive = false;
- removeAutoRemovalCallbacks();
- mRemoveHeadsUpRunnable = null;
- }
-
public void removeAutoRemovalCallbacks() {
- if (mRemoveHeadsUpRunnable != null)
- mHandler.removeCallbacks(mRemoveHeadsUpRunnable);
+ mHandler.removeCallbacks(mRemoveHeadsUpRunnable);
+ }
+
+ public boolean wasShownLongEnough() {
+ return earliestRemovaltime < mClock.currentTimeMillis();
}
public void removeAsSoonAsPossible() {
- if (mRemoveHeadsUpRunnable != null) {
- removeAutoRemovalCallbacks();
- mHandler.postDelayed(mRemoveHeadsUpRunnable,
- earliestRemovaltime - mClock.currentTimeMillis());
- }
+ removeAutoRemovalCallbacks();
+ mHandler.postDelayed(mRemoveHeadsUpRunnable,
+ earliestRemovaltime - mClock.currentTimeMillis());
+ }
+
+ public void reset() {
+ removeAutoRemovalCallbacks();
+ entry = null;
+ mRemoveHeadsUpRunnable = null;
+ expanded = false;
+ remoteInputActive = false;
}
}
@@ -551,4 +762,5 @@
return SystemClock.elapsedRealtime();
}
}
+
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpUtil.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpUtil.java
deleted file mode 100644
index 1e3c123c..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/HeadsUpUtil.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.policy;
-
-import android.view.View;
-
-import com.android.systemui.R;
-
-/**
- * A class of utility static methods for heads up notifications.
- */
-public final class HeadsUpUtil {
- private static final int TAG_CLICKED_NOTIFICATION = R.id.is_clicked_heads_up_tag;
-
- /**
- * Set the given view as clicked or not-clicked.
- * @param view The view to be set the flag to.
- * @param clicked True to set as clicked. False to not-clicked.
- */
- public static void setIsClickedHeadsUpNotification(View view, boolean clicked) {
- view.setTag(TAG_CLICKED_NOTIFICATION, clicked ? true : null);
- }
-
- /**
- * Check if the given view has the flag of "clicked notification"
- * @param view The view to be checked.
- * @return True if the view has clicked. False othrewise.
- */
- public static boolean isClickedHeadsUpNotification(View view) {
- Boolean clicked = (Boolean) view.getTag(TAG_CLICKED_NOTIFICATION);
- return clicked != null && clicked;
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/AmbientState.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/AmbientState.java
index d7a810e..424858a 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/AmbientState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/AmbientState.java
@@ -64,7 +64,7 @@
private boolean mPanelTracking;
private boolean mExpansionChanging;
private boolean mPanelFullWidth;
- private boolean mPulsing;
+ private Collection<HeadsUpManager.HeadsUpEntry> mPulsing;
private boolean mUnlockHintRunning;
private boolean mQsCustomizerShowing;
private int mIntrinsicPadding;
@@ -315,18 +315,23 @@
}
public boolean hasPulsingNotifications() {
- return mPulsing;
+ return mPulsing != null;
}
- public void setPulsing(boolean hasPulsing) {
+ public void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> hasPulsing) {
mPulsing = hasPulsing;
}
public boolean isPulsing(NotificationData.Entry entry) {
- if (!mPulsing || mHeadsUpManager == null) {
+ if (mPulsing == null) {
return false;
}
- return mHeadsUpManager.getAllEntries().anyMatch(e -> (e == entry));
+ for (HeadsUpManager.HeadsUpEntry e : mPulsing) {
+ if (e.entry == entry) {
+ return true;
+ }
+ }
+ return false;
}
public boolean isPanelTracking() {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
index b28e1a9..c114a6f 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayout.java
@@ -92,11 +92,10 @@
import com.android.systemui.statusbar.notification.FakeShadowView;
import com.android.systemui.statusbar.notification.NotificationUtils;
import com.android.systemui.statusbar.notification.VisibilityLocationProvider;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.phone.StatusBar;
import com.android.systemui.statusbar.phone.ScrimController;
-import com.android.systemui.statusbar.policy.HeadsUpUtil;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.ScrollAdapter;
import android.support.v4.graphics.ColorUtils;
@@ -289,7 +288,7 @@
private HashSet<View> mClearOverlayViewsWhenFinished = new HashSet<>();
private HashSet<Pair<ExpandableNotificationRow, Boolean>> mHeadsUpChangeAnimations
= new HashSet<>();
- private HeadsUpManagerPhone mHeadsUpManager;
+ private HeadsUpManager mHeadsUpManager;
private boolean mTrackingHeadsUp;
private ScrimController mScrimController;
private boolean mForceNoOverlappingRendering;
@@ -359,7 +358,7 @@
}
};
private PorterDuffXfermode mSrcMode = new PorterDuffXfermode(PorterDuff.Mode.SRC);
- private boolean mPulsing;
+ private Collection<HeadsUpManager.HeadsUpEntry> mPulsing;
private boolean mDrawBackgroundAsSrc;
private boolean mFadingOut;
private boolean mParentNotFullyVisible;
@@ -403,6 +402,7 @@
private final int mSeparatorThickness;
private final Rect mTmpRect = new Rect();
private int mClockBottom;
+ private int mAntiBurnInOffsetX;
public NotificationStackScrollLayout(Context context) {
this(context, null);
@@ -690,7 +690,7 @@
}
private void updateAlgorithmHeightAndPadding() {
- if (mPulsing) {
+ if (mPulsing != null) {
mTopPadding = mClockBottom;
} else {
mTopPadding = mAmbientState.isDark() ? mDarkTopPadding : mRegularTopPadding;
@@ -920,27 +920,6 @@
}
/**
- * @return the height of the top heads up notification when pinned. This is different from the
- * intrinsic height, which also includes whether the notification is system expanded and
- * is mainly used when dragging down from a heads up notification.
- */
- private int getTopHeadsUpPinnedHeight() {
- NotificationData.Entry topEntry = mHeadsUpManager.getTopEntry();
- if (topEntry == null) {
- return 0;
- }
- ExpandableNotificationRow row = topEntry.row;
- if (row.isChildInGroup()) {
- final ExpandableNotificationRow groupSummary
- = mGroupManager.getGroupSummary(row.getStatusBarNotification());
- if (groupSummary != null) {
- row = groupSummary;
- }
- }
- return row.getPinnedHeadsUpHeight();
- }
-
- /**
* @return the position from where the appear transition ends when expanding.
* Measured in absolute height.
*/
@@ -951,7 +930,7 @@
int minNotificationsForShelf = 1;
if (mTrackingHeadsUp
|| (mHeadsUpManager.hasPinnedHeadsUp() && !mAmbientState.isDark())) {
- appearPosition = getTopHeadsUpPinnedHeight();
+ appearPosition = mHeadsUpManager.getTopHeadsUpPinnedHeight();
minNotificationsForShelf = 2;
} else {
appearPosition = 0;
@@ -1219,9 +1198,9 @@
if (slidingChild instanceof ExpandableNotificationRow) {
ExpandableNotificationRow row = (ExpandableNotificationRow) slidingChild;
if (!mIsExpanded && row.isHeadsUp() && row.isPinned()
- && mHeadsUpManager.getTopEntry().row != row
+ && mHeadsUpManager.getTopEntry().entry.row != row
&& mGroupManager.getGroupSummary(
- mHeadsUpManager.getTopEntry().row.getStatusBarNotification())
+ mHeadsUpManager.getTopEntry().entry.row.getStatusBarNotification())
!= row) {
continue;
}
@@ -2141,7 +2120,7 @@
@Override
public boolean hasPulsingNotifications() {
- return mPulsing;
+ return mPulsing != null;
}
private void updateScrollability() {
@@ -2774,7 +2753,7 @@
}
private boolean isClickedHeadsUp(View child) {
- return HeadsUpUtil.isClickedHeadsUpNotification(child);
+ return HeadsUpManager.isClickedHeadsUpNotification(child);
}
/**
@@ -3889,9 +3868,14 @@
applyCurrentBackgroundBounds();
updateWillNotDraw();
updateContentHeight();
+ updateAntiBurnInTranslation();
notifyHeightChangeListener(mShelf);
}
+ private void updateAntiBurnInTranslation() {
+ setTranslationX(mAmbientState.isDark() ? mAntiBurnInOffsetX : 0);
+ }
+
/**
* Updates whether or not this Layout will perform its own custom drawing (i.e. whether or
* not {@link #onDraw(Canvas)} is called). This method should be called whenever the
@@ -4274,7 +4258,7 @@
mAnimationFinishedRunnables.add(runnable);
}
- public void setHeadsUpManager(HeadsUpManagerPhone headsUpManager) {
+ public void setHeadsUpManager(HeadsUpManager headsUpManager) {
mHeadsUpManager = headsUpManager;
mAmbientState.setHeadsUpManager(headsUpManager);
}
@@ -4342,8 +4326,8 @@
return mIsExpanded;
}
- public void setPulsing(boolean pulsing, int clockBottom) {
- if (!mPulsing && !pulsing) {
+ public void setPulsing(Collection<HeadsUpManager.HeadsUpEntry> pulsing, int clockBottom) {
+ if (mPulsing == null && pulsing == null) {
return;
}
mPulsing = pulsing;
@@ -4473,15 +4457,16 @@
mHeadsUpGoingAwayAnimationsAllowed = headsUpGoingAwayAnimationsAllowed;
}
- public void setDarkShelfOffsetX(int shelfOffsetX) {
- mShelf.setDarkOffsetX(shelfOffsetX);
+ public void setAntiBurnInOffsetX(int antiBurnInOffsetX) {
+ mAntiBurnInOffsetX = antiBurnInOffsetX;
+ updateAntiBurnInTranslation();
}
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println(String.format("[%s: pulsing=%s qsCustomizerShowing=%s visibility=%s"
+ " alpha:%f scrollY:%d]",
this.getClass().getSimpleName(),
- mPulsing ? "T":"f",
+ mPulsing != null ?"T":"f",
mAmbientState.isQsCustomizerShowing() ? "T":"f",
getVisibility() == View.VISIBLE ? "visible"
: getVisibility() == View.GONE ? "gone"
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/stack/ViewState.java b/packages/SystemUI/src/com/android/systemui/statusbar/stack/ViewState.java
index 04a7bd7..682b849 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/stack/ViewState.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/stack/ViewState.java
@@ -30,7 +30,7 @@
import com.android.systemui.statusbar.ExpandableView;
import com.android.systemui.statusbar.notification.AnimatableProperty;
import com.android.systemui.statusbar.notification.PropertyAnimator;
-import com.android.systemui.statusbar.policy.HeadsUpUtil;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
/**
* A state of a view. This can be used to apply a set of view properties to a view with
@@ -582,7 +582,7 @@
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
- HeadsUpUtil.setIsClickedHeadsUpNotification(child, false);
+ HeadsUpManager.setIsClickedNotification(child, false);
child.setTag(TAG_ANIMATOR_TRANSLATION_Y, null);
child.setTag(TAG_START_TRANSLATION_Y, null);
child.setTag(TAG_END_TRANSLATION_Y, null);
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
index 001a582..0c6e0f6 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeDialogImpl.java
@@ -36,7 +36,6 @@
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
-import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.AudioSystem;
@@ -58,7 +57,6 @@
import android.view.View.AccessibilityDelegate;
import android.view.View.OnAttachStateChangeListener;
import android.view.View.OnClickListener;
-import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
@@ -105,6 +103,7 @@
private CustomDialog mDialog;
private ViewGroup mDialogView;
private ViewGroup mDialogRowsView;
+ private ViewGroup mFooter;
private ImageButton mRingerIcon;
private TextView mRingerStatus;
private final List<VolumeRow> mRows = new ArrayList<>();
@@ -202,8 +201,9 @@
hardwareLayout.setOutsideTouchListener(view -> dismiss(DISMISS_REASON_TOUCH_OUTSIDE));
mDialogRowsView = mDialog.findViewById(R.id.volume_dialog_rows);
- mRingerIcon = mDialog.findViewById(R.id.ringer_icon);
- mRingerStatus = mDialog.findViewById(R.id.ringer_status);
+ mFooter = mDialog.findViewById(R.id.footer);
+ mRingerIcon = mFooter.findViewById(R.id.ringer_icon);
+ mRingerStatus = mFooter.findViewById(R.id.ringer_status);
if (mRows.isEmpty()) {
addRow(AudioManager.STREAM_MUSIC,
@@ -340,36 +340,8 @@
row.outputChooser = row.view.findViewById(R.id.output_chooser);
row.outputChooser.setOnClickListener(mClickOutputChooser);
- row.outputChooser.findViewById(R.id.output_chooser_button)
- .setOnClickListener(mClickOutputChooser);
row.connectedDevice = row.view.findViewById(R.id.volume_row_connected_device);
- // forward events above the slider into the slider
- row.view.findViewById(R.id.volume_row_slider_frame)
- .setOnTouchListener(new OnTouchListener() {
- private final Rect mSliderHitRect = new Rect();
- private boolean mDragging;
-
- @SuppressLint("ClickableViewAccessibility")
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- row.slider.getHitRect(mSliderHitRect);
- if (!mDragging && event.getActionMasked() == MotionEvent.ACTION_DOWN
- && event.getY() < mSliderHitRect.top) {
- mDragging = true;
- }
- if (mDragging) {
- event.offsetLocation(-mSliderHitRect.left, -mSliderHitRect.top);
- row.slider.dispatchTouchEvent(event);
- if (event.getActionMasked() == MotionEvent.ACTION_UP
- || event.getActionMasked() == MotionEvent.ACTION_CANCEL) {
- mDragging = false;
- }
- return true;
- }
- return false;
- }
- });
row.icon = row.view.findViewById(R.id.volume_row_icon);
row.icon.setImageResource(iconRes);
if (row.stream != AudioSystem.STREAM_ACCESSIBILITY) {
@@ -412,6 +384,8 @@
if (ss == null) {
return;
}
+ // normal -> vibrate -> silent -> normal (skip vibrate if device doesn't have
+ // a vibrator.
final boolean hasVibrator = mController.hasVibrator();
if (mState.ringerModeInternal == AudioManager.RINGER_MODE_NORMAL) {
if (hasVibrator) {
@@ -419,7 +393,12 @@
} else {
final boolean wasZero = ss.level == 0;
mController.setStreamVolume(AudioManager.STREAM_RING, wasZero ? 1 : 0);
+ mController.setRingerMode(AudioManager.RINGER_MODE_SILENT, false);
}
+ } else if (mState.ringerModeInternal == AudioManager.RINGER_MODE_VIBRATE) {
+ final boolean wasZero = ss.level == 0;
+ mController.setStreamVolume(AudioManager.STREAM_RING, wasZero ? 1 : 0);
+ mController.setRingerMode(AudioManager.RINGER_MODE_SILENT, false);
} else {
mController.setRingerMode(AudioManager.RINGER_MODE_NORMAL, false);
if (ss.level == 0) {
@@ -908,7 +887,6 @@
private final OnClickListener mClickOutputChooser = new OnClickListener() {
@Override
public void onClick(View v) {
- // TODO: log
dismissH(DISMISS_REASON_OUTPUT_CHOOSER);
showOutputChooserH();
}
diff --git a/packages/SystemUI/src/com/android/systemui/volume/VolumeUiLayout.java b/packages/SystemUI/src/com/android/systemui/volume/VolumeUiLayout.java
index 368194e..f50a287 100644
--- a/packages/SystemUI/src/com/android/systemui/volume/VolumeUiLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/volume/VolumeUiLayout.java
@@ -309,6 +309,12 @@
return super.getOutlineProvider();
}
+ @Override
+ public void setPressed(boolean pressed)
+ {
+ // Ignore presses because it activates the seekbar thumb unnecessarily.
+ }
+
public void setOutsideTouchListener(OnClickListener onClickListener) {
mHasOutsideTouch = true;
requestLayout();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java b/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
index 40f8059..dfc1852 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/AutoAddTrackerTest.java
@@ -30,6 +30,7 @@
import com.android.systemui.Prefs.Key;
import com.android.systemui.SysuiTestCase;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -40,6 +41,11 @@
private AutoAddTracker mAutoTracker;
+ @Before
+ public void setUp() {
+ Secure.putString(mContext.getContentResolver(), Secure.QS_AUTO_ADDED_TILES, "");
+ }
+
@Test
public void testMigration() {
Prefs.putBoolean(mContext, Key.QS_DATA_SAVER_ADDED, true);
@@ -50,7 +56,10 @@
assertTrue(mAutoTracker.isAdded(WORK));
assertFalse(mAutoTracker.isAdded(INVERSION));
+ // These keys have been removed; retrieving their values should always return the default.
+ assertTrue(Prefs.getBoolean(mContext, Key.QS_DATA_SAVER_ADDED, true ));
assertFalse(Prefs.getBoolean(mContext, Key.QS_DATA_SAVER_ADDED, false));
+ assertTrue(Prefs.getBoolean(mContext, Key.QS_WORK_ADDED, true));
assertFalse(Prefs.getBoolean(mContext, Key.QS_WORK_ADDED, false));
mAutoTracker.destroy();
@@ -96,5 +105,4 @@
mAutoTracker.destroy();
}
-
}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
index f3c1171..6e7477f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/NotificationTestHelper.java
@@ -32,7 +32,6 @@
import com.android.systemui.statusbar.notification.AboveShelfObserver;
import com.android.systemui.statusbar.notification.InflationException;
import com.android.systemui.statusbar.notification.NotificationInflaterTest;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.phone.NotificationGroupManager;
import com.android.systemui.statusbar.policy.HeadsUpManager;
@@ -52,7 +51,7 @@
public NotificationTestHelper(Context context) {
mContext = context;
mInstrumentation = InstrumentationRegistry.getInstrumentation();
- mHeadsUpManager = new HeadsUpManagerPhone(mContext, null, mGroupManager, null, null);
+ mHeadsUpManager = new HeadsUpManager(mContext, null, mGroupManager);
}
public ExpandableNotificationRow createRow() throws Exception {
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
index a95e3db..2d2db1b 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/AutoTileManagerTest.java
@@ -18,45 +18,48 @@
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import android.app.AlarmManager.AlarmClockInfo;
+import android.os.Handler;
import android.support.test.filters.SmallTest;
import android.testing.AndroidTestingRunner;
import android.testing.TestableLooper;
import android.testing.TestableLooper.RunWithLooper;
-
import com.android.internal.app.ColorDisplayController;
import com.android.systemui.Dependency;
-import com.android.systemui.Prefs;
-import com.android.systemui.Prefs.Key;
import com.android.systemui.SysuiTestCase;
+import com.android.systemui.qs.AutoAddTracker;
import com.android.systemui.qs.QSTileHost;
-
-import org.junit.After;
+import com.android.systemui.statusbar.policy.NextAlarmController;
+import com.android.systemui.statusbar.policy.NextAlarmController.NextAlarmChangeCallback;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mockito;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
@RunWith(AndroidTestingRunner.class)
@RunWithLooper
@SmallTest
public class AutoTileManagerTest extends SysuiTestCase {
- private QSTileHost mQsTileHost;
+ @Mock private QSTileHost mQsTileHost;
+ @Mock private AutoAddTracker mAutoAddTracker;
+ @Captor private ArgumentCaptor<NextAlarmChangeCallback> mAlarmCallback;
+
private AutoTileManager mAutoTileManager;
@Before
public void setUp() throws Exception {
- mDependency.injectTestDependency(Dependency.BG_LOOPER,
- TestableLooper.get(this).getLooper());
- Prefs.putBoolean(mContext, Key.QS_NIGHTDISPLAY_ADDED, false);
- mQsTileHost = Mockito.mock(QSTileHost.class);
- mAutoTileManager = new AutoTileManager(mContext, mQsTileHost);
- }
-
- @After
- public void tearDown() throws Exception {
- mAutoTileManager = null;
+ MockitoAnnotations.initMocks(this);
+ mDependency.injectMockDependency(NextAlarmController.class);
+ mAutoTileManager = new AutoTileManager(mContext, mAutoAddTracker,
+ mQsTileHost, new Handler(TestableLooper.get(this).getLooper()));
+ verify(Dependency.get(NextAlarmController.class))
+ .addCallback(mAlarmCallback.capture());
}
@Test
@@ -106,4 +109,30 @@
ColorDisplayController.AUTO_MODE_DISABLED);
verify(mQsTileHost, never()).addTile("night");
}
+
+ @Test
+ public void alarmTileAdded_whenAlarmSet() {
+ mAlarmCallback.getValue().onNextAlarmChanged(new AlarmClockInfo(0, null));
+
+ verify(mQsTileHost).addTile("alarm");
+ verify(mAutoAddTracker).setTileAdded("alarm");
+ }
+
+ @Test
+ public void alarmTileNotAdded_whenAlarmNotSet() {
+ mAlarmCallback.getValue().onNextAlarmChanged(null);
+
+ verify(mQsTileHost, never()).addTile("alarm");
+ verify(mAutoAddTracker, never()).setTileAdded("alarm");
+ }
+
+ @Test
+ public void alarmTileNotAdded_whenAlreadyAdded() {
+ when(mAutoAddTracker.isAdded("alarm")).thenReturn(true);
+
+ mAlarmCallback.getValue().onNextAlarmChanged(new AlarmClockInfo(0, null));
+
+ verify(mQsTileHost, never()).addTile("alarm");
+ verify(mAutoAddTracker, never()).setTileAdded("alarm");
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
deleted file mode 100644
index 28f9417..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/HeadsUpManagerPhoneTest.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.statusbar.phone;
-
-import android.app.ActivityManager;
-import android.app.Notification;
-import android.content.Context;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.UserHandle;
-import android.view.View;
-import android.service.notification.StatusBarNotification;
-import android.support.test.filters.SmallTest;
-import android.testing.AndroidTestingRunner;
-import android.testing.TestableLooper;
-
-import com.android.systemui.R;
-import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.ExpandableNotificationRow;
-import com.android.systemui.statusbar.NotificationData;
-import com.android.systemui.statusbar.StatusBarIconView;
-import com.android.systemui.statusbar.notification.VisualStabilityManager;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnit;
-import org.mockito.junit.MockitoRule;
-
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.assertFalse;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-@SmallTest
-@RunWith(AndroidTestingRunner.class)
-@TestableLooper.RunWithLooper
-public class HeadsUpManagerPhoneTest extends SysuiTestCase {
- @Rule public MockitoRule rule = MockitoJUnit.rule();
-
- private static final String TEST_PACKAGE_NAME = "test";
- private static final int TEST_UID = 0;
-
- private HeadsUpManagerPhone mHeadsUpManager;
-
- private NotificationData.Entry mEntry;
- private StatusBarNotification mSbn;
-
- private final Handler mHandler = new Handler(Looper.getMainLooper());
-
- @Mock private NotificationGroupManager mGroupManager;
- @Mock private View mStatusBarWindowView;
- @Mock private StatusBar mBar;
- @Mock private ExpandableNotificationRow mRow;
- @Mock private VisualStabilityManager mVSManager;
-
- @Before
- public void setUp() {
- when(mVSManager.isReorderingAllowed()).thenReturn(true);
-
- mHeadsUpManager = new HeadsUpManagerPhone(mContext, mStatusBarWindowView, mGroupManager, mBar, mVSManager);
-
- Notification.Builder n = new Notification.Builder(mContext, "")
- .setSmallIcon(R.drawable.ic_person)
- .setContentTitle("Title")
- .setContentText("Text");
- mSbn = new StatusBarNotification(TEST_PACKAGE_NAME, TEST_PACKAGE_NAME, 0, null, TEST_UID,
- 0, n.build(), new UserHandle(ActivityManager.getCurrentUser()), null, 0);
-
- mEntry = new NotificationData.Entry(mSbn);
- mEntry.row = mRow;
- mEntry.expandedIcon = mock(StatusBarIconView.class);
- }
-
- @Test
- public void testBasicOperations() {
- // Check the initial state.
- assertNull(mHeadsUpManager.getEntry(mEntry.key));
- assertNull(mHeadsUpManager.getTopEntry());
- assertEquals(0, mHeadsUpManager.getAllEntries().count());
- assertFalse(mHeadsUpManager.hasHeadsUpNotifications());
-
- // Add a notification.
- mHeadsUpManager.showNotification(mEntry);
-
- assertEquals(mEntry, mHeadsUpManager.getEntry(mEntry.key));
- assertEquals(mEntry, mHeadsUpManager.getTopEntry());
- assertEquals(1, mHeadsUpManager.getAllEntries().count());
- assertTrue(mHeadsUpManager.hasHeadsUpNotifications());
-
- // Update the notification.
- mHeadsUpManager.updateNotification(mEntry, false);
-
- assertEquals(mEntry, mHeadsUpManager.getEntry(mEntry.key));
- assertEquals(mEntry, mHeadsUpManager.getTopEntry());
- assertEquals(1, mHeadsUpManager.getAllEntries().count());
- assertTrue(mHeadsUpManager.hasHeadsUpNotifications());
-
- // Remove but defer, since the notification is visible on display.
- mHeadsUpManager.removeNotification(mEntry.key, false);
-
- assertEquals(mEntry, mHeadsUpManager.getEntry(mEntry.key));
- assertEquals(mEntry, mHeadsUpManager.getTopEntry());
- assertEquals(1, mHeadsUpManager.getAllEntries().count());
- assertTrue(mHeadsUpManager.hasHeadsUpNotifications());
- }
-}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
index 31442af..bdf9b1f 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java
@@ -86,8 +86,8 @@
import com.android.systemui.statusbar.StatusBarState;
import com.android.systemui.statusbar.notification.ActivityLaunchAnimator;
import com.android.systemui.statusbar.notification.VisualStabilityManager;
-import com.android.systemui.statusbar.phone.HeadsUpManagerPhone;
import com.android.systemui.statusbar.policy.DeviceProvisionedController;
+import com.android.systemui.statusbar.policy.HeadsUpManager;
import com.android.systemui.statusbar.policy.KeyguardMonitor;
import com.android.systemui.statusbar.policy.KeyguardMonitorImpl;
import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
@@ -110,7 +110,7 @@
@Mock private UnlockMethodCache mUnlockMethodCache;
@Mock private KeyguardIndicationController mKeyguardIndicationController;
@Mock private NotificationStackScrollLayout mStackScroller;
- @Mock private HeadsUpManagerPhone mHeadsUpManager;
+ @Mock private HeadsUpManager mHeadsUpManager;
@Mock private SystemServicesProxy mSystemServicesProxy;
@Mock private NotificationPanelView mNotificationPanelView;
@Mock private IStatusBarService mBarService;
@@ -588,7 +588,7 @@
static class TestableStatusBar extends StatusBar {
public TestableStatusBar(StatusBarKeyguardViewManager man,
UnlockMethodCache unlock, KeyguardIndicationController key,
- NotificationStackScrollLayout stack, HeadsUpManagerPhone hum,
+ NotificationStackScrollLayout stack, HeadsUpManager hum,
PowerManager pm, NotificationPanelView panelView,
IStatusBarService barService, NotificationListener notificationListener,
NotificationLogger notificationLogger,
@@ -650,7 +650,7 @@
public void setUpForTest(NotificationPresenter presenter,
NotificationListContainer listContainer,
Callback callback,
- HeadsUpManagerPhone headsUpManager,
+ HeadsUpManager headsUpManager,
NotificationData notificationData) {
super.setUpWithPresenter(presenter, listContainer, callback, headsUpManager);
mNotificationData = notificationData;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayoutTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayoutTest.java
index 1c010b6..d9673d3 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayoutTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/stack/NotificationStackScrollLayoutTest.java
@@ -61,4 +61,15 @@
Assert.assertFalse(mStackScroller.isDimmed());
}
+ @Test
+ public void testAntiBurnInOffset() {
+ final int burnInOffset = 30;
+ mStackScroller.setAntiBurnInOffsetX(burnInOffset);
+ mStackScroller.setDark(false /* dark */, false /* animated */, null /* touch */);
+ Assert.assertEquals(0 /* expected */, mStackScroller.getTranslationX(), 0.01 /* delta */);
+ mStackScroller.setDark(true /* dark */, false /* animated */, null /* touch */);
+ Assert.assertEquals(burnInOffset /* expected */, mStackScroller.getTranslationX(),
+ 0.01 /* delta */);
+ }
+
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/OutputChooserDialogTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/OutputChooserDialogTest.java
index c18ed73..f7bb065 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/OutputChooserDialogTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/OutputChooserDialogTest.java
@@ -44,11 +44,13 @@
import org.junit.After;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+@Ignore
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -87,7 +89,7 @@
public void tearDown() throws Exception {
TestableLooper.get(this).processAllMessages();
}
-
+/*
@Test
public void testClickMediaRouterItemConnectsMedia() {
mDialog.show();
@@ -137,7 +139,7 @@
.getText().toString().contains("Phone"));
mDialog.dismiss();
}
-
+*/
@Test
public void testNoMediaScanIfInCall() {
mDialog.setIsInCall(true);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
index 2d28c9f..43d60e4 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/volume/VolumeDialogImplTest.java
@@ -16,12 +16,21 @@
package com.android.systemui.volume;
+import static android.media.AudioManager.RINGER_MODE_NORMAL;
+import static android.media.AudioManager.RINGER_MODE_SILENT;
+import static android.media.AudioManager.RINGER_MODE_VIBRATE;
+import static android.media.AudioManager.STREAM_RING;
+
import static com.android.systemui.volume.Events.DISMISS_REASON_UNKNOWN;
import static com.android.systemui.volume.Events.SHOW_REASON_UNKNOWN;
import static com.android.systemui.volume.VolumeDialogControllerImpl.STREAMS;
import static junit.framework.Assert.assertTrue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
import android.app.KeyguardManager;
import android.media.AudioManager;
import android.support.test.filters.SmallTest;
@@ -32,11 +41,14 @@
import android.view.ViewGroup;
import android.widget.ImageView;
+import com.android.systemui.R;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.plugins.VolumeDialogController;
+import com.android.systemui.plugins.VolumeDialogController.State;
import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -44,6 +56,7 @@
import java.util.function.Predicate;
+@Ignore
@SmallTest
@RunWith(AndroidTestingRunner.class)
@TestableLooper.RunWithLooper
@@ -70,13 +83,19 @@
mDialog = new VolumeDialogImpl(getContext());
mDialog.init(0, null);
- VolumeDialogController.State state = new VolumeDialogController.State();
+ State state = createShellState();
+ mDialog.onStateChangedH(state);
+ }
+
+ private State createShellState() {
+ State state = new VolumeDialogController.State();
for (int i = AudioManager.STREAM_VOICE_CALL; i <= AudioManager.STREAM_ACCESSIBILITY; i++) {
VolumeDialogController.StreamState ss = new VolumeDialogController.StreamState();
ss.name = STREAMS.get(i);
+ ss.level = 1;
state.states.append(i, ss);
}
- mDialog.onStateChangedH(state);
+ return state;
}
private void navigateViews(View view, Predicate<View> condition) {
@@ -94,7 +113,7 @@
+ " failed test", condition.test(view));
}
}
-
+/*
@Test
public void testContentDescriptions() {
mDialog.show(SHOW_REASON_UNKNOWN);
@@ -111,4 +130,95 @@
mDialog.dismiss(DISMISS_REASON_UNKNOWN);
}
+ @Test
+ public void testNoDuplicationOfParentState() {
+ mDialog.show(SHOW_REASON_UNKNOWN);
+ ViewGroup dialog = mDialog.getDialogView();
+
+ navigateViews(dialog, view -> !view.isDuplicateParentStateEnabled());
+
+ mDialog.dismiss(DISMISS_REASON_UNKNOWN);
+ }
+
+ @Test
+ public void testNoClickableViewGroups() {
+ mDialog.show(SHOW_REASON_UNKNOWN);
+ ViewGroup dialog = mDialog.getDialogView();
+
+ navigateViews(dialog, view -> {
+ if (view instanceof ViewGroup) {
+ return !view.isClickable();
+ } else {
+ return true;
+ }
+ });
+
+ mDialog.dismiss(DISMISS_REASON_UNKNOWN);
+ }
+
+ @Test
+ public void testTristateToggle_withVibrator() {
+ when(mController.hasVibrator()).thenReturn(true);
+
+ State state = createShellState();
+ state.ringerModeInternal = RINGER_MODE_NORMAL;
+ mDialog.onStateChangedH(state);
+
+ mDialog.show(SHOW_REASON_UNKNOWN);
+ ViewGroup dialog = mDialog.getDialogView();
+
+ // click once, verify updates to vibrate
+ dialog.findViewById(R.id.ringer_icon).performClick();
+ verify(mController, times(1)).setRingerMode(RINGER_MODE_VIBRATE, false);
+
+ // fake the update back to the dialog with the new ringer mode
+ state = createShellState();
+ state.ringerModeInternal = RINGER_MODE_VIBRATE;
+ mDialog.onStateChangedH(state);
+
+ // click once, verify updates to silent
+ dialog.findViewById(R.id.ringer_icon).performClick();
+ verify(mController, times(1)).setRingerMode(RINGER_MODE_SILENT, false);
+ verify(mController, times(1)).setStreamVolume(STREAM_RING, 0);
+
+ // fake the update back to the dialog with the new ringer mode
+ state = createShellState();
+ state.states.get(STREAM_RING).level = 0;
+ state.ringerModeInternal = RINGER_MODE_SILENT;
+ mDialog.onStateChangedH(state);
+
+ // click once, verify updates to normal
+ dialog.findViewById(R.id.ringer_icon).performClick();
+ verify(mController, times(1)).setRingerMode(RINGER_MODE_NORMAL, false);
+ verify(mController, times(1)).setStreamVolume(STREAM_RING, 0);
+ }
+
+ @Test
+ public void testTristateToggle_withoutVibrator() {
+ when(mController.hasVibrator()).thenReturn(false);
+
+ State state = createShellState();
+ state.ringerModeInternal = RINGER_MODE_NORMAL;
+ mDialog.onStateChangedH(state);
+
+ mDialog.show(SHOW_REASON_UNKNOWN);
+ ViewGroup dialog = mDialog.getDialogView();
+
+ // click once, verify updates to silent
+ dialog.findViewById(R.id.ringer_icon).performClick();
+ verify(mController, times(1)).setRingerMode(RINGER_MODE_SILENT, false);
+ verify(mController, times(1)).setStreamVolume(STREAM_RING, 0);
+
+ // fake the update back to the dialog with the new ringer mode
+ state = createShellState();
+ state.states.get(STREAM_RING).level = 0;
+ state.ringerModeInternal = RINGER_MODE_SILENT;
+ mDialog.onStateChangedH(state);
+
+ // click once, verify updates to normal
+ dialog.findViewById(R.id.ringer_icon).performClick();
+ verify(mController, times(1)).setRingerMode(RINGER_MODE_NORMAL, false);
+ verify(mController, times(1)).setStreamVolume(STREAM_RING, 0);
+ }
+ */
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/volume/ZenModePanelTest.java b/packages/SystemUI/tests/src/com/android/systemui/volume/ZenModePanelTest.java
deleted file mode 100644
index 4ab2063..0000000
--- a/packages/SystemUI/tests/src/com/android/systemui/volume/ZenModePanelTest.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/**
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.volume;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import android.net.Uri;
-import android.provider.Settings;
-import android.service.notification.Condition;
-import android.service.notification.ZenModeConfig;
-import android.support.test.annotation.UiThreadTest;
-import android.support.test.filters.SmallTest;
-import android.support.test.runner.AndroidJUnit4;
-import android.test.FlakyTest;
-import android.view.LayoutInflater;
-
-import com.android.systemui.SysuiTestCase;
-import com.android.systemui.statusbar.policy.ZenModeController;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@Ignore
-@SmallTest
-@RunWith(AndroidJUnit4.class)
-public class ZenModePanelTest extends SysuiTestCase {
-
- ZenModePanel mPanel;
- ZenModeController mController;
- Uri mForeverId;
-
- @Before
- public void setup() throws Exception {
- final LayoutInflater layoutInflater = LayoutInflater.from(mContext);
- mPanel = (ZenModePanel) layoutInflater.inflate(com.android.systemui.R.layout.zen_mode_panel,
- null);
- mController = mock(ZenModeController.class);
- mForeverId = Condition.newId(mContext).appendPath("forever").build();
-
- mPanel.init(mController);
- }
-
- private void assertProperConditionTagTypes(boolean hasAlarm) {
- final int N = mPanel.getVisibleConditions();
- assertEquals(hasAlarm ? 3 : 2, N);
-
- assertEquals(mForeverId, mPanel.getConditionTagAt(0).condition.id);
- assertTrue(ZenModeConfig.isValidCountdownConditionId(
- mPanel.getConditionTagAt(1).condition.id));
- assertFalse(ZenModeConfig.isValidCountdownToAlarmConditionId(
- mPanel.getConditionTagAt(1).condition.id));
- if (hasAlarm) {
- assertTrue(ZenModeConfig.isValidCountdownToAlarmConditionId(
- mPanel.getConditionTagAt(2).condition.id));
- }
- }
-
- @Test
- public void testHandleUpdateConditions_foreverSelected_alarmExists() {
- Condition forever = new Condition(mForeverId, "", Condition.STATE_TRUE);
-
- when(mController.getNextAlarm()).thenReturn(System.currentTimeMillis() + 1000);
-
- mPanel.handleUpdateConditions(forever);
- assertProperConditionTagTypes(true);
- assertTrue(mPanel.getConditionTagAt(0).rb.isChecked());
- }
-
- @Test
- public void testHandleUpdateConditions_foreverSelected_noAlarm() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
- Condition forever = new Condition(foreverId, "", Condition.STATE_TRUE);
-
- when(mController.getNextAlarm()).thenReturn((long) 0);
-
- mPanel.handleUpdateConditions(forever);
- assertProperConditionTagTypes(false);
- assertEquals(foreverId, mPanel.getConditionTagAt(0).condition.id);
- }
-
- @Test
- public void testHandleUpdateConditions_countdownSelected_alarmExists() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
-
- Condition countdown = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + (3 * 60 * 60 * 1000) + 4000, false),
- "", Condition.STATE_TRUE);
-
- when(mController.getNextAlarm()).thenReturn(System.currentTimeMillis() + 1000);
-
- mPanel.handleUpdateConditions(countdown);
- assertProperConditionTagTypes(true);
- assertTrue(mPanel.getConditionTagAt(1).rb.isChecked());
- }
-
- @Test
- public void testHandleUpdateConditions_countdownSelected_noAlarm() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
-
- Condition countdown = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + (3 * 60 * 60 * 1000) + 4000, false),
- "", Condition.STATE_TRUE);
-
- when(mController.getNextAlarm()).thenReturn((long) 0);
-
- mPanel.handleUpdateConditions(countdown);
- assertProperConditionTagTypes(false);
- assertTrue(mPanel.getConditionTagAt(1).rb.isChecked());
- }
-
- @Test
- public void testHandleUpdateConditions_nextAlarmSelected() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
-
- Condition alarm = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + 1000, true),
- "", Condition.STATE_TRUE);
- when(mController.getNextAlarm()).thenReturn(System.currentTimeMillis() + 9000);
-
- mPanel.handleUpdateConditions(alarm);
-
- assertProperConditionTagTypes(true);
- assertEquals(alarm, mPanel.getConditionTagAt(2).condition);
- assertTrue(mPanel.getConditionTagAt(2).rb.isChecked());
- }
-
- @Test
- public void testHandleUpdateConditions_foreverSelected_alarmConditionDoesNotChangeIfAttached() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
- Condition forever = new Condition(foreverId, "", Condition.STATE_TRUE);
-
- Condition alarm = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + 9000, true),
- "", Condition.STATE_TRUE);
- when(mController.getNextAlarm()).thenReturn(System.currentTimeMillis() + 1000);
-
- mPanel.handleUpdateConditions(alarm);
- mPanel.setAttached(true);
- mPanel.handleUpdateConditions(forever);
-
- assertProperConditionTagTypes(true);
- assertEquals(alarm, mPanel.getConditionTagAt(2).condition);
- assertTrue(mPanel.getConditionTagAt(0).rb.isChecked());
- }
-
- @Test
- public void testHandleUpdateConditions_foreverSelected_timeConditionDoesNotChangeIfAttached() {
- Uri foreverId = Condition.newId(mContext).appendPath("forever").build();
- Condition forever = new Condition(foreverId, "", Condition.STATE_TRUE);
-
- Condition countdown = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + (3 * 60 * 60 * 1000) + 4000, false),
- "", Condition.STATE_TRUE);
- when(mController.getNextAlarm()).thenReturn((long) 0);
-
- mPanel.handleUpdateConditions(countdown);
- mPanel.setAttached(true);
- mPanel.handleUpdateConditions(forever);
-
- assertProperConditionTagTypes(false);
- assertEquals(countdown, mPanel.getConditionTagAt(1).condition);
- assertTrue(mPanel.getConditionTagAt(0).rb.isChecked());
- }
-
- @Test
- @UiThreadTest
- public void testHandleUpdateManualRule_stillSelectedAfterModeChange() {
- ZenModeConfig.ZenRule rule = new ZenModeConfig.ZenRule();
-
- Condition alarm = new Condition(ZenModeConfig.toCountdownConditionId(
- System.currentTimeMillis() + 1000, true),
- "", Condition.STATE_TRUE);
-
- rule.condition = alarm;
- rule.conditionId = alarm.id;
- rule.enabled = true;
- rule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
-
- mPanel.handleUpdateManualRule(rule);
-
- assertProperConditionTagTypes(true);
- assertEquals(alarm, mPanel.getConditionTagAt(2).condition);
- assertTrue(mPanel.getConditionTagAt(2).rb.isChecked());
-
- assertEquals(Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS,
- mPanel.getSelectedZen(Settings.Global.ZEN_MODE_OFF));
-
- rule.zenMode = Settings.Global.ZEN_MODE_NO_INTERRUPTIONS;
-
- mPanel.handleUpdateManualRule(rule);
-
- assertProperConditionTagTypes(true);
- assertEquals(alarm, mPanel.getConditionTagAt(2).condition);
- assertTrue(mPanel.getConditionTagAt(2).rb.isChecked());
-
- assertEquals(Settings.Global.ZEN_MODE_NO_INTERRUPTIONS,
- mPanel.getSelectedZen(Settings.Global.ZEN_MODE_OFF));
- }
-}
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index 7539d88..01714cf 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -5173,6 +5173,18 @@
// OS: P
AUTOFILL_INVALID_PERMISSION = 1289;
+ // OPEN: QS Alarm tile shown
+ // ACTION: QS Alarm tile tapped
+ // SUBTYPE: 0 is off, 1 is on
+ // CATEGORY: QUICK_SETTINGS
+ // OS: P
+ QS_ALARM = 1290;
+
+ // OPEN: Settings->Connected Devices->USB->(click on details link)
+ // CATEGORY: SETTINGS
+ // OS: P
+ USB_DEVICE_DETAILS = 1291;
+
// ---- End P Constants, all P constants go above this line ----
// Add new aosp constants above this line.
// END OF AOSP CONSTANTS
diff --git a/proto/src/system_messages.proto b/proto/src/system_messages.proto
index db70184..08fdb97 100644
--- a/proto/src/system_messages.proto
+++ b/proto/src/system_messages.proto
@@ -200,6 +200,10 @@
// Package: android
NOTE_CARRIER_NETWORK_AVAILABLE = 46;
+ // Inform that USB is configured for Tethering
+ // Package: android
+ NOTE_USB_TETHER = 47;
+
// ADD_NEW_IDS_ABOVE_THIS_LINE
// Legacy IDs with arbitrary values appear below
// Legacy IDs existed as stable non-conflicting constants prior to the O release
diff --git a/proto/src/wifi.proto b/proto/src/wifi.proto
index f5349df..f6a54af 100644
--- a/proto/src/wifi.proto
+++ b/proto/src/wifi.proto
@@ -373,6 +373,9 @@
// Wps connection metrics
optional WpsMetrics wps_metrics = 91;
+
+ // Wifi power statistics
+ optional WifiPowerStats wifi_power_stats = 92;
}
// Information that gets logged for every WiFi connection.
@@ -1134,3 +1137,22 @@
// Total number of wps cancellation
optional int32 num_wps_cancellation = 8;
}
+
+// Power stats for Wifi
+message WifiPowerStats {
+
+ // Duration of log (ms)
+ optional int64 logging_duration_ms = 1;
+
+ // Energy consumed by wifi (mAh)
+ optional double energy_consumed_mah = 2;
+
+ // Amount of time wifi is in idle (ms)
+ optional int64 idle_time_ms = 3;
+
+ // Amount of time wifi is in rx (ms)
+ optional int64 rx_time_ms = 4;
+
+ // Amount of time wifi is in tx (ms)
+ optional int64 tx_time_ms = 5;
+}
\ No newline at end of file
diff --git a/services/autofill/java/com/android/server/autofill/ui/FillUi.java b/services/autofill/java/com/android/server/autofill/ui/FillUi.java
index 5ee3cbf..5f112c7 100644
--- a/services/autofill/java/com/android/server/autofill/ui/FillUi.java
+++ b/services/autofill/java/com/android/server/autofill/ui/FillUi.java
@@ -27,6 +27,7 @@
import android.graphics.Point;
import android.graphics.Rect;
import android.service.autofill.Dataset;
+import android.service.autofill.Dataset.DatasetFieldFilter;
import android.service.autofill.FillResponse;
import android.text.TextUtils;
import android.util.Slog;
@@ -58,6 +59,7 @@
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
final class FillUi {
private static final String TAG = "FillUi";
@@ -185,7 +187,7 @@
final ArrayList<ViewItem> items = new ArrayList<>(totalItems);
if (header != null) {
if (sVerbose) Slog.v(TAG, "adding header");
- items.add(new ViewItem(null, null, null, header));
+ items.add(new ViewItem(null, null, false, null, header));
}
for (int i = 0; i < datasetCount; i++) {
final Dataset dataset = response.getDatasets().get(i);
@@ -205,21 +207,32 @@
Slog.e(TAG, "Error inflating remote views", e);
continue;
}
- final Pattern filter = dataset.getFilter(index);
+ final DatasetFieldFilter filter = dataset.getFilter(index);
+ Pattern filterPattern = null;
String valueText = null;
+ boolean filterable = true;
if (filter == null) {
final AutofillValue value = dataset.getFieldValues().get(index);
if (value != null && value.isText()) {
valueText = value.getTextValue().toString().toLowerCase();
}
+ } else {
+ filterPattern = filter.pattern;
+ if (filterPattern == null) {
+ if (sVerbose) {
+ Slog.v(TAG, "Explicitly disabling filter at id " + focusedViewId
+ + " for dataset #" + index);
+ }
+ filterable = false;
+ }
}
- items.add(new ViewItem(dataset, filter, valueText, view));
+ items.add(new ViewItem(dataset, filterPattern, filterable, valueText, view));
}
}
if (footer != null) {
if (sVerbose) Slog.v(TAG, "adding footer");
- items.add(new ViewItem(null, null, null, footer));
+ items.add(new ViewItem(null, null, false, null, footer));
}
mAdapter = new ItemsAdapter(items);
@@ -354,7 +367,7 @@
MeasureSpec.AT_MOST);
final int itemCount = mAdapter.getCount();
for (int i = 0; i < itemCount; i++) {
- View view = mAdapter.getItem(i).view;
+ final View view = mAdapter.getItem(i).view;
view.measure(widthMeasureSpec, heightMeasureSpec);
final int clampedMeasuredWidth = Math.min(view.getMeasuredWidth(), maxSize.x);
final int newContentWidth = Math.max(mContentWidth, clampedMeasuredWidth);
@@ -400,13 +413,62 @@
public final @Nullable Dataset dataset;
public final @NonNull View view;
public final @Nullable Pattern filter;
+ public final boolean filterable;
- ViewItem(@Nullable Dataset dataset, @Nullable Pattern filter, @Nullable String value,
- @NonNull View view) {
+ /**
+ * Default constructor.
+ *
+ * @param dataset dataset associated with the item or {@code null} if it's a header or
+ * footer (TODO(b/69796626): make @NonNull if header/footer is refactored out of the list)
+ * @param filter optional filter set by the service to determine how the item should be
+ * filtered
+ * @param filterable optional flag set by the service to indicate this item should not be
+ * filtered (typically used when the dataset has value but it's sensitive, like a password)
+ * @param value dataset value
+ * @param view dataset presentation.
+ */
+ ViewItem(@Nullable Dataset dataset, @Nullable Pattern filter, boolean filterable,
+ @Nullable String value, @NonNull View view) {
this.dataset = dataset;
this.value = value;
this.view = view;
this.filter = filter;
+ this.filterable = filterable;
+ }
+
+ /**
+ * Returns whether this item matches the value input by the user so it can be included
+ * in the filtered datasets.
+ */
+ public boolean matches(CharSequence filterText) {
+ if (TextUtils.isEmpty(filterText)) {
+ // Always show item when the user input is empty
+ return true;
+ }
+ if (!filterable) {
+ // Service explicitly disabled filtering using a null Pattern.
+ return false;
+ }
+ final String constraintLowerCase = filterText.toString().toLowerCase();
+ if (filter != null) {
+ // Uses pattern provided by service
+ return filter.matcher(constraintLowerCase).matches();
+ } else {
+ // Compares it with dataset value with dataset
+ return (value == null)
+ ? (dataset.getAuthentication() == null)
+ : value.toLowerCase().startsWith(constraintLowerCase);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "ViewItem: [dataset=" + (dataset == null ? "null" : dataset.getId())
+ + ", value=" + (value == null ? "null" : value.length() + "_chars")
+ + ", filterable=" + filterable
+ + ", filter=" + (filter == null ? "null" : filter.pattern().length() + "_chars")
+ + ", view=" + view.getAutofillId()
+ + "]";
}
}
@@ -509,7 +571,7 @@
public void dump(PrintWriter pw, String prefix) {
pw.print(prefix); pw.print("mCallback: "); pw.println(mCallback != null);
pw.print(prefix); pw.print("mListView: "); pw.println(mListView);
- pw.print(prefix); pw.print("mAdapter: "); pw.println(mAdapter != null);
+ pw.print(prefix); pw.print("mAdapter: "); pw.println(mAdapter);
pw.print(prefix); pw.print("mFilterText: ");
Helper.printlnRedactedText(pw, mFilterText);
pw.print(prefix); pw.print("mContentWidth: "); pw.println(mContentWidth);
@@ -556,33 +618,14 @@
public Filter getFilter() {
return new Filter() {
@Override
- protected FilterResults performFiltering(CharSequence constraint) {
+ protected FilterResults performFiltering(CharSequence filterText) {
// No locking needed as mAllItems is final an immutable
+ final List<ViewItem> filtered = mAllItems.stream()
+ .filter((item) -> item.matches(filterText))
+ .collect(Collectors.toList());
final FilterResults results = new FilterResults();
- if (TextUtils.isEmpty(constraint)) {
- results.values = mAllItems;
- results.count = mAllItems.size();
- return results;
- }
- final List<ViewItem> filteredItems = new ArrayList<>();
- final String constraintLowerCase = constraint.toString().toLowerCase();
- final int itemCount = mAllItems.size();
- for (int i = 0; i < itemCount; i++) {
- final ViewItem item = mAllItems.get(i);
- final boolean matches;
- if (item.filter != null) {
- matches = item.filter.matcher(constraintLowerCase).matches();
- } else {
- matches = (item.value == null)
- ? (item.dataset.getAuthentication() == null)
- : item.value.toLowerCase().startsWith(constraintLowerCase);
- }
- if (matches) {
- filteredItems.add(item);
- }
- }
- results.values = filteredItems;
- results.count = filteredItems.size();
+ results.values = filtered;
+ results.count = filtered.size();
return results;
}
@@ -624,6 +667,11 @@
public View getView(int position, View convertView, ViewGroup parent) {
return getItem(position).view;
}
+
+ @Override
+ public String toString() {
+ return "ItemsAdapter: [all=" + mAllItems + ", filtered=" + mFilteredItems + "]";
+ }
}
private final class AnnounceFilterResult implements Runnable {
diff --git a/services/core/java/com/android/server/EventLogTags.logtags b/services/core/java/com/android/server/EventLogTags.logtags
index 219facd..0502117 100644
--- a/services/core/java/com/android/server/EventLogTags.logtags
+++ b/services/core/java/com/android/server/EventLogTags.logtags
@@ -34,7 +34,7 @@
2731 power_soft_sleep_requested (savedwaketimems|2)
# Power save state has changed. See BatterySaverController.java for the details.
2739 battery_saver_mode (prevOffOrOn|1|5),(nowOffOrOn|1|5),(interactive|1|5),(features|3|5)
-27390 battery_saving_stats (batterySaver|1|5),(interactive|1|5),(doze|1|5),(delta_duration|2|3),(delta_battery_drain|1|6),(total_duration|2|3),(total_battery_drain|1|6)
+27390 battery_saving_stats (batterySaver|1|5),(interactive|1|5),(doze|1|5),(delta_duration|2|3),(delta_battery_drain|1|1),(delta_battery_drain_percent|1|6),(total_duration|2|3),(total_battery_drain|1|1),(total_battery_drain_percent|1|6)
#
# Leave IDs through 2740 for more power logs (2730 used by battery_discharge above)
diff --git a/services/core/java/com/android/server/IpSecService.java b/services/core/java/com/android/server/IpSecService.java
index fe4ac6d7..a07a982 100644
--- a/services/core/java/com/android/server/IpSecService.java
+++ b/services/core/java/com/android/server/IpSecService.java
@@ -87,6 +87,7 @@
private static final String NETD_SERVICE_NAME = "netd";
private static final int[] DIRECTIONS =
new int[] {IpSecManager.DIRECTION_OUT, IpSecManager.DIRECTION_IN};
+ private static final String[] WILDCARD_ADDRESSES = new String[]{"0.0.0.0", "::"};
private static final int NETD_FETCH_TIMEOUT_MS = 5000; // ms
private static final int MAX_PORT_BIND_ATTEMPTS = 10;
@@ -413,12 +414,16 @@
.append(mTransformQuotaTracker)
.append(", mSocketQuotaTracker=")
.append(mSocketQuotaTracker)
+ .append(", mTunnelQuotaTracker=")
+ .append(mTunnelQuotaTracker)
.append(", mSpiRecords=")
.append(mSpiRecords)
.append(", mTransformRecords=")
.append(mTransformRecords)
.append(", mEncapSocketRecords=")
.append(mEncapSocketRecords)
+ .append(", mTunnelInterfaceRecords=")
+ .append(mTunnelInterfaceRecords)
.append("}")
.toString();
}
@@ -815,12 +820,14 @@
try {
mSrvConfig.getNetdInstance().removeVirtualTunnelInterface(mInterfaceName);
- for (int direction : DIRECTIONS) {
- int mark = (direction == IpSecManager.DIRECTION_IN) ? mIkey : mOkey;
- mSrvConfig
- .getNetdInstance()
- .ipSecDeleteSecurityPolicy(
- 0, direction, mLocalAddress, mRemoteAddress, mark, 0xffffffff);
+ for(String wildcardAddr : WILDCARD_ADDRESSES) {
+ for (int direction : DIRECTIONS) {
+ int mark = (direction == IpSecManager.DIRECTION_IN) ? mIkey : mOkey;
+ mSrvConfig
+ .getNetdInstance()
+ .ipSecDeleteSecurityPolicy(
+ 0, direction, wildcardAddr, wildcardAddr, mark, 0xffffffff);
+ }
}
} catch (ServiceSpecificException e) {
// FIXME: get the error code and throw is at an IOException from Errno Exception
@@ -1261,19 +1268,21 @@
.getNetdInstance()
.addVirtualTunnelInterface(intfName, localAddr, remoteAddr, ikey, okey);
- for (int direction : DIRECTIONS) {
- int mark = (direction == IpSecManager.DIRECTION_OUT) ? okey : ikey;
+ for(String wildcardAddr : WILDCARD_ADDRESSES) {
+ for (int direction : DIRECTIONS) {
+ int mark = (direction == IpSecManager.DIRECTION_OUT) ? okey : ikey;
- mSrvConfig
- .getNetdInstance()
- .ipSecAddSecurityPolicy(
+ mSrvConfig
+ .getNetdInstance()
+ .ipSecAddSecurityPolicy(
0, // Use 0 for reqId
direction,
- "",
- "",
+ wildcardAddr,
+ wildcardAddr,
0,
mark,
0xffffffff);
+ }
}
userRecord.mTunnelInterfaceRecords.put(
@@ -1646,16 +1655,18 @@
c.setNetwork(tunnelInterfaceInfo.getUnderlyingNetwork());
// If outbound, also add SPI to the policy.
- mSrvConfig
- .getNetdInstance()
- .ipSecUpdateSecurityPolicy(
- 0, // Use 0 for reqId
- direction,
- "",
- "",
- transformInfo.getSpiRecord().getSpi(),
- mark,
- 0xffffffff);
+ for(String wildcardAddr : WILDCARD_ADDRESSES) {
+ mSrvConfig
+ .getNetdInstance()
+ .ipSecUpdateSecurityPolicy(
+ 0, // Use 0 for reqId
+ direction,
+ wildcardAddr,
+ wildcardAddr,
+ transformInfo.getSpiRecord().getSpi(),
+ mark,
+ 0xffffffff);
+ }
}
// Update SA with tunnel mark (ikey or okey based on direction)
diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java
index 1dd92f3..65e90bad 100644
--- a/services/core/java/com/android/server/LocationManagerService.java
+++ b/services/core/java/com/android/server/LocationManagerService.java
@@ -1397,23 +1397,6 @@
}
/**
- * Returns "true" if access to the specified location provider is allowed by the specified
- * user's settings. Access to all location providers is forbidden to non-location-provider
- * processes belonging to background users.
- *
- * @param provider the name of the location provider
- * @param uid the requestor's UID
- * @param userId the user id to query
- */
- private boolean isAllowedByUserSettingsLockedForUser(
- String provider, int uid, int userId) {
- if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
- return false;
- }
- return isLocationProviderEnabledForUser(provider, userId);
- }
-
- /**
* Returns the permission string associated with the specified resolution level.
*
* @param resolutionLevel the resolution level
@@ -2585,143 +2568,6 @@
}
/**
- * Method for enabling or disabling location.
- *
- * @param enabled true to enable location. false to disable location
- * @param userId the user id to set
- */
- @Override
- public void setLocationEnabledForUser(boolean enabled, int userId) {
- // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
- checkInteractAcrossUsersPermission(userId);
-
- // Enable or disable all location providers. Fused provider and passive provider are
- // excluded.
- synchronized (mLock) {
- for(String provider : getAllProvidersForLocationSettings()) {
- setProviderEnabledForUser(provider, enabled, userId);
- }
- }
- }
-
- /**
- * Returns the current enabled/disabled status of location
- *
- * @param userId the user id to query
- * @return true if location is enabled. false if location is disabled.
- */
- @Override
- public boolean isLocationEnabledForUser(int userId) {
- // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
- checkInteractAcrossUsersPermission(userId);
-
- // If at least one location provider is enabled, return true. Fused provider and passive
- // provider are excluded.
- synchronized (mLock) {
- for (String provider : getAllProvidersForLocationSettings()) {
- if (isProviderEnabledForUser(provider, userId)) {
- return true;
- }
- }
- return false;
- }
- }
-
- @Override
- public boolean isProviderEnabled(String provider) {
- return isProviderEnabledForUser(provider, UserHandle.getCallingUserId());
- }
-
- /**
- * Method for determining if a location provider is enabled.
- *
- * @param provider the location provider to query
- * @param userId the user id to query
- * @return true if the provider is enabled
- */
- @Override
- public boolean isProviderEnabledForUser(String provider, int userId) {
- // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
- checkInteractAcrossUsersPermission(userId);
-
- // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
- // so we discourage its use
- if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
-
- int uid = Binder.getCallingUid();
- long identity = Binder.clearCallingIdentity();
- try {
- synchronized (mLock) {
- LocationProviderInterface p = mProvidersByName.get(provider);
- return p != null
- && isAllowedByUserSettingsLockedForUser(provider, uid, userId);
- }
- } finally {
- Binder.restoreCallingIdentity(identity);
- }
- }
-
- /**
- * Method for enabling or disabling a single location provider.
- *
- * @param provider the name of the provider
- * @param enabled true to enable the provider. false to disable the provider
- * @param userId the user id to set
- * @return true if the value was set successfully. false on failure.
- */
- @Override
- public boolean setProviderEnabledForUser(
- String provider, boolean enabled, int userId) {
- mContext.enforceCallingPermission(
- android.Manifest.permission.WRITE_SECURE_SETTINGS,
- "Requires WRITE_SECURE_SETTINGS permission");
-
- // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
- checkInteractAcrossUsersPermission(userId);
-
- final long identity = Binder.clearCallingIdentity();
- try {
- synchronized (mLock) {
- // to ensure thread safety, we write the provider name with a '+' or '-'
- // and let the SettingsProvider handle it rather than reading and modifying
- // the list of enabled providers.
- if (enabled) {
- provider = "+" + provider;
- } else {
- provider = "-" + provider;
- }
- return Settings.Secure.putStringForUser(
- mContext.getContentResolver(),
- Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
- provider,
- userId);
- }
- } finally {
- Binder.restoreCallingIdentity(identity);
- }
- }
-
- /**
- * Return all location providers except fused provider and passive provider. These two
- * providers are not generating location by themselves, but only echo locations from other
- * providers.
- *
- * @return All location providers except fused provider and passive provider, including
- * providers that are not permitted to be accessed by the calling activity or are
- * currently disabled.
- */
- private List<String> getAllProvidersForLocationSettings() {
- List<String> providersForSettings = new ArrayList<>(mProviders.size());
- for (String provider : getAllProviders()) {
- if (provider.equals(LocationManager.PASSIVE_PROVIDER)) {
- continue;
- }
- providersForSettings.add(provider);
- }
- return providersForSettings;
- }
-
- /**
* Read location provider status from Settings.Secure
*
* @param provider the location provider to query
@@ -2742,23 +2588,6 @@
}
/**
- * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
- * current user id
- *
- * @param userId the user id to get or set value
- */
- private void checkInteractAcrossUsersPermission(int userId) {
- int uid = Binder.getCallingUid();
- if (UserHandle.getUserId(uid) != userId) {
- if (ActivityManager.checkComponentPermission(
- android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
- != PERMISSION_GRANTED) {
- throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
- }
- }
- }
-
- /**
* Returns "true" if the UID belongs to a bound location provider.
*
* @param uid the uid
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 5b8b691..ea53dfc 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -4331,7 +4331,9 @@
final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
StatsLog.write(StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED,
component.userId, component.realActivity.getPackageName(),
- component.realActivity.getShortClassName(), resumed ? 1 : 0);
+ component.realActivity.getShortClassName(), resumed ?
+ StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__ACTIVITY__MOVE_TO_FOREGROUND :
+ StatsLog.ACTIVITY_FOREGROUND_STATE_CHANGED__ACTIVITY__MOVE_TO_BACKGROUND);
if (resumed) {
if (mUsageStatsService != null) {
mUsageStatsService.reportEvent(component.realActivity, component.userId,
@@ -12844,7 +12846,8 @@
}
// TODO: Where should the corresponding '1' (start) write go?
- StatsLog.write(StatsLog.DEVICE_ON_STATUS_CHANGED, 0);
+ StatsLog.write(StatsLog.DEVICE_ON_STATUS_CHANGED,
+ StatsLog.DEVICE_ON_STATUS_CHANGED__STATE__OFF);
boolean timedout = false;
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 6beafcb..bf38825 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -1251,10 +1251,14 @@
synchronized (mService) {
try {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "resolveIntent");
+ int modifiedFlags = flags
+ | PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS;
+ if (intent.isBrowsableWebIntent()
+ || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) {
+ modifiedFlags |= PackageManager.MATCH_INSTANT;
+ }
return mService.getPackageManagerInternalLocked().resolveIntent(
- intent, resolvedType, PackageManager.MATCH_INSTANT
- | PackageManager.MATCH_DEFAULT_ONLY | flags
- | ActivityManagerService.STOCK_PM_FLAGS, userId, true);
+ intent, resolvedType, modifiedFlags, userId, true);
} finally {
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/am/ActivityStarter.java
index 8fd754a..eab88aa 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/am/ActivityStarter.java
@@ -31,6 +31,7 @@
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
+import static android.content.Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK;
import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT;
@@ -789,7 +790,7 @@
// Instead, launch the ephemeral installer. Once the installer is finished, it
// starts either the intent we resolved here [on install error] or the ephemeral
// app [on install success].
- if (rInfo != null && rInfo.auxiliaryInfo != null) {
+ if (rInfo != null && rInfo.isInstantAppAvailable) {
intent = createLaunchIntent(rInfo.auxiliaryInfo, ephemeralIntent,
callingPackage, verificationBundle, resolvedType, userId);
resolvedType = null;
@@ -849,22 +850,27 @@
/**
* Creates a launch intent for the given auxiliary resolution data.
*/
- private @NonNull Intent createLaunchIntent(@NonNull AuxiliaryResolveInfo auxiliaryResponse,
+ private @NonNull Intent createLaunchIntent(@Nullable AuxiliaryResolveInfo auxiliaryResponse,
Intent originalIntent, String callingPackage, Bundle verificationBundle,
String resolvedType, int userId) {
- if (auxiliaryResponse.needsPhaseTwo) {
+ if (auxiliaryResponse != null && auxiliaryResponse.needsPhaseTwo) {
// request phase two resolution
mService.getPackageManagerInternalLocked().requestInstantAppResolutionPhaseTwo(
auxiliaryResponse, originalIntent, resolvedType, callingPackage,
verificationBundle, userId);
}
return InstantAppResolver.buildEphemeralInstallerIntent(
- Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE, originalIntent,
- auxiliaryResponse.failureIntent, callingPackage, verificationBundle,
- resolvedType, userId, auxiliaryResponse.packageName, auxiliaryResponse.splitName,
- auxiliaryResponse.installFailureActivity, auxiliaryResponse.versionCode,
- auxiliaryResponse.token, auxiliaryResponse.resolveInfo.getExtras(),
- auxiliaryResponse.needsPhaseTwo);
+ originalIntent,
+ InstantAppResolver.sanitizeIntent(originalIntent),
+ auxiliaryResponse == null ? null : auxiliaryResponse.failureIntent,
+ callingPackage,
+ verificationBundle,
+ resolvedType,
+ userId,
+ auxiliaryResponse == null ? null : auxiliaryResponse.installFailureActivity,
+ auxiliaryResponse == null ? null : auxiliaryResponse.token,
+ auxiliaryResponse != null && auxiliaryResponse.needsPhaseTwo,
+ auxiliaryResponse == null ? null : auxiliaryResponse.filters);
}
void postStartActivityProcessing(ActivityRecord r, int result, ActivityStack targetStack) {
@@ -924,12 +930,12 @@
// Don't modify the client's object!
intent = new Intent(intent);
if (componentSpecified
- && intent.getData() != null
- && Intent.ACTION_VIEW.equals(intent.getAction())
+ && !Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE.equals(intent.getAction())
+ && !Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE.equals(intent.getAction())
&& mService.getPackageManagerInternalLocked()
.isInstantAppInstallerComponent(intent.getComponent())) {
// intercept intents targeted directly to the ephemeral installer the
- // ephemeral installer should never be started with a raw URL; instead
+ // ephemeral installer should never be started with a raw Intent; instead
// adjust the intent so it looks like a "normal" instant app launch
intent.setComponent(null /*component*/);
componentSpecified = false;
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 0d96468..ea52782 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -325,39 +325,38 @@
void noteProcessStart(String name, int uid) {
synchronized (mStats) {
mStats.noteProcessStartLocked(name, uid);
- // TODO: decide where this should be and use a constant instead of a literal.
- StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name, 1);
+ StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name,
+ StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED__EVENT__PROCESS_STARTED);
}
}
void noteProcessCrash(String name, int uid) {
synchronized (mStats) {
mStats.noteProcessCrashLocked(name, uid);
- // TODO: decide where this should be and use a constant instead of a literal.
- StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name, 2);
+ StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name,
+ StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED__EVENT__PROCESS_CRASHED);
}
}
void noteProcessAnr(String name, int uid) {
synchronized (mStats) {
mStats.noteProcessAnrLocked(name, uid);
- // TODO: decide where this should be and use a constant instead of a literal.
- StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name, 3);
+ StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name,
+ StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED__EVENT__PROCESS_ANRED);
}
}
void noteProcessFinish(String name, int uid) {
synchronized (mStats) {
mStats.noteProcessFinishLocked(name, uid);
- // TODO: decide where this should be and use a constant instead of a literal.
- StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name, 0);
+ StatsLog.write(StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED, uid, name,
+ StatsLog.PROCESS_LIFE_CYCLE_STATE_CHANGED__EVENT__PROCESS_FINISHED);
}
}
/** @param state Process state from ActivityManager.java. */
void noteUidProcessState(int uid, int state) {
synchronized (mStats) {
- // TODO: remove this once we figure out properly where and how
StatsLog.write(StatsLog.UID_PROCESS_STATE_CHANGED, uid,
ActivityManager.processStateAmToProto(state));
@@ -603,7 +602,6 @@
enforceCallingPermission();
if (DBG) Slog.d(TAG, "begin noteScreenState");
synchronized (mStats) {
- // TODO: remove this once we figure out properly where and how
StatsLog.write(StatsLog.SCREEN_STATE_CHANGED, state);
mStats.noteScreenStateLocked(state);
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index be6c4a1..9a9cdbd 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -1095,7 +1095,8 @@
if (VDBG) Log.d(TAG, "setUsbTethering(" + enable + ")");
UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
synchronized (mPublicSync) {
- usbManager.setCurrentFunction(enable ? UsbManager.USB_FUNCTION_RNDIS : null, false);
+ usbManager.setCurrentFunctions(enable ? UsbManager.FUNCTION_RNDIS
+ : UsbManager.FUNCTION_NONE);
}
return ConnectivityManager.TETHER_ERROR_NO_ERROR;
}
diff --git a/services/core/java/com/android/server/display/AmbientBrightnessStatsTracker.java b/services/core/java/com/android/server/display/AmbientBrightnessStatsTracker.java
new file mode 100644
index 0000000..6e571bd
--- /dev/null
+++ b/services/core/java/com/android/server/display/AmbientBrightnessStatsTracker.java
@@ -0,0 +1,363 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.display;
+
+import android.annotation.Nullable;
+import android.annotation.UserIdInt;
+import android.hardware.display.AmbientBrightnessDayStats;
+import android.os.SystemClock;
+import android.os.UserManager;
+import android.util.Slog;
+import android.util.Xml;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.FastXmlSerializer;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDate;
+import java.time.format.DateTimeParseException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Class that stores stats of ambient brightness regions as histogram.
+ */
+public class AmbientBrightnessStatsTracker {
+
+ private static final String TAG = "AmbientBrightnessStatsTracker";
+ private static final boolean DEBUG = false;
+
+ @VisibleForTesting
+ static final float[] BUCKET_BOUNDARIES_FOR_NEW_STATS =
+ {0, 0.1f, 0.3f, 1, 3, 10, 30, 100, 300, 1000, 3000, 10000};
+ @VisibleForTesting
+ static final int MAX_DAYS_TO_TRACK = 7;
+
+ private final AmbientBrightnessStats mAmbientBrightnessStats;
+ private final Timer mTimer;
+ private final Injector mInjector;
+ private final UserManager mUserManager;
+ private float mCurrentAmbientBrightness;
+ private @UserIdInt int mCurrentUserId;
+
+ public AmbientBrightnessStatsTracker(UserManager userManager, @Nullable Injector injector) {
+ mUserManager = userManager;
+ if (injector != null) {
+ mInjector = injector;
+ } else {
+ mInjector = new Injector();
+ }
+ mAmbientBrightnessStats = new AmbientBrightnessStats();
+ mTimer = new Timer(() -> mInjector.elapsedRealtimeMillis());
+ mCurrentAmbientBrightness = -1;
+ }
+
+ public synchronized void start() {
+ mTimer.reset();
+ mTimer.start();
+ }
+
+ public synchronized void stop() {
+ if (mTimer.isRunning()) {
+ mAmbientBrightnessStats.log(mCurrentUserId, mInjector.getLocalDate(),
+ mCurrentAmbientBrightness, mTimer.totalDurationSec());
+ }
+ mTimer.reset();
+ mCurrentAmbientBrightness = -1;
+ }
+
+ public synchronized void add(@UserIdInt int userId, float newAmbientBrightness) {
+ if (mTimer.isRunning()) {
+ if (userId == mCurrentUserId) {
+ mAmbientBrightnessStats.log(mCurrentUserId, mInjector.getLocalDate(),
+ mCurrentAmbientBrightness, mTimer.totalDurationSec());
+ } else {
+ if (DEBUG) {
+ Slog.v(TAG, "User switched since last sensor event.");
+ }
+ mCurrentUserId = userId;
+ }
+ mTimer.reset();
+ mTimer.start();
+ mCurrentAmbientBrightness = newAmbientBrightness;
+ } else {
+ if (DEBUG) {
+ Slog.e(TAG, "Timer not running while trying to add brightness stats.");
+ }
+ }
+ }
+
+ public synchronized void writeStats(OutputStream stream) throws IOException {
+ mAmbientBrightnessStats.writeToXML(stream);
+ }
+
+ public synchronized void readStats(InputStream stream) throws IOException {
+ mAmbientBrightnessStats.readFromXML(stream);
+ }
+
+ public synchronized ArrayList<AmbientBrightnessDayStats> getUserStats(int userId) {
+ return mAmbientBrightnessStats.getUserStats(userId);
+ }
+
+ public synchronized void dump(PrintWriter pw) {
+ pw.println("AmbientBrightnessStats:");
+ pw.print(mAmbientBrightnessStats);
+ }
+
+ /**
+ * AmbientBrightnessStats tracks ambient brightness stats across users over multiple days.
+ * This class is not ThreadSafe.
+ */
+ class AmbientBrightnessStats {
+
+ private static final String TAG_AMBIENT_BRIGHTNESS_STATS = "ambient-brightness-stats";
+ private static final String TAG_AMBIENT_BRIGHTNESS_DAY_STATS =
+ "ambient-brightness-day-stats";
+ private static final String ATTR_USER = "user";
+ private static final String ATTR_LOCAL_DATE = "local-date";
+ private static final String ATTR_BUCKET_BOUNDARIES = "bucket-boundaries";
+ private static final String ATTR_BUCKET_STATS = "bucket-stats";
+
+ private Map<Integer, Deque<AmbientBrightnessDayStats>> mStats;
+
+ public AmbientBrightnessStats() {
+ mStats = new HashMap<>();
+ }
+
+ public void log(@UserIdInt int userId, LocalDate localDate, float ambientBrightness,
+ float durationSec) {
+ Deque<AmbientBrightnessDayStats> userStats = getOrCreateUserStats(mStats, userId);
+ AmbientBrightnessDayStats dayStats = getOrCreateDayStats(userStats, localDate);
+ dayStats.log(ambientBrightness, durationSec);
+ }
+
+ public ArrayList<AmbientBrightnessDayStats> getUserStats(@UserIdInt int userId) {
+ if (mStats.containsKey(userId)) {
+ return new ArrayList<>(mStats.get(userId));
+ } else {
+ return null;
+ }
+ }
+
+ public void writeToXML(OutputStream stream) throws IOException {
+ XmlSerializer out = new FastXmlSerializer();
+ out.setOutput(stream, StandardCharsets.UTF_8.name());
+ out.startDocument(null, true);
+ out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
+
+ final LocalDate cutOffDate = mInjector.getLocalDate().minusDays(MAX_DAYS_TO_TRACK);
+ out.startTag(null, TAG_AMBIENT_BRIGHTNESS_STATS);
+ for (Map.Entry<Integer, Deque<AmbientBrightnessDayStats>> entry : mStats.entrySet()) {
+ for (AmbientBrightnessDayStats userDayStats : entry.getValue()) {
+ int userSerialNumber = mInjector.getUserSerialNumber(mUserManager,
+ entry.getKey());
+ if (userSerialNumber != -1 && userDayStats.getLocalDate().isAfter(cutOffDate)) {
+ out.startTag(null, TAG_AMBIENT_BRIGHTNESS_DAY_STATS);
+ out.attribute(null, ATTR_USER, Integer.toString(userSerialNumber));
+ out.attribute(null, ATTR_LOCAL_DATE,
+ userDayStats.getLocalDate().toString());
+ StringBuilder bucketBoundariesValues = new StringBuilder();
+ StringBuilder timeSpentValues = new StringBuilder();
+ for (int i = 0; i < userDayStats.getBucketBoundaries().length; i++) {
+ if (i > 0) {
+ bucketBoundariesValues.append(",");
+ timeSpentValues.append(",");
+ }
+ bucketBoundariesValues.append(userDayStats.getBucketBoundaries()[i]);
+ timeSpentValues.append(userDayStats.getStats()[i]);
+ }
+ out.attribute(null, ATTR_BUCKET_BOUNDARIES,
+ bucketBoundariesValues.toString());
+ out.attribute(null, ATTR_BUCKET_STATS, timeSpentValues.toString());
+ out.endTag(null, TAG_AMBIENT_BRIGHTNESS_DAY_STATS);
+ }
+ }
+ }
+ out.endTag(null, TAG_AMBIENT_BRIGHTNESS_STATS);
+ out.endDocument();
+ stream.flush();
+ }
+
+ public void readFromXML(InputStream stream) throws IOException {
+ try {
+ Map<Integer, Deque<AmbientBrightnessDayStats>> parsedStats = new HashMap<>();
+ XmlPullParser parser = Xml.newPullParser();
+ parser.setInput(stream, StandardCharsets.UTF_8.name());
+
+ int type;
+ while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
+ && type != XmlPullParser.START_TAG) {
+ }
+ String tag = parser.getName();
+ if (!TAG_AMBIENT_BRIGHTNESS_STATS.equals(tag)) {
+ throw new XmlPullParserException(
+ "Ambient brightness stats not found in tracker file " + tag);
+ }
+
+ final LocalDate cutOffDate = mInjector.getLocalDate().minusDays(MAX_DAYS_TO_TRACK);
+ parser.next();
+ int outerDepth = parser.getDepth();
+ while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
+ && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
+ if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
+ continue;
+ }
+ tag = parser.getName();
+ if (TAG_AMBIENT_BRIGHTNESS_DAY_STATS.equals(tag)) {
+ String userSerialNumber = parser.getAttributeValue(null, ATTR_USER);
+ LocalDate localDate = LocalDate.parse(
+ parser.getAttributeValue(null, ATTR_LOCAL_DATE));
+ String[] bucketBoundaries = parser.getAttributeValue(null,
+ ATTR_BUCKET_BOUNDARIES).split(",");
+ String[] bucketStats = parser.getAttributeValue(null,
+ ATTR_BUCKET_STATS).split(",");
+ if (bucketBoundaries.length != bucketStats.length
+ || bucketBoundaries.length < 1) {
+ throw new IOException("Invalid brightness stats string.");
+ }
+ float[] parsedBucketBoundaries = new float[bucketBoundaries.length];
+ float[] parsedBucketStats = new float[bucketStats.length];
+ for (int i = 0; i < bucketBoundaries.length; i++) {
+ parsedBucketBoundaries[i] = Float.parseFloat(bucketBoundaries[i]);
+ parsedBucketStats[i] = Float.parseFloat(bucketStats[i]);
+ }
+ int userId = mInjector.getUserId(mUserManager,
+ Integer.parseInt(userSerialNumber));
+ if (userId != -1 && localDate.isAfter(cutOffDate)) {
+ Deque<AmbientBrightnessDayStats> userStats = getOrCreateUserStats(
+ parsedStats, userId);
+ userStats.offer(
+ new AmbientBrightnessDayStats(localDate,
+ parsedBucketBoundaries, parsedBucketStats));
+ }
+ }
+ }
+ mStats = parsedStats;
+ } catch (NullPointerException | NumberFormatException | XmlPullParserException |
+ DateTimeParseException | IOException e) {
+ throw new IOException("Failed to parse brightness stats file.", e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ for (Map.Entry<Integer, Deque<AmbientBrightnessDayStats>> entry : mStats.entrySet()) {
+ for (AmbientBrightnessDayStats dayStats : entry.getValue()) {
+ builder.append(" ");
+ builder.append(entry.getKey()).append(" ");
+ builder.append(dayStats).append("\n");
+ }
+ }
+ return builder.toString();
+ }
+
+ private Deque<AmbientBrightnessDayStats> getOrCreateUserStats(
+ Map<Integer, Deque<AmbientBrightnessDayStats>> stats, @UserIdInt int userId) {
+ if (!stats.containsKey(userId)) {
+ stats.put(userId, new ArrayDeque<>());
+ }
+ return stats.get(userId);
+ }
+
+ private AmbientBrightnessDayStats getOrCreateDayStats(
+ Deque<AmbientBrightnessDayStats> userStats, LocalDate localDate) {
+ AmbientBrightnessDayStats lastBrightnessStats = userStats.peekLast();
+ if (lastBrightnessStats != null && lastBrightnessStats.getLocalDate().equals(
+ localDate)) {
+ return lastBrightnessStats;
+ } else {
+ AmbientBrightnessDayStats dayStats = new AmbientBrightnessDayStats(localDate,
+ BUCKET_BOUNDARIES_FOR_NEW_STATS);
+ if (userStats.size() == MAX_DAYS_TO_TRACK) {
+ userStats.poll();
+ }
+ userStats.offer(dayStats);
+ return dayStats;
+ }
+ }
+ }
+
+ @VisibleForTesting
+ interface Clock {
+ long elapsedTimeMillis();
+ }
+
+ @VisibleForTesting
+ static class Timer {
+
+ private final Clock clock;
+ private long startTimeMillis;
+ private boolean started;
+
+ public Timer(Clock clock) {
+ this.clock = clock;
+ }
+
+ public void reset() {
+ started = false;
+ }
+
+ public void start() {
+ if (!started) {
+ startTimeMillis = clock.elapsedTimeMillis();
+ started = true;
+ }
+ }
+
+ public boolean isRunning() {
+ return started;
+ }
+
+ public float totalDurationSec() {
+ if (started) {
+ return (float) ((clock.elapsedTimeMillis() - startTimeMillis) / 1000.0);
+ }
+ return 0;
+ }
+ }
+
+ @VisibleForTesting
+ static class Injector {
+ public long elapsedRealtimeMillis() {
+ return SystemClock.elapsedRealtime();
+ }
+
+ public int getUserSerialNumber(UserManager userManager, int userId) {
+ return userManager.getUserSerialNumber(userId);
+ }
+
+ public int getUserId(UserManager userManager, int userSerialNumber) {
+ return userManager.getUserHandle(userSerialNumber);
+ }
+
+ public LocalDate getLocalDate() {
+ return LocalDate.now();
+ }
+ }
+}
\ No newline at end of file
diff --git a/services/core/java/com/android/server/display/AutomaticBrightnessController.java b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
index 6a88b1e..e2aee88 100644
--- a/services/core/java/com/android/server/display/AutomaticBrightnessController.java
+++ b/services/core/java/com/android/server/display/AutomaticBrightnessController.java
@@ -269,6 +269,14 @@
}
}
+ public boolean hasUserDataPoints() {
+ return mBrightnessMapper.hasUserDataPoints();
+ }
+
+ public boolean isDefaultConfig() {
+ return mBrightnessMapper.isDefaultConfig();
+ }
+
private boolean setDisplayPolicy(int policy) {
if (mDisplayPolicy == policy) {
return false;
diff --git a/services/core/java/com/android/server/display/BrightnessIdleJob.java b/services/core/java/com/android/server/display/BrightnessIdleJob.java
index 876acf4..b0a41cb 100644
--- a/services/core/java/com/android/server/display/BrightnessIdleJob.java
+++ b/services/core/java/com/android/server/display/BrightnessIdleJob.java
@@ -70,7 +70,7 @@
Slog.d(BrightnessTracker.TAG, "Scheduled write of brightness events");
}
DisplayManagerInternal dmi = LocalServices.getService(DisplayManagerInternal.class);
- dmi.persistBrightnessSliderEvents();
+ dmi.persistBrightnessTrackerState();
return false;
}
diff --git a/services/core/java/com/android/server/display/BrightnessMappingStrategy.java b/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
index 001d4d9..c0d2599 100644
--- a/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
+++ b/services/core/java/com/android/server/display/BrightnessMappingStrategy.java
@@ -200,6 +200,12 @@
*/
public abstract void clearUserDataPoints();
+ /** @return true if there are any short term adjustments applied to the curve */
+ public abstract boolean hasUserDataPoints();
+
+ /** @return true if the current brightness config is the default one */
+ public abstract boolean isDefaultConfig();
+
public abstract void dump(PrintWriter pw);
private static float normalizeAbsoluteBrightness(int brightness) {
@@ -390,6 +396,16 @@
}
@Override
+ public boolean hasUserDataPoints() {
+ return mUserLux != -1;
+ }
+
+ @Override
+ public boolean isDefaultConfig() {
+ return true;
+ }
+
+ @Override
public void dump(PrintWriter pw) {
pw.println("SimpleMappingStrategy");
pw.println(" mSpline=" + mSpline);
@@ -507,6 +523,16 @@
}
@Override
+ public boolean hasUserDataPoints() {
+ return mUserLux != -1;
+ }
+
+ @Override
+ public boolean isDefaultConfig() {
+ return mDefaultConfig.equals(mConfig);
+ }
+
+ @Override
public void dump(PrintWriter pw) {
pw.println("PhysicalMappingStrategy");
pw.println(" mConfig=" + mConfig);
diff --git a/services/core/java/com/android/server/display/BrightnessTracker.java b/services/core/java/com/android/server/display/BrightnessTracker.java
index bcf8bfe..6b4666a 100644
--- a/services/core/java/com/android/server/display/BrightnessTracker.java
+++ b/services/core/java/com/android/server/display/BrightnessTracker.java
@@ -17,6 +17,7 @@
package com.android.server.display;
import android.annotation.Nullable;
+import android.annotation.UserIdInt;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
@@ -28,8 +29,8 @@
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
+import android.hardware.display.AmbientBrightnessDayStats;
import android.hardware.display.BrightnessChangeEvent;
-import android.net.Uri;
import android.os.BatteryManager;
import android.os.Environment;
import android.os.Handler;
@@ -81,6 +82,7 @@
static final boolean DEBUG = false;
private static final String EVENTS_FILE = "brightness_events.xml";
+ private static final String AMBIENT_BRIGHTNESS_STATS_FILE = "ambient_brightness_stats.xml";
private static final int MAX_EVENTS = 100;
// Discard events when reading or writing that are older than this.
private static final long MAX_EVENT_AGE = TimeUnit.DAYS.toMillis(30);
@@ -99,6 +101,9 @@
private static final String ATTR_NIGHT_MODE = "nightMode";
private static final String ATTR_COLOR_TEMPERATURE = "colorTemperature";
private static final String ATTR_LAST_NITS = "lastNits";
+ private static final String ATTR_DEFAULT_CONFIG = "defaultConfig";
+ private static final String ATTR_POWER_SAVE = "powerSaveFactor";
+ private static final String ATTR_USER_POINT = "userPoint";
private static final int MSG_BACKGROUND_START = 0;
private static final int MSG_BRIGHTNESS_CHANGED = 1;
@@ -113,6 +118,10 @@
private final Runnable mEventsWriter = () -> writeEvents();
private volatile boolean mWriteEventsScheduled;
+ private AmbientBrightnessStatsTracker mAmbientBrightnessStatsTracker;
+ private final Runnable mAmbientBrightnessStatsWriter = () -> writeAmbientBrightnessStats();
+ private volatile boolean mWriteBrightnessStatsScheduled;
+
private UserManager mUserManager;
private final Context mContext;
private final ContentResolver mContentResolver;
@@ -120,6 +129,7 @@
// mBroadcastReceiver and mSensorListener should only be used on the mBgHandler thread.
private BroadcastReceiver mBroadcastReceiver;
private SensorListener mSensorListener;
+ private @UserIdInt int mCurrentUserId = UserHandle.USER_NULL;
// Lock held while collecting data related to brightness changes.
private final Object mDataCollectionLock = new Object();
@@ -157,12 +167,19 @@
}
mBgHandler = new TrackerHandler(mInjector.getBackgroundHandler().getLooper());
mUserManager = mContext.getSystemService(UserManager.class);
-
+ try {
+ final ActivityManager.StackInfo focusedStack = mInjector.getFocusedStack();
+ mCurrentUserId = focusedStack.userId;
+ } catch (RemoteException e) {
+ // Really shouldn't be possible.
+ return;
+ }
mBgHandler.obtainMessage(MSG_BACKGROUND_START, (Float) initialBrightness).sendToTarget();
}
private void backgroundStart(float initialBrightness) {
readEvents();
+ readAmbientBrightnessStats();
mSensorListener = new SensorListener();
@@ -196,12 +213,20 @@
mInjector.unregisterSensorListener(mContext, mSensorListener);
mInjector.unregisterReceiver(mContext, mBroadcastReceiver);
mInjector.cancelIdleJob(mContext);
+ mAmbientBrightnessStatsTracker.stop();
synchronized (mDataCollectionLock) {
mStarted = false;
}
}
+ public void onSwitchUser(@UserIdInt int newUserId) {
+ if (DEBUG) {
+ Slog.d(TAG, "Used id updated from " + mCurrentUserId + " to " + newUserId);
+ }
+ mCurrentUserId = newUserId;
+ }
+
/**
* @param userId userId to fetch data for.
* @param includePackage if false we will null out BrightnessChangeEvent.packageName
@@ -228,24 +253,29 @@
return new ParceledListSlice<>(out);
}
- public void persistEvents() {
- scheduleWriteEvents();
+ public void persistBrightnessTrackerState() {
+ scheduleWriteBrightnessTrackerState();
}
/**
* Notify the BrightnessTracker that the user has changed the brightness of the display.
*/
- public void notifyBrightnessChanged(float brightness, boolean userInitiated) {
+ public void notifyBrightnessChanged(float brightness, boolean userInitiated,
+ float powerBrightnessFactor, boolean isUserSetBrightness,
+ boolean isDefaultBrightnessConfig) {
if (DEBUG) {
Slog.d(TAG, String.format("notifyBrightnessChanged(brightness=%f, userInitiated=%b)",
brightness, userInitiated));
}
Message m = mBgHandler.obtainMessage(MSG_BRIGHTNESS_CHANGED,
- userInitiated ? 1 : 0, 0 /*unused*/, (Float) brightness);
+ userInitiated ? 1 : 0, 0 /*unused*/, new BrightnessChangeValues(brightness,
+ powerBrightnessFactor, isUserSetBrightness, isDefaultBrightnessConfig));
m.sendToTarget();
}
- private void handleBrightnessChanged(float brightness, boolean userInitiated) {
+ private void handleBrightnessChanged(float brightness, boolean userInitiated,
+ float powerBrightnessFactor, boolean isUserSetBrightness,
+ boolean isDefaultBrightnessConfig) {
BrightnessChangeEvent.Builder builder;
synchronized (mDataCollectionLock) {
@@ -267,6 +297,9 @@
builder = new BrightnessChangeEvent.Builder();
builder.setBrightness(brightness);
builder.setTimeStamp(mInjector.currentTimeMillis());
+ builder.setPowerBrightnessFactor(powerBrightnessFactor);
+ builder.setUserBrightnessPoint(isUserSetBrightness);
+ builder.setIsDefaultBrightnessConfig(isDefaultBrightnessConfig);
final int readingCount = mLastSensorReadings.size();
if (readingCount == 0) {
@@ -321,11 +354,15 @@
}
}
- private void scheduleWriteEvents() {
+ private void scheduleWriteBrightnessTrackerState() {
if (!mWriteEventsScheduled) {
mBgHandler.post(mEventsWriter);
mWriteEventsScheduled = true;
}
+ if (!mWriteBrightnessStatsScheduled) {
+ mBgHandler.post(mAmbientBrightnessStatsWriter);
+ mWriteBrightnessStatsScheduled = true;
+ }
}
private void writeEvents() {
@@ -336,7 +373,7 @@
return;
}
- final AtomicFile writeTo = mInjector.getFile();
+ final AtomicFile writeTo = mInjector.getFile(EVENTS_FILE);
if (writeTo == null) {
return;
}
@@ -360,12 +397,29 @@
}
}
+ private void writeAmbientBrightnessStats() {
+ mWriteBrightnessStatsScheduled = false;
+ final AtomicFile writeTo = mInjector.getFile(AMBIENT_BRIGHTNESS_STATS_FILE);
+ if (writeTo == null) {
+ return;
+ }
+ FileOutputStream output = null;
+ try {
+ output = writeTo.startWrite();
+ mAmbientBrightnessStatsTracker.writeStats(output);
+ writeTo.finishWrite(output);
+ } catch (IOException e) {
+ writeTo.failWrite(output);
+ Slog.e(TAG, "Failed to write ambient brightness stats.", e);
+ }
+ }
+
private void readEvents() {
synchronized (mEventsLock) {
// Read might prune events so mark as dirty.
mEventsDirty = true;
mEvents.clear();
- final AtomicFile readFrom = mInjector.getFile();
+ final AtomicFile readFrom = mInjector.getFile(EVENTS_FILE);
if (readFrom != null && readFrom.exists()) {
FileInputStream input = null;
try {
@@ -381,6 +435,23 @@
}
}
+ private void readAmbientBrightnessStats() {
+ mAmbientBrightnessStatsTracker = new AmbientBrightnessStatsTracker(mUserManager, null);
+ final AtomicFile readFrom = mInjector.getFile(AMBIENT_BRIGHTNESS_STATS_FILE);
+ if (readFrom != null && readFrom.exists()) {
+ FileInputStream input = null;
+ try {
+ input = readFrom.openRead();
+ mAmbientBrightnessStatsTracker.readStats(input);
+ } catch (IOException e) {
+ readFrom.delete();
+ Slog.e(TAG, "Failed to read ambient brightness stats.", e);
+ } finally {
+ IoUtils.closeQuietly(input);
+ }
+ }
+ }
+
@VisibleForTesting
@GuardedBy("mEventsLock")
void writeEventsLocked(OutputStream stream) throws IOException {
@@ -412,6 +483,12 @@
toWrite[i].colorTemperature));
out.attribute(null, ATTR_LAST_NITS,
Float.toString(toWrite[i].lastBrightness));
+ out.attribute(null, ATTR_DEFAULT_CONFIG,
+ Boolean.toString(toWrite[i].isDefaultBrightnessConfig));
+ out.attribute(null, ATTR_POWER_SAVE,
+ Float.toString(toWrite[i].powerBrightnessFactor));
+ out.attribute(null, ATTR_USER_POINT,
+ Boolean.toString(toWrite[i].isUserSetBrightness));
StringBuilder luxValues = new StringBuilder();
StringBuilder luxTimestamps = new StringBuilder();
for (int j = 0; j < toWrite[i].luxValues.length; ++j) {
@@ -496,6 +573,21 @@
builder.setLuxValues(luxValues);
builder.setLuxTimestamps(luxTimestamps);
+ String defaultConfig = parser.getAttributeValue(null, ATTR_DEFAULT_CONFIG);
+ if (defaultConfig != null) {
+ builder.setIsDefaultBrightnessConfig(Boolean.parseBoolean(defaultConfig));
+ }
+ String powerSave = parser.getAttributeValue(null, ATTR_POWER_SAVE);
+ if (powerSave != null) {
+ builder.setPowerBrightnessFactor(Float.parseFloat(powerSave));
+ } else {
+ builder.setPowerBrightnessFactor(1.0f);
+ }
+ String userPoint = parser.getAttributeValue(null, ATTR_USER_POINT);
+ if (userPoint != null) {
+ builder.setUserBrightnessPoint(Boolean.parseBoolean(userPoint));
+ }
+
BrightnessChangeEvent event = builder.build();
if (DEBUG) {
Slog.i(TAG, "Read event " + event.brightness
@@ -535,7 +627,11 @@
BrightnessChangeEvent[] events = mEvents.toArray();
for (int i = 0; i < events.length; ++i) {
pw.print(" " + events[i].timeStamp + ", " + events[i].userId);
- pw.print(", " + events[i].lastBrightness + "->" + events[i].brightness + ", {");
+ pw.print(", " + events[i].lastBrightness + "->" + events[i].brightness);
+ pw.print(", isUserSetBrightness=" + events[i].isUserSetBrightness);
+ pw.print(", powerBrightnessFactor=" + events[i].powerBrightnessFactor);
+ pw.print(", isDefaultBrightnessConfig=" + events[i].isDefaultBrightnessConfig);
+ pw.print(" {");
for (int j = 0; j < events[i].luxValues.length; ++j){
if (j != 0) {
pw.print(", ");
@@ -545,6 +641,13 @@
pw.println("}");
}
}
+ if (mAmbientBrightnessStatsTracker != null) {
+ mAmbientBrightnessStatsTracker.dump(pw);
+ }
+ }
+
+ public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(int userId) {
+ return new ParceledListSlice<>(mAmbientBrightnessStatsTracker.getUserStats(userId));
}
// Not allowed to keep the SensorEvent so used to copy the data we care about.
@@ -584,6 +687,10 @@
}
}
+ private void recordAmbientBrightnessStats(SensorEvent event) {
+ mAmbientBrightnessStatsTracker.add(mCurrentUserId, event.values[0]);
+ }
+
private void batteryLevelChanged(int level, int scale) {
synchronized (mDataCollectionLock) {
mLastBatteryLevel = (float) level / (float) scale;
@@ -594,6 +701,7 @@
@Override
public void onSensorChanged(SensorEvent event) {
recordSensorEvent(event);
+ recordAmbientBrightnessStats(event);
}
@Override
@@ -611,7 +719,7 @@
String action = intent.getAction();
if (Intent.ACTION_SHUTDOWN.equals(action)) {
stop();
- scheduleWriteEvents();
+ scheduleWriteBrightnessTrackerState();
} else if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);
@@ -619,8 +727,10 @@
batteryLevelChanged(level, scale);
}
} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
+ mAmbientBrightnessStatsTracker.stop();
mInjector.unregisterSensorListener(mContext, mSensorListener);
} else if (Intent.ACTION_SCREEN_ON.equals(action)) {
+ mAmbientBrightnessStatsTracker.start();
mInjector.registerSensorListener(mContext, mSensorListener,
mInjector.getBackgroundHandler());
}
@@ -637,14 +747,31 @@
backgroundStart((float)msg.obj /*initial brightness*/);
break;
case MSG_BRIGHTNESS_CHANGED:
- float newBrightness = (float) msg.obj;
+ BrightnessChangeValues values = (BrightnessChangeValues) msg.obj;
boolean userInitiatedChange = (msg.arg1 == 1);
- handleBrightnessChanged(newBrightness, userInitiatedChange);
+ handleBrightnessChanged(values.brightness, userInitiatedChange,
+ values.powerBrightnessFactor, values.isUserSetBrightness,
+ values.isDefaultBrightnessConfig);
break;
}
}
}
+ private static class BrightnessChangeValues {
+ final float brightness;
+ final float powerBrightnessFactor;
+ final boolean isUserSetBrightness;
+ final boolean isDefaultBrightnessConfig;
+
+ BrightnessChangeValues(float brightness, float powerBrightnessFactor,
+ boolean isUserSetBrightness, boolean isDefaultBrightnessConfig) {
+ this.brightness = brightness;
+ this.powerBrightnessFactor = powerBrightnessFactor;
+ this.isUserSetBrightness = isUserSetBrightness;
+ this.isDefaultBrightnessConfig = isDefaultBrightnessConfig;
+ }
+ }
+
@VisibleForTesting
static class Injector {
public void registerSensorListener(Context context,
@@ -679,8 +806,8 @@
return Settings.Secure.getIntForUser(resolver, setting, defaultValue, userId);
}
- public AtomicFile getFile() {
- return new AtomicFile(new File(Environment.getDataSystemDeDirectory(), EVENTS_FILE));
+ public AtomicFile getFile(String filename) {
+ return new AtomicFile(new File(Environment.getDataSystemDeDirectory(), filename));
}
public long currentTimeMillis() {
diff --git a/services/core/java/com/android/server/display/DisplayManagerService.java b/services/core/java/com/android/server/display/DisplayManagerService.java
index 0c2ff05..a5c1fe2 100644
--- a/services/core/java/com/android/server/display/DisplayManagerService.java
+++ b/services/core/java/com/android/server/display/DisplayManagerService.java
@@ -38,6 +38,7 @@
import android.content.res.Resources;
import android.graphics.Point;
import android.hardware.SensorManager;
+import android.hardware.display.AmbientBrightnessDayStats;
import android.hardware.display.BrightnessChangeEvent;
import android.hardware.display.BrightnessConfiguration;
import android.hardware.display.DisplayManagerGlobal;
@@ -359,6 +360,7 @@
mPersistentDataStore.getBrightnessConfiguration(userSerial);
mDisplayPowerController.setBrightnessConfiguration(config);
}
+ mDisplayPowerController.onSwitchUser(newUserId);
}
}
@@ -1835,6 +1837,23 @@
}
@Override // Binder call
+ public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats() {
+ mContext.enforceCallingOrSelfPermission(
+ Manifest.permission.ACCESS_AMBIENT_LIGHT_STATS,
+ "Permission required to to access ambient light stats.");
+ final int callingUid = Binder.getCallingUid();
+ final int userId = UserHandle.getUserId(callingUid);
+ final long token = Binder.clearCallingIdentity();
+ try {
+ synchronized (mSyncRoot) {
+ return mDisplayPowerController.getAmbientBrightnessStats(userId);
+ }
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
+ }
+
+ @Override // Binder call
public void setBrightnessConfigurationForUser(
BrightnessConfiguration c, @UserIdInt int userId, String packageName) {
mContext.enforceCallingOrSelfPermission(
@@ -2039,9 +2058,9 @@
}
@Override
- public void persistBrightnessSliderEvents() {
+ public void persistBrightnessTrackerState() {
synchronized (mSyncRoot) {
- mDisplayPowerController.persistBrightnessSliderEvents();
+ mDisplayPowerController.persistBrightnessTrackerState();
}
}
diff --git a/services/core/java/com/android/server/display/DisplayPowerController.java b/services/core/java/com/android/server/display/DisplayPowerController.java
index 80aec42..b27f1ec 100644
--- a/services/core/java/com/android/server/display/DisplayPowerController.java
+++ b/services/core/java/com/android/server/display/DisplayPowerController.java
@@ -34,6 +34,7 @@
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
+import android.hardware.display.AmbientBrightnessDayStats;
import android.hardware.display.BrightnessChangeEvent;
import android.hardware.display.BrightnessConfiguration;
import android.hardware.display.DisplayManagerInternal.DisplayPowerCallbacks;
@@ -478,6 +479,7 @@
mScreenBrightnessForVr = getScreenBrightnessForVrSetting();
mAutoBrightnessAdjustment = getAutoBrightnessAdjustmentSetting();
mTemporaryScreenBrightness = -1;
+ mPendingScreenBrightnessSetting = -1;
mTemporaryAutoBrightnessAdjustment = Float.NaN;
}
@@ -498,11 +500,20 @@
return mBrightnessTracker.getEvents(userId, includePackage);
}
+ public void onSwitchUser(@UserIdInt int newUserId) {
+ mBrightnessTracker.onSwitchUser(newUserId);
+ }
+
+ public ParceledListSlice<AmbientBrightnessDayStats> getAmbientBrightnessStats(
+ @UserIdInt int userId) {
+ return mBrightnessTracker.getAmbientBrightnessStats(userId);
+ }
+
/**
- * Persist the brightness slider events to disk.
+ * Persist the brightness slider events and ambient brightness stats to disk.
*/
- public void persistBrightnessSliderEvents() {
- mBrightnessTracker.persistEvents();
+ public void persistBrightnessTrackerState() {
+ mBrightnessTracker.persistBrightnessTrackerState();
}
/**
@@ -795,13 +806,15 @@
brightness = PowerManager.BRIGHTNESS_ON;
}
- // If the brightness is already set then it's been overriden by something other than the
+ // If the brightness is already set then it's been overridden by something other than the
// user, or is a temporary adjustment.
final boolean userInitiatedChange = brightness < 0
&& (autoBrightnessAdjustmentChanged || userSetBrightnessChanged);
+ boolean hadUserBrightnessPoint = false;
// Configure auto-brightness.
if (mAutomaticBrightnessController != null) {
+ hadUserBrightnessPoint = mAutomaticBrightnessController.hasUserDataPoints();
mAutomaticBrightnessController.configure(autoBrightnessEnabled,
mBrightnessConfiguration,
mLastUserSetScreenBrightness / (float) PowerManager.BRIGHTNESS_ON,
@@ -930,7 +943,7 @@
}
if (!brightnessIsTemporary) {
- notifyBrightnessChanged(brightness, userInitiatedChange);
+ notifyBrightnessChanged(brightness, userInitiatedChange, hadUserBrightnessPoint);
}
}
@@ -1464,18 +1477,26 @@
mPendingScreenBrightnessSetting = -1;
return false;
}
+ mCurrentScreenBrightnessSetting = mPendingScreenBrightnessSetting;
mLastUserSetScreenBrightness = mPendingScreenBrightnessSetting;
mPendingScreenBrightnessSetting = -1;
return true;
}
- private void notifyBrightnessChanged(int brightness, boolean userInitiated) {
+ private void notifyBrightnessChanged(int brightness, boolean userInitiated,
+ boolean hadUserDataPoint) {
final float brightnessInNits = convertToNits(brightness);
- if (brightnessInNits >= 0.0f) {
+ if (mPowerRequest.useAutoBrightness && brightnessInNits >= 0.0f
+ && mAutomaticBrightnessController != null) {
// We only want to track changes on devices that can actually map the display backlight
// values into a physical brightness unit since the value provided by the API is in
// nits and not using the arbitrary backlight units.
- mBrightnessTracker.notifyBrightnessChanged(brightnessInNits, userInitiated);
+ final float powerFactor = mPowerRequest.lowPowerMode
+ ? mPowerRequest.screenLowPowerBrightnessFactor
+ : 1.0f;
+ mBrightnessTracker.notifyBrightnessChanged(brightnessInNits, userInitiated,
+ powerFactor, hadUserDataPoint,
+ mAutomaticBrightnessController.isDefaultConfig());
}
}
diff --git a/services/core/java/com/android/server/job/JobSchedulerService.java b/services/core/java/com/android/server/job/JobSchedulerService.java
index e0baeee..401c05e 100644
--- a/services/core/java/com/android/server/job/JobSchedulerService.java
+++ b/services/core/java/com/android/server/job/JobSchedulerService.java
@@ -862,7 +862,8 @@
}
startTrackingJobLocked(jobStatus, toCancel);
StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
- uId, null, jobStatus.getBatteryName(), 2);
+ uId, null, jobStatus.getBatteryName(),
+ StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED);
// If the job is immediately ready to run, then we can just immediately
// put it in the pending list and try to schedule it. This is especially
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/RecoverableKeyStoreDbHelper.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/RecoverableKeyStoreDbHelper.java
index d96671c..79fd496 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/RecoverableKeyStoreDbHelper.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/storage/RecoverableKeyStoreDbHelper.java
@@ -28,7 +28,7 @@
* Helper for creating the recoverable key database.
*/
class RecoverableKeyStoreDbHelper extends SQLiteOpenHelper {
- private static final int DATABASE_VERSION = 1;
+ private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "recoverablekeystore.db";
private static final String SQL_CREATE_KEYS_ENTRY =
diff --git a/services/core/java/com/android/server/pm/InstantAppResolver.java b/services/core/java/com/android/server/pm/InstantAppResolver.java
index 30072d4..af446ba 100644
--- a/services/core/java/com/android/server/pm/InstantAppResolver.java
+++ b/services/core/java/com/android/server/pm/InstantAppResolver.java
@@ -40,26 +40,33 @@
import android.content.pm.InstantAppResolveInfo;
import android.content.pm.InstantAppResolveInfo.InstantAppDigest;
import android.metrics.LogMaker;
+import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
+import android.text.TextUtils;
import android.util.Log;
+import android.util.Slog;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto;
-import com.android.server.pm.EphemeralResolverConnection.ConnectionException;
-import com.android.server.pm.EphemeralResolverConnection.PhaseTwoCallback;
+import com.android.server.pm.InstantAppResolverConnection.ConnectionException;
+import com.android.server.pm.InstantAppResolverConnection.PhaseTwoCallback;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
import java.util.List;
+import java.util.Set;
import java.util.UUID;
/** @hide */
public abstract class InstantAppResolver {
- private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
+ private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
private static final String TAG = "PackageManager";
private static final int RESOLUTION_SUCCESS = 0;
@@ -79,6 +86,7 @@
public @interface ResolutionStatus {}
private static MetricsLogger sMetricsLogger;
+
private static MetricsLogger getLogger() {
if (sMetricsLogger == null) {
sMetricsLogger = new MetricsLogger();
@@ -86,26 +94,49 @@
return sMetricsLogger;
}
- public static AuxiliaryResolveInfo doInstantAppResolutionPhaseOne(Context context,
- EphemeralResolverConnection connection, InstantAppRequest requestObj) {
+ /**
+ * Returns an intent with potential PII removed from the original intent. Fields removed
+ * include extras and the host + path of the data, if defined.
+ */
+ public static Intent sanitizeIntent(Intent origIntent) {
+ final Intent sanitizedIntent;
+ sanitizedIntent = new Intent(origIntent.getAction());
+ Set<String> categories = origIntent.getCategories();
+ if (categories != null) {
+ for (String category : categories) {
+ sanitizedIntent.addCategory(category);
+ }
+ }
+ Uri sanitizedUri = origIntent.getData() == null
+ ? null
+ : Uri.fromParts(origIntent.getScheme(), "", "");
+ sanitizedIntent.setDataAndType(sanitizedUri, origIntent.getType());
+ sanitizedIntent.addFlags(origIntent.getFlags());
+ sanitizedIntent.setPackage(origIntent.getPackage());
+ return sanitizedIntent;
+ }
+
+ public static AuxiliaryResolveInfo doInstantAppResolutionPhaseOne(
+ InstantAppResolverConnection connection, InstantAppRequest requestObj) {
final long startTime = System.currentTimeMillis();
final String token = UUID.randomUUID().toString();
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Log.d(TAG, "[" + token + "] Phase1; resolving");
}
- final Intent intent = requestObj.origIntent;
- final InstantAppDigest digest =
- new InstantAppDigest(intent.getData().getHost(), 5 /*maxDigests*/);
+ final Intent origIntent = requestObj.origIntent;
+ final Intent sanitizedIntent = sanitizeIntent(origIntent);
+
+ final InstantAppDigest digest = getInstantAppDigest(origIntent);
final int[] shaPrefix = digest.getDigestPrefix();
AuxiliaryResolveInfo resolveInfo = null;
@ResolutionStatus int resolutionStatus = RESOLUTION_SUCCESS;
try {
final List<InstantAppResolveInfo> instantAppResolveInfoList =
- connection.getInstantAppResolveInfoList(shaPrefix, token);
+ connection.getInstantAppResolveInfoList(sanitizedIntent, shaPrefix, token);
if (instantAppResolveInfoList != null && instantAppResolveInfoList.size() > 0) {
resolveInfo = InstantAppResolver.filterInstantAppIntent(
- instantAppResolveInfoList, intent, requestObj.resolvedType,
- requestObj.userId, intent.getPackage(), digest, token);
+ instantAppResolveInfoList, origIntent, requestObj.resolvedType,
+ requestObj.userId, origIntent.getPackage(), digest, token);
}
} catch (ConnectionException e) {
if (e.failure == ConnectionException.FAILURE_BIND) {
@@ -121,7 +152,7 @@
logMetrics(ACTION_INSTANT_APP_RESOLUTION_PHASE_ONE, startTime, token,
resolutionStatus);
}
- if (DEBUG_EPHEMERAL && resolveInfo == null) {
+ if (DEBUG_INSTANT && resolveInfo == null) {
if (resolutionStatus == RESOLUTION_BIND_TIMEOUT) {
Log.d(TAG, "[" + token + "] Phase1; bind timed out");
} else if (resolutionStatus == RESOLUTION_CALL_TIMEOUT) {
@@ -135,81 +166,67 @@
return resolveInfo;
}
+ private static InstantAppDigest getInstantAppDigest(Intent origIntent) {
+ return origIntent.getData() != null && !TextUtils.isEmpty(origIntent.getData().getHost())
+ ? new InstantAppDigest(origIntent.getData().getHost(), 5 /*maxDigests*/)
+ : InstantAppDigest.UNDEFINED;
+ }
+
public static void doInstantAppResolutionPhaseTwo(Context context,
- EphemeralResolverConnection connection, InstantAppRequest requestObj,
+ InstantAppResolverConnection connection, InstantAppRequest requestObj,
ActivityInfo instantAppInstaller, Handler callbackHandler) {
final long startTime = System.currentTimeMillis();
final String token = requestObj.responseObj.token;
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Log.d(TAG, "[" + token + "] Phase2; resolving");
}
- final Intent intent = requestObj.origIntent;
- final String hostName = intent.getData().getHost();
- final InstantAppDigest digest = new InstantAppDigest(hostName, 5 /*maxDigests*/);
+ final Intent origIntent = requestObj.origIntent;
+ final Intent sanitizedIntent = sanitizeIntent(origIntent);
+ final InstantAppDigest digest = getInstantAppDigest(origIntent);
final int[] shaPrefix = digest.getDigestPrefix();
final PhaseTwoCallback callback = new PhaseTwoCallback() {
@Override
void onPhaseTwoResolved(List<InstantAppResolveInfo> instantAppResolveInfoList,
long startTime) {
- final String packageName;
- final String splitName;
- final long versionCode;
final Intent failureIntent;
- final Bundle extras;
if (instantAppResolveInfoList != null && instantAppResolveInfoList.size() > 0) {
final AuxiliaryResolveInfo instantAppIntentInfo =
InstantAppResolver.filterInstantAppIntent(
- instantAppResolveInfoList, intent, null /*resolvedType*/,
- 0 /*userId*/, intent.getPackage(), digest, token);
- if (instantAppIntentInfo != null
- && instantAppIntentInfo.resolveInfo != null) {
- packageName = instantAppIntentInfo.resolveInfo.getPackageName();
- splitName = instantAppIntentInfo.splitName;
- versionCode = instantAppIntentInfo.resolveInfo.getVersionCode();
+ instantAppResolveInfoList, origIntent, null /*resolvedType*/,
+ 0 /*userId*/, origIntent.getPackage(), digest, token);
+ if (instantAppIntentInfo != null) {
failureIntent = instantAppIntentInfo.failureIntent;
- extras = instantAppIntentInfo.resolveInfo.getExtras();
} else {
- packageName = null;
- splitName = null;
- versionCode = -1;
failureIntent = null;
- extras = null;
}
} else {
- packageName = null;
- splitName = null;
- versionCode = -1;
failureIntent = null;
- extras = null;
}
final Intent installerIntent = buildEphemeralInstallerIntent(
- Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE,
requestObj.origIntent,
+ sanitizedIntent,
failureIntent,
requestObj.callingPackage,
requestObj.verificationBundle,
requestObj.resolvedType,
requestObj.userId,
- packageName,
- splitName,
requestObj.responseObj.installFailureActivity,
- versionCode,
token,
- extras,
- false /*needsPhaseTwo*/);
+ false /*needsPhaseTwo*/,
+ requestObj.responseObj.filters);
installerIntent.setComponent(new ComponentName(
instantAppInstaller.packageName, instantAppInstaller.name));
logMetrics(ACTION_INSTANT_APP_RESOLUTION_PHASE_TWO, startTime, token,
- packageName != null ? RESOLUTION_SUCCESS : RESOLUTION_FAILURE);
+ requestObj.responseObj.filters != null ? RESOLUTION_SUCCESS : RESOLUTION_FAILURE);
context.startActivity(installerIntent);
}
};
try {
- connection.getInstantAppIntentFilterList(
- shaPrefix, token, hostName, callback, callbackHandler, startTime);
+ connection.getInstantAppIntentFilterList(sanitizedIntent, shaPrefix, token, callback,
+ callbackHandler, startTime);
} catch (ConnectionException e) {
@ResolutionStatus int resolutionStatus = RESOLUTION_FAILURE;
if (e.failure == ConnectionException.FAILURE_BIND) {
@@ -217,7 +234,7 @@
}
logMetrics(ACTION_INSTANT_APP_RESOLUTION_PHASE_TWO, startTime, token,
resolutionStatus);
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
if (resolutionStatus == RESOLUTION_BIND_TIMEOUT) {
Log.d(TAG, "[" + token + "] Phase2; bind timed out");
} else {
@@ -231,49 +248,53 @@
* Builds and returns an intent to launch the instant installer.
*/
public static Intent buildEphemeralInstallerIntent(
- @NonNull String action,
@NonNull Intent origIntent,
- @NonNull Intent failureIntent,
+ @NonNull Intent sanitizedIntent,
+ @Nullable Intent failureIntent,
@NonNull String callingPackage,
@Nullable Bundle verificationBundle,
@NonNull String resolvedType,
int userId,
- @NonNull String instantAppPackageName,
- @Nullable String instantAppSplitName,
@Nullable ComponentName installFailureActivity,
- long versionCode,
@Nullable String token,
- @Nullable Bundle extras,
- boolean needsPhaseTwo) {
+ boolean needsPhaseTwo,
+ List<AuxiliaryResolveInfo.AuxiliaryFilter> filters) {
// Construct the intent that launches the instant installer
int flags = origIntent.getFlags();
- final Intent intent = new Intent(action);
+ final Intent intent = new Intent();
intent.setFlags(flags
| Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
if (token != null) {
+ // TODO(b/72700831): remove populating old extra
intent.putExtra(Intent.EXTRA_EPHEMERAL_TOKEN, token);
+ intent.putExtra(Intent.EXTRA_INSTANT_APP_TOKEN, token);
}
if (origIntent.getData() != null) {
+ // TODO(b/72700831): remove populating old extra
intent.putExtra(Intent.EXTRA_EPHEMERAL_HOSTNAME, origIntent.getData().getHost());
+ intent.putExtra(Intent.EXTRA_INSTANT_APP_HOSTNAME, origIntent.getData().getHost());
}
intent.putExtra(Intent.EXTRA_INSTANT_APP_ACTION, origIntent.getAction());
- if (extras != null) {
- intent.putExtra(Intent.EXTRA_INSTANT_APP_EXTRAS, extras);
- }
+ intent.putExtra(Intent.EXTRA_INTENT, sanitizedIntent);
- // We have all of the data we need; just start the installer without a second phase
- if (!needsPhaseTwo) {
- // Intent that is launched if the package couldn't be installed for any reason.
+ if (needsPhaseTwo) {
+ intent.setAction(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE);
+ } else {
+ // We have all of the data we need; just start the installer without a second phase
if (failureIntent != null || installFailureActivity != null) {
+ // Intent that is launched if the package couldn't be installed for any reason.
try {
final Intent onFailureIntent;
if (installFailureActivity != null) {
onFailureIntent = new Intent();
onFailureIntent.setComponent(installFailureActivity);
- onFailureIntent.putExtra(Intent.EXTRA_SPLIT_NAME, instantAppSplitName);
+ if (filters != null && filters.size() == 1) {
+ onFailureIntent.putExtra(Intent.EXTRA_SPLIT_NAME,
+ filters.get(0).splitName);
+ }
onFailureIntent.putExtra(Intent.EXTRA_INTENT, origIntent);
} else {
onFailureIntent = failureIntent;
@@ -288,8 +309,10 @@
| PendingIntent.FLAG_ONE_SHOT
| PendingIntent.FLAG_IMMUTABLE,
null /*bOptions*/, userId);
- intent.putExtra(Intent.EXTRA_EPHEMERAL_FAILURE,
- new IntentSender(failureIntentTarget));
+ IntentSender failureSender = new IntentSender(failureIntentTarget);
+ // TODO(b/72700831): remove populating old extra
+ intent.putExtra(Intent.EXTRA_EPHEMERAL_FAILURE, failureSender);
+ intent.putExtra(Intent.EXTRA_INSTANT_APP_FAILURE, failureSender);
} catch (RemoteException ignore) { /* ignore; same process */ }
}
@@ -306,20 +329,40 @@
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
| PendingIntent.FLAG_IMMUTABLE,
null /*bOptions*/, userId);
- intent.putExtra(Intent.EXTRA_EPHEMERAL_SUCCESS,
- new IntentSender(successIntentTarget));
+ IntentSender successSender = new IntentSender(successIntentTarget);
+ // TODO(b/72700831): remove populating old extra
+ intent.putExtra(Intent.EXTRA_EPHEMERAL_SUCCESS, successSender);
+ intent.putExtra(Intent.EXTRA_INSTANT_APP_SUCCESS, successSender);
} catch (RemoteException ignore) { /* ignore; same process */ }
-
- intent.putExtra(Intent.EXTRA_PACKAGE_NAME, instantAppPackageName);
- intent.putExtra(Intent.EXTRA_SPLIT_NAME, instantAppSplitName);
- intent.putExtra(Intent.EXTRA_VERSION_CODE, (int) (versionCode & 0x7fffffff));
- intent.putExtra(Intent.EXTRA_LONG_VERSION_CODE, versionCode);
- intent.putExtra(Intent.EXTRA_CALLING_PACKAGE, callingPackage);
if (verificationBundle != null) {
intent.putExtra(Intent.EXTRA_VERIFICATION_BUNDLE, verificationBundle);
}
- }
+ intent.putExtra(Intent.EXTRA_CALLING_PACKAGE, callingPackage);
+ if (filters != null) {
+ Bundle resolvableFilters[] = new Bundle[filters.size()];
+ for (int i = 0, max = filters.size(); i < max; i++) {
+ Bundle resolvableFilter = new Bundle();
+ AuxiliaryResolveInfo.AuxiliaryFilter filter = filters.get(i);
+ resolvableFilter.putBoolean(Intent.EXTRA_UNKNOWN_INSTANT_APP,
+ filter.resolveInfo != null
+ && filter.resolveInfo.shouldLetInstallerDecide());
+ resolvableFilter.putString(Intent.EXTRA_PACKAGE_NAME, filter.packageName);
+ resolvableFilter.putString(Intent.EXTRA_SPLIT_NAME, filter.splitName);
+ resolvableFilter.putLong(Intent.EXTRA_LONG_VERSION_CODE, filter.versionCode);
+ resolvableFilter.putBundle(Intent.EXTRA_INSTANT_APP_EXTRAS, filter.extras);
+ resolvableFilters[i] = resolvableFilter;
+ if (i == 0) {
+ // for backwards compat, always set the first result on the intent and add
+ // the int version code
+ intent.putExtras(resolvableFilter);
+ intent.putExtra(Intent.EXTRA_VERSION_CODE, (int) filter.versionCode);
+ }
+ }
+ intent.putExtra(Intent.EXTRA_INSTANT_APP_BUNDLES, resolvableFilters);
+ }
+ intent.setAction(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
+ }
return intent;
}
@@ -330,69 +373,134 @@
final int[] shaPrefix = digest.getDigestPrefix();
final byte[][] digestBytes = digest.getDigestBytes();
final Intent failureIntent = new Intent(origIntent);
+ boolean requiresSecondPhase = false;
failureIntent.setFlags(failureIntent.getFlags() | Intent.FLAG_IGNORE_EPHEMERAL);
failureIntent.setLaunchToken(token);
- // Go in reverse order so we match the narrowest scope first.
- for (int i = shaPrefix.length - 1; i >= 0 ; --i) {
- for (InstantAppResolveInfo instantAppInfo : instantAppResolveInfoList) {
- if (!Arrays.equals(digestBytes[i], instantAppInfo.getDigestBytes())) {
+ ArrayList<AuxiliaryResolveInfo.AuxiliaryFilter> filters = null;
+ boolean isWebIntent = origIntent.isBrowsableWebIntent();
+ for (InstantAppResolveInfo instantAppResolveInfo : instantAppResolveInfoList) {
+ if (shaPrefix.length > 0 && instantAppResolveInfo.shouldLetInstallerDecide()) {
+ Slog.e(TAG, "InstantAppResolveInfo with mShouldLetInstallerDecide=true when digest"
+ + " provided; ignoring");
+ continue;
+ }
+ byte[] filterDigestBytes = instantAppResolveInfo.getDigestBytes();
+ // Only include matching digests if we have a prefix and we're either dealing with a
+ // web intent or the resolveInfo specifies digest details.
+ if (shaPrefix.length > 0 && (isWebIntent || filterDigestBytes.length > 0)) {
+ boolean matchFound = false;
+ // Go in reverse order so we match the narrowest scope first.
+ for (int i = shaPrefix.length - 1; i >= 0; --i) {
+ if (Arrays.equals(digestBytes[i], filterDigestBytes)) {
+ matchFound = true;
+ break;
+ }
+ }
+ if (!matchFound) {
continue;
}
- if (packageName != null
- && !packageName.equals(instantAppInfo.getPackageName())) {
- continue;
+ }
+ // We matched a resolve info; resolve the filters to see if anything matches completely.
+ List<AuxiliaryResolveInfo.AuxiliaryFilter> matchFilters = computeResolveFilters(
+ origIntent, resolvedType, userId, packageName, token, instantAppResolveInfo);
+ if (matchFilters != null) {
+ if (matchFilters.isEmpty()) {
+ requiresSecondPhase = true;
}
- final List<InstantAppIntentFilter> instantAppFilters =
- instantAppInfo.getIntentFilters();
- // No filters; we need to start phase two
- if (instantAppFilters == null || instantAppFilters.isEmpty()) {
- if (DEBUG_EPHEMERAL) {
- Log.d(TAG, "No app filters; go to phase 2");
- }
- return new AuxiliaryResolveInfo(instantAppInfo,
- new IntentFilter(Intent.ACTION_VIEW) /*intentFilter*/,
- null /*splitName*/, token, true /*needsPhase2*/,
- null /*failureIntent*/);
- }
- // We have a domain match; resolve the filters to see if anything matches.
- final PackageManagerService.EphemeralIntentResolver instantAppResolver =
- new PackageManagerService.EphemeralIntentResolver();
- for (int j = instantAppFilters.size() - 1; j >= 0; --j) {
- final InstantAppIntentFilter instantAppFilter = instantAppFilters.get(j);
- final List<IntentFilter> splitFilters = instantAppFilter.getFilters();
- if (splitFilters == null || splitFilters.isEmpty()) {
- continue;
- }
- for (int k = splitFilters.size() - 1; k >= 0; --k) {
- final AuxiliaryResolveInfo intentInfo =
- new AuxiliaryResolveInfo(instantAppInfo,
- splitFilters.get(k), instantAppFilter.getSplitName(),
- token, false /*needsPhase2*/, failureIntent);
- instantAppResolver.addFilter(intentInfo);
- }
- }
- List<AuxiliaryResolveInfo> matchedResolveInfoList = instantAppResolver.queryIntent(
- origIntent, resolvedType, false /*defaultOnly*/, userId);
- if (!matchedResolveInfoList.isEmpty()) {
- if (DEBUG_EPHEMERAL) {
- final AuxiliaryResolveInfo info = matchedResolveInfoList.get(0);
- Log.d(TAG, "[" + token + "] Found match;"
- + " package: " + info.packageName
- + ", split: " + info.splitName
- + ", versionCode: " + info.versionCode);
- }
- return matchedResolveInfoList.get(0);
- } else if (DEBUG_EPHEMERAL) {
- Log.d(TAG, "[" + token + "] No matches found"
- + " package: " + instantAppInfo.getPackageName()
- + ", versionCode: " + instantAppInfo.getVersionCode());
+ if (filters == null) {
+ filters = new ArrayList<>(matchFilters);
+ } else {
+ filters.addAll(matchFilters);
}
}
}
+ if (filters != null && !filters.isEmpty()) {
+ return new AuxiliaryResolveInfo(token, requiresSecondPhase, failureIntent, filters);
+ }
// Hash or filter mis-match; no instant apps for this domain.
return null;
}
+ /**
+ * Returns one of three states: <p/>
+ * <ul>
+ * <li>{@code null} if there are no matches will not be; resolution is unnecessary.</li>
+ * <li>An empty list signifying that a 2nd phase of resolution is required.</li>
+ * <li>A populated list meaning that matches were found and should be sent directly to the
+ * installer</li>
+ * </ul>
+ *
+ */
+ private static List<AuxiliaryResolveInfo.AuxiliaryFilter> computeResolveFilters(
+ Intent origIntent, String resolvedType, int userId, String packageName, String token,
+ InstantAppResolveInfo instantAppInfo) {
+ if (instantAppInfo.shouldLetInstallerDecide()) {
+ return Collections.singletonList(
+ new AuxiliaryResolveInfo.AuxiliaryFilter(
+ instantAppInfo, null /* splitName */,
+ instantAppInfo.getExtras()));
+ }
+ if (packageName != null
+ && !packageName.equals(instantAppInfo.getPackageName())) {
+ return null;
+ }
+ final List<InstantAppIntentFilter> instantAppFilters =
+ instantAppInfo.getIntentFilters();
+ if (instantAppFilters == null || instantAppFilters.isEmpty()) {
+ // No filters on web intent; no matches, 2nd phase unnecessary.
+ if (origIntent.isBrowsableWebIntent()) {
+ return null;
+ }
+ // No filters; we need to start phase two
+ if (DEBUG_INSTANT) {
+ Log.d(TAG, "No app filters; go to phase 2");
+ }
+ return Collections.emptyList();
+ }
+ final PackageManagerService.InstantAppIntentResolver instantAppResolver =
+ new PackageManagerService.InstantAppIntentResolver();
+ for (int j = instantAppFilters.size() - 1; j >= 0; --j) {
+ final InstantAppIntentFilter instantAppFilter = instantAppFilters.get(j);
+ final List<IntentFilter> splitFilters = instantAppFilter.getFilters();
+ if (splitFilters == null || splitFilters.isEmpty()) {
+ continue;
+ }
+ for (int k = splitFilters.size() - 1; k >= 0; --k) {
+ IntentFilter filter = splitFilters.get(k);
+ Iterator<IntentFilter.AuthorityEntry> authorities =
+ filter.authoritiesIterator();
+ // ignore http/s-only filters.
+ if ((authorities == null || !authorities.hasNext())
+ && (filter.hasDataScheme("http") || filter.hasDataScheme("https"))
+ && filter.hasAction(Intent.ACTION_VIEW)
+ && filter.hasCategory(Intent.CATEGORY_BROWSABLE)) {
+ continue;
+ }
+ instantAppResolver.addFilter(
+ new AuxiliaryResolveInfo.AuxiliaryFilter(
+ filter,
+ instantAppInfo,
+ instantAppFilter.getSplitName(),
+ instantAppInfo.getExtras()
+ ));
+ }
+ }
+ List<AuxiliaryResolveInfo.AuxiliaryFilter> matchedResolveInfoList =
+ instantAppResolver.queryIntent(
+ origIntent, resolvedType, false /*defaultOnly*/, userId);
+ if (!matchedResolveInfoList.isEmpty()) {
+ if (DEBUG_INSTANT) {
+ Log.d(TAG, "[" + token + "] Found match(es); " + matchedResolveInfoList);
+ }
+ return matchedResolveInfoList;
+ } else if (DEBUG_INSTANT) {
+ Log.d(TAG, "[" + token + "] No matches found"
+ + " package: " + instantAppInfo.getPackageName()
+ + ", versionCode: " + instantAppInfo.getVersionCode());
+ }
+ return null;
+ }
+
private static void logMetrics(int action, long startTime, String token,
@ResolutionStatus int status) {
final LogMaker logMaker = new LogMaker(action)
diff --git a/services/core/java/com/android/server/pm/EphemeralResolverConnection.java b/services/core/java/com/android/server/pm/InstantAppResolverConnection.java
similarity index 85%
rename from services/core/java/com/android/server/pm/EphemeralResolverConnection.java
rename to services/core/java/com/android/server/pm/InstantAppResolverConnection.java
index b5ddf8c..a9ee411 100644
--- a/services/core/java/com/android/server/pm/EphemeralResolverConnection.java
+++ b/services/core/java/com/android/server/pm/InstantAppResolverConnection.java
@@ -37,33 +37,29 @@
import android.util.TimedRemoteCaller;
import com.android.internal.annotations.GuardedBy;
-import com.android.internal.os.TransferPipe;
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeoutException;
/**
- * Represents a remote ephemeral resolver. It is responsible for binding to the remote
+ * Represents a remote instant app resolver. It is responsible for binding to the remote
* service and handling all interactions in a timely manner.
* @hide
*/
-final class EphemeralResolverConnection implements DeathRecipient {
+final class InstantAppResolverConnection implements DeathRecipient {
private static final String TAG = "PackageManager";
// This is running in a critical section and the timeout must be sufficiently low
private static final long BIND_SERVICE_TIMEOUT_MS =
Build.IS_ENG ? 500 : 300;
private static final long CALL_SERVICE_TIMEOUT_MS =
Build.IS_ENG ? 200 : 100;
- private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
+ private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
private final Object mLock = new Object();
- private final GetEphemeralResolveInfoCaller mGetEphemeralResolveInfoCaller =
- new GetEphemeralResolveInfoCaller();
+ private final GetInstantAppResolveInfoCaller mGetInstantAppResolveInfoCaller =
+ new GetInstantAppResolveInfoCaller();
private final ServiceConnection mServiceConnection = new MyServiceConnection();
private final Context mContext;
/** Intent used to bind to the service */
@@ -78,14 +74,14 @@
@GuardedBy("mLock")
private IInstantAppResolver mRemoteInstance;
- public EphemeralResolverConnection(
+ public InstantAppResolverConnection(
Context context, ComponentName componentName, String action) {
mContext = context;
mIntent = new Intent(action).setComponent(componentName);
}
- public final List<InstantAppResolveInfo> getInstantAppResolveInfoList(int hashPrefix[],
- String token) throws ConnectionException {
+ public final List<InstantAppResolveInfo> getInstantAppResolveInfoList(Intent sanitizedIntent,
+ int hashPrefix[], String token) throws ConnectionException {
throwIfCalledOnMainThread();
IInstantAppResolver target = null;
try {
@@ -97,8 +93,8 @@
throw new ConnectionException(ConnectionException.FAILURE_INTERRUPTED);
}
try {
- return mGetEphemeralResolveInfoCaller
- .getEphemeralResolveInfoList(target, hashPrefix, token);
+ return mGetInstantAppResolveInfoCaller
+ .getInstantAppResolveInfoList(target, sanitizedIntent, hashPrefix, token);
} catch (TimeoutException e) {
throw new ConnectionException(ConnectionException.FAILURE_CALL);
} catch (RemoteException ignore) {
@@ -111,26 +107,22 @@
return null;
}
- public final void getInstantAppIntentFilterList(int hashPrefix[], String token,
- String hostName, PhaseTwoCallback callback, Handler callbackHandler,
- final long startTime) throws ConnectionException {
+ public final void getInstantAppIntentFilterList(Intent sanitizedIntent, int hashPrefix[],
+ String token, PhaseTwoCallback callback, Handler callbackHandler, final long startTime)
+ throws ConnectionException {
final IRemoteCallback remoteCallback = new IRemoteCallback.Stub() {
@Override
public void sendResult(Bundle data) throws RemoteException {
final ArrayList<InstantAppResolveInfo> resolveList =
data.getParcelableArrayList(
InstantAppResolverService.EXTRA_RESOLVE_INFO);
- callbackHandler.post(new Runnable() {
- @Override
- public void run() {
- callback.onPhaseTwoResolved(resolveList, startTime);
- }
- });
+ callbackHandler.post(() -> callback.onPhaseTwoResolved(resolveList, startTime));
}
};
try {
getRemoteInstanceLazy(token)
- .getInstantAppIntentFilterList(hashPrefix, token, hostName, remoteCallback);
+ .getInstantAppIntentFilterList(sanitizedIntent, hashPrefix, token,
+ remoteCallback);
} catch (TimeoutException e) {
throw new ConnectionException(ConnectionException.FAILURE_BIND);
} catch (InterruptedException e) {
@@ -174,7 +166,7 @@
if (mBindState == STATE_PENDING) {
// there is a pending bind, let's see if we can use it.
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.i(TAG, "[" + token + "] Previous bind timed out; waiting for connection");
}
try {
@@ -191,7 +183,7 @@
if (mBindState == STATE_BINDING) {
// someone was binding when we called bind(), or they raced ahead while we were
// waiting in the PENDING case; wait for their result instead. Last chance!
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.i(TAG, "[" + token + "] Another thread is binding; waiting for connection");
}
waitForBindLocked(token);
@@ -209,12 +201,12 @@
IInstantAppResolver instance = null;
try {
if (doUnbind) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.i(TAG, "[" + token + "] Previous connection never established; rebinding");
}
mContext.unbindService(mServiceConnection);
}
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "[" + token + "] Binding to instant app resolver");
}
final int flags = Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE;
@@ -250,7 +242,7 @@
@Override
public void binderDied() {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Binder to instant app resolver died");
}
synchronized (mLock) {
@@ -289,7 +281,7 @@
private final class MyServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Connected to instant app resolver");
}
synchronized (mLock) {
@@ -298,7 +290,7 @@
mBindState = STATE_IDLE;
}
try {
- service.linkToDeath(EphemeralResolverConnection.this, 0 /*flags*/);
+ service.linkToDeath(InstantAppResolverConnection.this, 0 /*flags*/);
} catch (RemoteException e) {
handleBinderDiedLocked();
}
@@ -308,7 +300,7 @@
@Override
public void onServiceDisconnected(ComponentName name) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Disconnected from instant app resolver");
}
synchronized (mLock) {
@@ -317,11 +309,11 @@
}
}
- private static final class GetEphemeralResolveInfoCaller
+ private static final class GetInstantAppResolveInfoCaller
extends TimedRemoteCaller<List<InstantAppResolveInfo>> {
private final IRemoteCallback mCallback;
- public GetEphemeralResolveInfoCaller() {
+ public GetInstantAppResolveInfoCaller() {
super(CALL_SERVICE_TIMEOUT_MS);
mCallback = new IRemoteCallback.Stub() {
@Override
@@ -336,11 +328,12 @@
};
}
- public List<InstantAppResolveInfo> getEphemeralResolveInfoList(
- IInstantAppResolver target, int hashPrefix[], String token)
+ public List<InstantAppResolveInfo> getInstantAppResolveInfoList(
+ IInstantAppResolver target, Intent sanitizedIntent, int hashPrefix[], String token)
throws RemoteException, TimeoutException {
final int sequence = onBeforeRemoteCall();
- target.getInstantAppResolveInfoList(hashPrefix, token, sequence, mCallback);
+ target.getInstantAppResolveInfoList(sanitizedIntent, hashPrefix, token, sequence,
+ mCallback);
return getResultTimed(sequence);
}
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 01c44af..89fbd17 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -423,7 +423,7 @@
public static final boolean DEBUG_DEXOPT = false;
private static final boolean DEBUG_ABI_SELECTION = false;
- private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
+ private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
private static final boolean DEBUG_TRIAGED_MISSING = false;
private static final boolean DEBUG_APP_DATA = false;
@@ -582,6 +582,7 @@
sBrowserIntent.setAction(Intent.ACTION_VIEW);
sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
sBrowserIntent.setData(Uri.parse("http:"));
+ sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
}
/**
@@ -980,7 +981,7 @@
private int mIntentFilterVerificationToken = 0;
/** The service connection to the ephemeral resolver */
- final EphemeralResolverConnection mInstantAppResolverConnection;
+ final InstantAppResolverConnection mInstantAppResolverConnection;
/** Component used to show resolver settings for Instant Apps */
final ComponentName mInstantAppResolverSettingsComponent;
@@ -3148,10 +3149,10 @@
final Pair<ComponentName, String> instantAppResolverComponent =
getInstantAppResolverLPr();
if (instantAppResolverComponent != null) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
}
- mInstantAppResolverConnection = new EphemeralResolverConnection(
+ mInstantAppResolverConnection = new InstantAppResolverConnection(
mContext, instantAppResolverComponent.first,
instantAppResolverComponent.second);
mInstantAppResolverSettingsComponent =
@@ -3531,7 +3532,7 @@
final String[] packageArray =
mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
}
return null;
@@ -3546,19 +3547,9 @@
final Intent resolverIntent = new Intent(actionName);
List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
- // temporarily look for the old action
- if (resolvers.size() == 0) {
- if (DEBUG_EPHEMERAL) {
- Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
- }
- actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
- resolverIntent.setAction(actionName);
- resolvers = queryIntentServicesInternal(resolverIntent, null,
- resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
- }
final int N = resolvers.size();
if (N == 0) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
}
return null;
@@ -3574,44 +3565,53 @@
final String packageName = info.serviceInfo.packageName;
if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
+ " pkg: " + packageName + ", info:" + info);
}
continue;
}
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Ephemeral resolver found;"
+ " pkg: " + packageName + ", info:" + info);
}
return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
}
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Ephemeral resolver NOT found");
}
return null;
}
private @Nullable ActivityInfo getInstantAppInstallerLPr() {
- final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
- intent.addCategory(Intent.CATEGORY_DEFAULT);
- intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
+ String[] orderedActions = Build.IS_ENG
+ ? new String[]{
+ Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
+ Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
+ : new String[]{
+ Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
final int resolveFlags =
MATCH_DIRECT_BOOT_AWARE
- | MATCH_DIRECT_BOOT_UNAWARE
- | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
- List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
- resolveFlags, UserHandle.USER_SYSTEM);
- // temporarily look for the old action
- if (matches.isEmpty()) {
- if (DEBUG_EPHEMERAL) {
- Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
- }
- intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
+ | MATCH_DIRECT_BOOT_UNAWARE
+ | Intent.FLAG_IGNORE_EPHEMERAL
+ | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
+ final Intent intent = new Intent();
+ intent.addCategory(Intent.CATEGORY_DEFAULT);
+ intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
+ List<ResolveInfo> matches = null;
+ for (String action : orderedActions) {
+ intent.setAction(action);
matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
resolveFlags, UserHandle.USER_SYSTEM);
+ if (matches.isEmpty()) {
+ if (DEBUG_INSTANT) {
+ Slog.d(TAG, "Instant App installer not found with " + action);
+ }
+ } else {
+ break;
+ }
}
Iterator<ResolveInfo> iter = matches.iterator();
while (iter.hasNext()) {
@@ -3619,7 +3619,8 @@
final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
if (ps != null) {
final PermissionsState permissionsState = ps.getPermissionsState();
- if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
+ if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
+ || Build.IS_ENG) {
continue;
}
}
@@ -3643,15 +3644,6 @@
final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
UserHandle.USER_SYSTEM);
- // temporarily look for the old action
- if (matches.isEmpty()) {
- if (DEBUG_EPHEMERAL) {
- Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
- }
- intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
- matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
- UserHandle.USER_SYSTEM);
- }
if (matches.isEmpty()) {
return null;
}
@@ -4778,10 +4770,7 @@
flags |= PackageManager.MATCH_INSTANT;
} else {
final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
- final boolean allowMatchInstant =
- (wantInstantApps
- && Intent.ACTION_VIEW.equals(intent.getAction())
- && hasWebURI(intent))
+ final boolean allowMatchInstant = wantInstantApps
|| (wantMatchInstant && canViewInstantApps(callingUid, userId));
flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
| PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
@@ -5971,8 +5960,14 @@
if (!skipPackageCheck && intent.getPackage() != null) {
return false;
}
- final boolean isWebUri = hasWebURI(intent);
- if (!isWebUri || intent.getData().getHost() == null) {
+ if (!intent.isBrowsableWebIntent()) {
+ // for non web intents, we should not resolve externally if an app already exists to
+ // handle it or if the caller didn't explicitly request it.
+ if ((resolvedActivities != null && resolvedActivities.size() != 0)
+ || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
+ return false;
+ }
+ } else if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
return false;
}
// Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
@@ -5991,7 +5986,7 @@
final int status = (int) (packedStatus >> 32);
if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
|| status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "DENY instant app;"
+ " pkg: " + packageName + ", status: " + status);
}
@@ -5999,7 +5994,7 @@
}
}
if (ps.getInstantApp(userId)) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "DENY instant app installed;"
+ " pkg: " + packageName);
}
@@ -6370,7 +6365,7 @@
if (matches.get(i).getTargetUserId() == targetUserId) return true;
}
}
- if (hasWebURI(intent)) {
+ if (intent.hasWebURI()) {
// cross-profile app linking works only towards the parent.
final int callingUid = Binder.getCallingUid();
final UserInfo parent = getProfileParent(sourceUserId);
@@ -6545,7 +6540,7 @@
sortResult = true;
}
}
- if (hasWebURI(intent)) {
+ if (intent.hasWebURI()) {
CrossProfileDomainInfo xpDomainInfo = null;
final UserInfo parent = getProfileParent(userId);
if (parent != null) {
@@ -6631,12 +6626,11 @@
if (ps.getInstantApp(userId)) {
final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
final int status = (int)(packedStatus >> 32);
- final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
// there's a local instant application installed, but, the user has
// chosen to never use it; skip resolution and don't acknowledge
// an instant application is even available
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
}
blockResolution = true;
@@ -6644,7 +6638,7 @@
} else {
// we have a locally installed instant application; skip resolution
// but acknowledge there's an instant application available
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
}
localInstantApp = info;
@@ -6663,9 +6657,8 @@
null /*responseObj*/, intent /*origIntent*/, resolvedType,
null /*callingPackage*/, userId, null /*verificationBundle*/,
resolveForStart);
- auxiliaryResponse =
- InstantAppResolver.doInstantAppResolutionPhaseOne(
- mContext, mInstantAppResolverConnection, requestObject);
+ auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
+ mInstantAppResolverConnection, requestObject);
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
} else {
// we have an instant application locally, but, we can't admit that since
@@ -6674,35 +6667,40 @@
// instant application available externally. when it comes time to start
// the instant application, we'll do the right thing.
final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
- auxiliaryResponse = new AuxiliaryResolveInfo(
- ai.packageName, null /*splitName*/, null /*failureActivity*/,
- ai.versionCode, null /*failureIntent*/);
+ auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
+ ai.packageName, ai.versionCode, null /* splitName */);
}
}
- if (auxiliaryResponse != null) {
- if (DEBUG_EPHEMERAL) {
- Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
- }
- final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
- final PackageSetting ps =
- mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
- if (ps != null) {
- ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
- mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
- ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
- ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
- // make sure this resolver is the default
- ephemeralInstaller.isDefault = true;
- ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
- | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
- // add a non-generic filter
- ephemeralInstaller.filter = new IntentFilter(intent.getAction());
- ephemeralInstaller.filter.addDataPath(
- intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
- ephemeralInstaller.isInstantAppAvailable = true;
- result.add(ephemeralInstaller);
- }
+ if (intent.isBrowsableWebIntent() && auxiliaryResponse == null) {
+ return result;
}
+ final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
+ if (ps == null) {
+ return result;
+ }
+ final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
+ ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
+ mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
+ ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
+ | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
+ // add a non-generic filter
+ ephemeralInstaller.filter = new IntentFilter();
+ if (intent.getAction() != null) {
+ ephemeralInstaller.filter.addAction(intent.getAction());
+ }
+ if (intent.getData() != null && intent.getData().getPath() != null) {
+ ephemeralInstaller.filter.addDataPath(
+ intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
+ }
+ ephemeralInstaller.isInstantAppAvailable = true;
+ // make sure this resolver is the default
+ ephemeralInstaller.isDefault = true;
+ ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
+ if (DEBUG_INSTANT) {
+ Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
+ }
+
+ result.add(ephemeralInstaller);
return result;
}
@@ -6817,10 +6815,11 @@
final ResolveInfo info = resolveInfos.get(i);
// allow activities that are defined in the provided package
if (allowDynamicSplits
+ && info.activityInfo != null
&& info.activityInfo.splitName != null
&& !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
info.activityInfo.splitName)) {
- if (mInstantAppInstallerInfo == null) {
+ if (mInstantAppInstallerActivity == null) {
if (DEBUG_INSTALL) {
Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
}
@@ -6832,14 +6831,15 @@
if (DEBUG_INSTALL) {
Slog.v(TAG, "Adding installer to the ResolveInfo list");
}
- final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
+ final ResolveInfo installerInfo = new ResolveInfo(
+ mInstantAppInstallerInfo);
final ComponentName installFailureActivity = findInstallFailureActivity(
info.activityInfo.packageName, filterCallingUid, userId);
installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
- info.activityInfo.packageName, info.activityInfo.splitName,
installFailureActivity,
+ info.activityInfo.packageName,
info.activityInfo.applicationInfo.versionCode,
- null /*failureIntent*/);
+ info.activityInfo.splitName);
installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
| IntentFilter.MATCH_ADJUSTMENT_NORMAL;
// add a non-generic filter
@@ -6856,6 +6856,7 @@
installerInfo.priority = info.priority;
installerInfo.preferredOrder = info.preferredOrder;
installerInfo.isDefault = info.isDefault;
+ installerInfo.isInstantAppAvailable = true;
resolveInfos.set(i, installerInfo);
continue;
}
@@ -6913,17 +6914,6 @@
return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
}
- private static boolean hasWebURI(Intent intent) {
- if (intent.getData() == null) {
- return false;
- }
- final String scheme = intent.getScheme();
- if (TextUtils.isEmpty(scheme)) {
- return false;
- }
- return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
- }
-
private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
int userId) {
@@ -7593,14 +7583,16 @@
info.serviceInfo.splitName)) {
// requested service is defined in a split that hasn't been installed yet.
// add the installer to the resolve list
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
}
- final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
+ final ResolveInfo installerInfo = new ResolveInfo(
+ mInstantAppInstallerInfo);
installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
- info.serviceInfo.packageName, info.serviceInfo.splitName,
- null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode,
- null /*failureIntent*/);
+ null /* installFailureActivity */,
+ info.serviceInfo.packageName,
+ info.serviceInfo.applicationInfo.versionCode,
+ info.serviceInfo.splitName);
// make sure this resolver is the default
installerInfo.isDefault = true;
installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
@@ -7713,14 +7705,16 @@
info.providerInfo.splitName)) {
// requested provider is defined in a split that hasn't been installed yet.
// add the installer to the resolve list
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
}
- final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
+ final ResolveInfo installerInfo = new ResolveInfo(
+ mInstantAppInstallerInfo);
installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
- info.providerInfo.packageName, info.providerInfo.splitName,
- null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode,
- null /*failureIntent*/);
+ null /*failureActivity*/,
+ info.providerInfo.packageName,
+ info.providerInfo.applicationInfo.versionCode,
+ info.providerInfo.splitName);
// make sure this resolver is the default
installerInfo.isDefault = true;
installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
@@ -9991,8 +9985,7 @@
// priv-apps.
synchronized (mPackages) {
PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
- if (!pkg.packageName.equals("android")
- && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
+ if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
scanFlags |= SCAN_AS_PRIVILEGED;
}
@@ -10459,7 +10452,20 @@
pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
}
- SELinuxMMAC.assignSeInfoValue(pkg);
+ // SELinux sandboxes become more restrictive as targetSdkVersion increases.
+ // To ensure that apps with sharedUserId are placed in the same selinux domain
+ // without breaking any assumptions about access, put them into the least
+ // restrictive targetSdkVersion=25 domain.
+ // TODO(b/72290969): Base this on the actual targetSdkVersion(s) of the apps within the
+ // sharedUserSetting, instead of defaulting to the least restrictive domain.
+ final int targetSdk = (sharedUserSetting != null) ? 25
+ : pkg.applicationInfo.targetSdkVersion;
+ // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
+ // They currently can be if the sharedUser apps are signed with the platform key.
+ final boolean isPrivileged = (sharedUserSetting != null) ?
+ sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
+
+ SELinuxMMAC.assignSeInfoValue(pkg, isPrivileged, targetSdk);
pkg.mExtras = pkgSetting;
pkg.applicationInfo.processName = fixProcessName(
@@ -11776,14 +11782,14 @@
private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
if (installerActivity == null) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Clear ephemeral installer activity");
}
mInstantAppInstallerActivity = null;
return;
}
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.d(TAG, "Set ephemeral installer activity: "
+ installerActivity.getComponentName());
}
@@ -11794,7 +11800,7 @@
mInstantAppInstallerActivity.exported = true;
mInstantAppInstallerActivity.enabled = true;
mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
- mInstantAppInstallerInfo.priority = 0;
+ mInstantAppInstallerInfo.priority = 1;
mInstantAppInstallerInfo.preferredOrder = 1;
mInstantAppInstallerInfo.isDefault = true;
mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
@@ -13243,8 +13249,9 @@
private int mFlags;
}
- static final class EphemeralIntentResolver
- extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
+ static final class InstantAppIntentResolver
+ extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
+ AuxiliaryResolveInfo.AuxiliaryFilter> {
/**
* The result that has the highest defined order. Ordering applies on a
* per-package basis. Mapping is from package name to Pair of order and
@@ -13259,18 +13266,19 @@
final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
@Override
- protected AuxiliaryResolveInfo[] newArray(int size) {
- return new AuxiliaryResolveInfo[size];
+ protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
+ return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
}
@Override
- protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
+ protected boolean isPackageForFilter(String packageName,
+ AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
return true;
}
@Override
- protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
- int userId) {
+ protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
+ AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
if (!sUserManager.exists(userId)) {
return null;
}
@@ -13291,7 +13299,7 @@
}
@Override
- protected void filterResults(List<AuxiliaryResolveInfo> results) {
+ protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
// only do work if ordering is enabled [most of the time it won't be]
if (mOrderResult.size() == 0) {
return;
@@ -13611,7 +13619,7 @@
IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
String installerPackageName, int installerUid, UserHandle user,
PackageParser.SigningDetails signingDetails) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
Slog.d(TAG, "Ephemeral install of " + packageName);
}
@@ -15095,7 +15103,7 @@
pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
packageAbiOverride);
- if (DEBUG_EPHEMERAL && ephemeral) {
+ if (DEBUG_INSTANT && ephemeral) {
Slog.v(TAG, "pkgLite for install: " + pkgLite);
}
@@ -15162,7 +15170,7 @@
installFlags |= PackageManager.INSTALL_EXTERNAL;
installFlags &= ~PackageManager.INSTALL_INTERNAL;
} else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
- if (DEBUG_EPHEMERAL) {
+ if (DEBUG_INSTANT) {
Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
}
installFlags |= PackageManager.INSTALL_INSTANT_APP;
diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
index c02331d..5060c4d 100644
--- a/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
+++ b/services/core/java/com/android/server/pm/PackageManagerServiceUtils.java
@@ -693,7 +693,7 @@
InputStream fileIn = new GZIPInputStream(new FileInputStream(srcFile));
OutputStream fileOut = new FileOutputStream(dstFile, false /*append*/);
) {
- Streams.copy(fileIn, fileOut);
+ FileUtils.copy(fileIn, fileOut);
Os.chmod(dstFile.getAbsolutePath(), 0644);
return PackageManager.INSTALL_SUCCEEDED;
} catch (IOException e) {
diff --git a/services/core/java/com/android/server/pm/SELinuxMMAC.java b/services/core/java/com/android/server/pm/SELinuxMMAC.java
index fe5b3d4..a9f1528 100644
--- a/services/core/java/com/android/server/pm/SELinuxMMAC.java
+++ b/services/core/java/com/android/server/pm/SELinuxMMAC.java
@@ -315,7 +315,8 @@
*
* @param pkg object representing the package to be labeled.
*/
- public static void assignSeInfoValue(PackageParser.Package pkg) {
+ public static void assignSeInfoValue(PackageParser.Package pkg, boolean isPrivileged,
+ int targetSdkVersion) {
synchronized (sPolicies) {
if (!sPolicyRead) {
if (DEBUG_POLICY) {
@@ -335,10 +336,11 @@
if (pkg.applicationInfo.targetSandboxVersion == 2)
pkg.applicationInfo.seInfo += SANDBOX_V2_STR;
- if (pkg.applicationInfo.isPrivilegedApp())
+ if (isPrivileged) {
pkg.applicationInfo.seInfo += PRIVILEGED_APP_STR;
+ }
- pkg.applicationInfo.seInfo += TARGETSDKVERSION_STR + pkg.applicationInfo.targetSdkVersion;
+ pkg.applicationInfo.seInfo += TARGETSDKVERSION_STR + targetSdkVersion;
if (DEBUG_POLICY_INSTALL) {
Slog.i(TAG, "package (" + pkg.packageName + ") labeled with " +
diff --git a/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java b/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
index 9466350..b0b07ea 100644
--- a/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
+++ b/services/core/java/com/android/server/power/batterysaver/BatterySavingStats.java
@@ -32,6 +32,8 @@
/**
* This class keeps track of battery drain rate.
*
+ * TODO: The use of the terms "percent" and "level" in this class is not standard. Fix it.
+ *
* Test:
atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
*/
@@ -96,8 +98,12 @@
public int startBatteryLevel;
public int endBatteryLevel;
+ public int startBatteryPercent;
+ public int endBatteryPercent;
+
public long totalTimeMillis;
public int totalBatteryDrain;
+ public int totalBatteryDrainPercent;
public long totalMinutes() {
return totalTimeMillis / 60_000;
@@ -110,14 +116,26 @@
return (double) totalBatteryDrain / (totalTimeMillis / (60.0 * 60 * 1000));
}
+ public double drainPercentPerHour() {
+ if (totalTimeMillis == 0) {
+ return 0;
+ }
+ return (double) totalBatteryDrainPercent / (totalTimeMillis / (60.0 * 60 * 1000));
+ }
+
@VisibleForTesting
String toStringForTest() {
return "{" + totalMinutes() + "m," + totalBatteryDrain + ","
- + String.format("%.2f", drainPerHour()) + "}";
+ + String.format("%.2f", drainPerHour()) + "uA/H,"
+ + String.format("%.2f", drainPercentPerHour()) + "%"
+ + "}";
}
}
@VisibleForTesting
+ static final String COUNTER_POWER_PERCENT_PREFIX = "battery_saver_stats_percent_";
+
+ @VisibleForTesting
static final String COUNTER_POWER_MILLIAMPS_PREFIX = "battery_saver_stats_milliamps_";
@VisibleForTesting
@@ -166,6 +184,9 @@
private BatteryManagerInternal getBatteryManagerInternal() {
if (mBatteryManagerInternal == null) {
mBatteryManagerInternal = LocalServices.getService(BatteryManagerInternal.class);
+ if (mBatteryManagerInternal == null) {
+ Slog.wtf(TAG, "BatteryManagerInternal not initialized");
+ }
}
return mBatteryManagerInternal;
}
@@ -229,12 +250,20 @@
int injectBatteryLevel() {
final BatteryManagerInternal bmi = getBatteryManagerInternal();
if (bmi == null) {
- Slog.wtf(TAG, "BatteryManagerInternal not initialized");
return 0;
}
return bmi.getBatteryChargeCounter();
}
+ @VisibleForTesting
+ int injectBatteryPercent() {
+ final BatteryManagerInternal bmi = getBatteryManagerInternal();
+ if (bmi == null) {
+ return 0;
+ }
+ return bmi.getBatteryLevel();
+ }
+
/**
* Called from the outside whenever any of the states changes, when the device is not plugged
* in.
@@ -262,33 +291,39 @@
}
final long now = injectCurrentTime();
final int batteryLevel = injectBatteryLevel();
+ final int batteryPercent = injectBatteryPercent();
- endLastStateLocked(now, batteryLevel);
- startNewStateLocked(newState, now, batteryLevel);
- mMetricsLoggerHelper.transitionState(newState, now, batteryLevel);
+ endLastStateLocked(now, batteryLevel, batteryPercent);
+ startNewStateLocked(newState, now, batteryLevel, batteryPercent);
+ mMetricsLoggerHelper.transitionState(newState, now, batteryLevel, batteryPercent);
}
- private void endLastStateLocked(long now, int batteryLevel) {
+ private void endLastStateLocked(long now, int batteryLevel, int batteryPercent) {
if (mCurrentState < 0) {
return;
}
final Stat stat = getStat(mCurrentState);
stat.endBatteryLevel = batteryLevel;
+ stat.endBatteryPercent = batteryPercent;
stat.endTime = now;
final long deltaTime = stat.endTime - stat.startTime;
final int deltaDrain = stat.startBatteryLevel - stat.endBatteryLevel;
+ final int deltaPercent = stat.startBatteryPercent - stat.endBatteryPercent;
stat.totalTimeMillis += deltaTime;
stat.totalBatteryDrain += deltaDrain;
+ stat.totalBatteryDrainPercent += deltaPercent;
if (DEBUG) {
Slog.d(TAG, "State summary: " + stateToString(mCurrentState)
+ ": " + (deltaTime / 1_000) + "s "
+ "Start level: " + stat.startBatteryLevel + "uA "
+ "End level: " + stat.endBatteryLevel + "uA "
- + deltaDrain + "uA");
+ + "Start percent: " + stat.startBatteryPercent + "% "
+ + "End percent: " + stat.endBatteryPercent + "% "
+ + "Drain " + deltaDrain + "uA");
}
EventLogTags.writeBatterySavingStats(
BatterySaverState.fromIndex(mCurrentState),
@@ -296,12 +331,14 @@
DozeState.fromIndex(mCurrentState),
deltaTime,
deltaDrain,
+ deltaPercent,
stat.totalTimeMillis,
- stat.totalBatteryDrain);
+ stat.totalBatteryDrain,
+ stat.totalBatteryDrainPercent);
}
- private void startNewStateLocked(int newState, long now, int batteryLevel) {
+ private void startNewStateLocked(int newState, long now, int batteryLevel, int batteryPercent) {
if (DEBUG) {
Slog.d(TAG, "New state: " + stateToString(newState));
}
@@ -313,6 +350,7 @@
final Stat stat = getStat(mCurrentState);
stat.startBatteryLevel = batteryLevel;
+ stat.startBatteryPercent = batteryPercent;
stat.startTime = now;
stat.endTime = 0;
}
@@ -325,7 +363,7 @@
indent = indent + " ";
pw.print(indent);
- pw.println("Battery Saver: Off On");
+ pw.println("Battery Saver: Off On");
dumpLineLocked(pw, indent, InteractiveState.NON_INTERACTIVE, "NonIntr",
DozeState.NOT_DOZING, "NonDoze");
dumpLineLocked(pw, indent, InteractiveState.INTERACTIVE, " Intr",
@@ -357,12 +395,14 @@
final Stat offStat = getStat(BatterySaverState.OFF, interactiveState, dozeState);
final Stat onStat = getStat(BatterySaverState.ON, interactiveState, dozeState);
- pw.println(String.format("%6dm %6dmA %8.1fmA/h %6dm %6dmA %8.1fmA/h",
+ pw.println(String.format("%6dm %6dmA (%3d%%) %8.1fmA/h %6dm %6dmA (%3d%%) %8.1fmA/h",
offStat.totalMinutes(),
offStat.totalBatteryDrain / 1000,
+ offStat.totalBatteryDrainPercent,
offStat.drainPerHour() / 1000.0,
onStat.totalMinutes(),
onStat.totalBatteryDrain / 1000,
+ onStat.totalBatteryDrainPercent,
onStat.drainPerHour() / 1000.0));
}
@@ -371,12 +411,13 @@
private int mLastState = STATE_NOT_INITIALIZED;
private long mStartTime;
private int mStartBatteryLevel;
+ private int mStartPercent;
private static final int STATE_CHANGE_DETECT_MASK =
(BatterySaverState.MASK << BatterySaverState.SHIFT) |
(InteractiveState.MASK << InteractiveState.SHIFT);
- public void transitionState(int newState, long now, int batteryLevel) {
+ public void transitionState(int newState, long now, int batteryLevel, int batteryPercent) {
final boolean stateChanging =
((mLastState >= 0) ^ (newState >= 0)) ||
(((mLastState ^ newState) & STATE_CHANGE_DETECT_MASK) != 0);
@@ -384,11 +425,13 @@
if (mLastState >= 0) {
final long deltaTime = now - mStartTime;
final int deltaBattery = mStartBatteryLevel - batteryLevel;
+ final int deltaPercent = mStartPercent - batteryPercent;
- report(mLastState, deltaTime, deltaBattery);
+ report(mLastState, deltaTime, deltaBattery, deltaPercent);
}
mStartTime = now;
mStartBatteryLevel = batteryLevel;
+ mStartPercent = batteryPercent;
}
mLastState = newState;
}
@@ -405,9 +448,10 @@
}
}
- void report(int state, long deltaTimeMs, int deltaBatteryUa) {
+ void report(int state, long deltaTimeMs, int deltaBatteryUa, int deltaPercent) {
final String suffix = getCounterSuffix(state);
mMetricsLogger.count(COUNTER_POWER_MILLIAMPS_PREFIX + suffix, deltaBatteryUa / 1000);
+ mMetricsLogger.count(COUNTER_POWER_PERCENT_PREFIX + suffix, deltaPercent);
mMetricsLogger.count(COUNTER_TIME_SECONDS_PREFIX + suffix, (int) (deltaTimeMs / 1000));
}
}
diff --git a/services/core/java/com/android/server/slice/SliceFullAccessList.java b/services/core/java/com/android/server/slice/SliceFullAccessList.java
index 591e809..5e0cd03 100644
--- a/services/core/java/com/android/server/slice/SliceFullAccessList.java
+++ b/services/core/java/com/android/server/slice/SliceFullAccessList.java
@@ -63,6 +63,15 @@
pkgs.add(pkg);
}
+ public void removeGrant(String pkg, int userId) {
+ ArraySet<String> pkgs = mFullAccessPkgs.get(userId, null);
+ if (pkgs == null) {
+ pkgs = new ArraySet<>();
+ mFullAccessPkgs.put(userId, pkgs);
+ }
+ pkgs.remove(pkg);
+ }
+
public void writeXml(XmlSerializer out) throws IOException {
out.startTag(null, TAG_LIST);
out.attribute(null, ATT_VERSION, String.valueOf(DB_VERSION));
diff --git a/services/core/java/com/android/server/slice/SliceManagerService.java b/services/core/java/com/android/server/slice/SliceManagerService.java
index 5db0fc0..c4871df 100644
--- a/services/core/java/com/android/server/slice/SliceManagerService.java
+++ b/services/core/java/com/android/server/slice/SliceManagerService.java
@@ -31,9 +31,11 @@
import android.app.slice.ISliceManager;
import android.app.slice.SliceManager;
import android.app.slice.SliceSpec;
+import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
+import android.content.IntentFilter;
import android.content.pm.PackageManagerInternal;
import android.content.pm.ResolveInfo;
import android.database.ContentObserver;
@@ -92,6 +94,7 @@
private final Handler mHandler;
private final ContentObserver mObserver;
private final AtomicFile mSliceAccessFile;
+ @GuardedBy("mAccessList")
private final SliceFullAccessList mAccessList;
public SliceManagerService(Context context) {
@@ -127,11 +130,19 @@
InputStream input = mSliceAccessFile.openRead();
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(input, Encoding.UTF_8.name());
- mAccessList.readXml(parser);
+ synchronized (mAccessList) {
+ mAccessList.readXml(parser);
+ }
} catch (IOException | XmlPullParserException e) {
Slog.d(TAG, "Can't read slice access file", e);
}
}
+
+ IntentFilter filter = new IntentFilter();
+ filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
+ filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ filter.addDataScheme("package");
+ mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
}
/// ----- Lifecycle stuff -----
@@ -223,7 +234,9 @@
getContext().enforceCallingOrSelfPermission(permission.MANAGE_SLICE_PERMISSIONS,
"Slice granting requires MANAGE_SLICE_PERMISSIONS");
if (allSlices) {
- mAccessList.grantFullAccess(pkg, Binder.getCallingUserHandle().getIdentifier());
+ synchronized (mAccessList) {
+ mAccessList.grantFullAccess(pkg, Binder.getCallingUserHandle().getIdentifier());
+ }
mHandler.post(mSaveAccessList);
} else {
synchronized (mLock) {
@@ -245,6 +258,13 @@
}
/// ----- internal code -----
+ private void removeFullAccess(String pkg, int userId) {
+ synchronized (mAccessList) {
+ mAccessList.removeGrant(pkg, userId);
+ }
+ mHandler.post(mSaveAccessList);
+ }
+
protected void removePinnedSlice(Uri uri) {
synchronized (mLock) {
mPinnedSlicesByUri.remove(uri).destroy();
@@ -444,7 +464,9 @@
}
private boolean isGrantedFullAccess(String pkg, int userId) {
- return mAccessList.hasFullAccess(pkg, userId);
+ synchronized (mAccessList) {
+ return mAccessList.hasFullAccess(pkg, userId);
+ }
}
private static ServiceThread createHandler() {
@@ -469,7 +491,9 @@
try {
XmlSerializer out = XmlPullParserFactory.newInstance().newSerializer();
out.setOutput(stream, Encoding.UTF_8.name());
- mAccessList.writeXml(out);
+ synchronized (mAccessList) {
+ mAccessList.writeXml(out);
+ }
out.flush();
mSliceAccessFile.finishWrite(stream);
} catch (IOException | XmlPullParserException e) {
@@ -480,6 +504,35 @@
}
};
+ private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
+ if (userId == UserHandle.USER_NULL) {
+ Slog.w(TAG, "Intent broadcast does not contain user handle: " + intent);
+ return;
+ }
+ Uri data = intent.getData();
+ String pkg = data != null ? data.getSchemeSpecificPart() : null;
+ if (pkg == null) {
+ Slog.w(TAG, "Intent broadcast does not contain package name: " + intent);
+ return;
+ }
+ switch (intent.getAction()) {
+ case Intent.ACTION_PACKAGE_REMOVED:
+ final boolean replacing =
+ intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
+ if (!replacing) {
+ removeFullAccess(pkg, userId);
+ }
+ break;
+ case Intent.ACTION_PACKAGE_DATA_CLEARED:
+ removeFullAccess(pkg, userId);
+ break;
+ }
+ }
+ };
+
public static class Lifecycle extends SystemService {
private SliceManagerService mService;
diff --git a/services/core/java/com/android/server/stats/StatsCompanionService.java b/services/core/java/com/android/server/stats/StatsCompanionService.java
index 648fa6a..f498cdd 100644
--- a/services/core/java/com/android/server/stats/StatsCompanionService.java
+++ b/services/core/java/com/android/server/stats/StatsCompanionService.java
@@ -161,7 +161,8 @@
@Override
public void sendBroadcast(String pkg, String cls) {
- // TODO: Use a pending intent, and enfoceCallingPermission.
+ // TODO: Use a pending intent.
+ enforceCallingPermission();
mContext.sendBroadcastAsUser(new Intent(ACTION_TRIGGER_COLLECTION).setClassName(pkg, cls),
UserHandle.SYSTEM);
}
@@ -239,7 +240,7 @@
}
}
- public final static class AppUpdateReceiver extends BroadcastReceiver {
+ private final static class AppUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/**
@@ -284,7 +285,7 @@
}
}
- public final static class AnomalyAlarmReceiver extends BroadcastReceiver {
+ private final static class AnomalyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Slog.i(TAG, "StatsCompanionService believes an anomaly has occurred.");
@@ -304,7 +305,7 @@
}
}
- public final static class PullingAlarmReceiver extends BroadcastReceiver {
+ private final static class PullingAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG)
@@ -325,7 +326,7 @@
}
}
- public final static class ShutdownEventReceiver extends BroadcastReceiver {
+ private final static class ShutdownEventReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/**
diff --git a/services/core/java/com/android/server/wm/AlertWindowNotification.java b/services/core/java/com/android/server/wm/AlertWindowNotification.java
index 3f32079..b00e595 100644
--- a/services/core/java/com/android/server/wm/AlertWindowNotification.java
+++ b/services/core/java/com/android/server/wm/AlertWindowNotification.java
@@ -72,20 +72,23 @@
}
/** Cancels the notification */
- void cancel() {
+ void cancel(boolean deleteChannel) {
// We can't call into NotificationManager with WM lock held since it might call into AM.
// So, we post a message to do it later.
- mService.mH.post(this::onCancelNotification);
+ mService.mH.post(() -> onCancelNotification(deleteChannel));
}
/** Don't call with the window manager lock held! */
- private void onCancelNotification() {
+ private void onCancelNotification(boolean deleteChannel) {
if (!mPosted) {
// Notification isn't currently posted...
return;
}
mPosted = false;
mNotificationManager.cancel(mNotificationTag, NOTIFICATION_ID);
+ if (deleteChannel) {
+ mNotificationManager.deleteNotificationChannel(mNotificationTag);
+ }
}
/** Don't call with the window manager lock held! */
@@ -146,8 +149,12 @@
final String nameChannel =
context.getString(R.string.alert_windows_notification_channel_name, appName);
- final NotificationChannel channel =
- new NotificationChannel(mNotificationTag, nameChannel, IMPORTANCE_MIN);
+
+ NotificationChannel channel = mNotificationManager.getNotificationChannel(mNotificationTag);
+ if (channel != null) {
+ return;
+ }
+ channel = new NotificationChannel(mNotificationTag, nameChannel, IMPORTANCE_MIN);
channel.enableLights(false);
channel.enableVibration(false);
channel.setBlockableSystem(true);
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index 7674b5e..bd3f302d 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -662,7 +662,7 @@
mWallpaperController.updateWallpaperVisibility();
}
- w.handleWindowMovedIfNeeded(mPendingTransaction);
+ w.handleWindowMovedIfNeeded();
final WindowStateAnimator winAnimator = w.mWinAnimator;
@@ -3599,8 +3599,6 @@
}
private final class AboveAppWindowContainers extends NonAppWindowContainers {
- private final Dimmer mDimmer = new Dimmer(this);
- private final Rect mTmpDimBoundsRect = new Rect();
AboveAppWindowContainers(String name, WindowManagerService service) {
super(name, service);
}
@@ -3632,22 +3630,6 @@
imeContainer.assignRelativeLayer(t, getSurfaceControl(), Integer.MAX_VALUE);
}
}
-
- @Override
- Dimmer getDimmer() {
- return mDimmer;
- }
-
- @Override
- void prepareSurfaces() {
- mDimmer.resetDimStates();
- super.prepareSurfaces();
- getBounds(mTmpDimBoundsRect);
-
- if (mDimmer.updateDims(getPendingTransaction(), mTmpDimBoundsRect)) {
- scheduleAnimation();
- }
- }
}
/**
@@ -3679,6 +3661,9 @@
};
private final String mName;
+ private final Dimmer mDimmer = new Dimmer(this);
+ private final Rect mTmpDimBoundsRect = new Rect();
+
NonAppWindowContainers(String name, WindowManagerService service) {
super(service);
mName = name;
@@ -3722,6 +3707,22 @@
String getName() {
return mName;
}
+
+ @Override
+ Dimmer getDimmer() {
+ return mDimmer;
+ }
+
+ @Override
+ void prepareSurfaces() {
+ mDimmer.resetDimStates();
+ super.prepareSurfaces();
+ getBounds(mTmpDimBoundsRect);
+
+ if (mDimmer.updateDims(getPendingTransaction(), mTmpDimBoundsRect)) {
+ scheduleAnimation();
+ }
+ }
}
private class NonMagnifiableWindowContainers extends NonAppWindowContainers {
diff --git a/services/core/java/com/android/server/wm/RemoteAnimationController.java b/services/core/java/com/android/server/wm/RemoteAnimationController.java
index 8269a3b..5bc739e 100644
--- a/services/core/java/com/android/server/wm/RemoteAnimationController.java
+++ b/services/core/java/com/android/server/wm/RemoteAnimationController.java
@@ -92,14 +92,21 @@
onAnimationFinished();
return;
}
- mHandler.postDelayed(mTimeoutRunnable, TIMEOUT_MS);
- try {
- mRemoteAnimationAdapter.getRunner().onAnimationStart(createAnimations(),
- mFinishedCallback);
- } catch (RemoteException e) {
- Slog.e(TAG, "Failed to start remote animation", e);
- onAnimationFinished();
- }
+
+ // Scale the timeout with the animator scale the controlling app is using.
+ mHandler.postDelayed(mTimeoutRunnable,
+ (long) (TIMEOUT_MS * mService.getCurrentAnimatorScale()));
+
+ final RemoteAnimationTarget[] animations = createAnimations();
+ mService.mAnimator.addAfterPrepareSurfacesRunnable(() -> {
+ try {
+ mRemoteAnimationAdapter.getRunner().onAnimationStart(animations,
+ mFinishedCallback);
+ } catch (RemoteException e) {
+ Slog.e(TAG, "Failed to start remote animation", e);
+ onAnimationFinished();
+ }
+ });
}
private RemoteAnimationTarget[] createAnimations() {
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index deed7f1..4b7cea7 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -599,6 +599,8 @@
"<<< CLOSE TRANSACTION performLayoutAndPlaceSurfaces");
}
+ mService.mAnimator.executeAfterPrepareSurfacesRunnables();
+
final WindowSurfacePlacer surfacePlacer = mService.mWindowPlacerLocked;
// If we are ready to perform an app transition, check through all of the app tokens to be
@@ -903,10 +905,26 @@
boolean handleNotObscuredLocked(WindowState w, boolean obscured, boolean syswin) {
final WindowManager.LayoutParams attrs = w.mAttrs;
final int attrFlags = attrs.flags;
+ final boolean onScreen = w.isOnScreen();
final boolean canBeSeen = w.isDisplayedLw();
final int privateflags = attrs.privateFlags;
boolean displayHasContent = false;
+ if (DEBUG_KEEP_SCREEN_ON) {
+ Slog.d(TAG_KEEP_SCREEN_ON, "handleNotObscuredLocked w: " + w
+ + ", w.mHasSurface: " + w.mHasSurface
+ + ", w.isOnScreen(): " + onScreen
+ + ", w.isDisplayedLw(): " + w.isDisplayedLw()
+ + ", w.mAttrs.userActivityTimeout: " + w.mAttrs.userActivityTimeout);
+ }
+ if (w.mHasSurface && onScreen) {
+ if (!syswin && w.mAttrs.userActivityTimeout >= 0 && mUserActivityTimeout < 0) {
+ mUserActivityTimeout = w.mAttrs.userActivityTimeout;
+ if (DEBUG_KEEP_SCREEN_ON) {
+ Slog.d(TAG, "mUserActivityTimeout set to " + mUserActivityTimeout);
+ }
+ }
+ }
if (w.mHasSurface && canBeSeen) {
if ((attrFlags & FLAG_KEEP_SCREEN_ON) != 0) {
mHoldScreen = w.mSession;
@@ -919,9 +937,6 @@
if (!syswin && w.mAttrs.screenBrightness >= 0 && mScreenBrightness < 0) {
mScreenBrightness = w.mAttrs.screenBrightness;
}
- if (!syswin && w.mAttrs.userActivityTimeout >= 0 && mUserActivityTimeout < 0) {
- mUserActivityTimeout = w.mAttrs.userActivityTimeout;
- }
final int type = attrs.type;
// This function assumes that the contents of the default display are processed first
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index 04ae38e..f09a294 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -547,7 +547,7 @@
if (allowed) {
mAlertWindowNotification.post();
} else {
- mAlertWindowNotification.cancel();
+ mAlertWindowNotification.cancel(false /* deleteChannel */);
}
}
}
@@ -586,7 +586,7 @@
if (mAlertWindowNotification == null) {
return;
}
- mAlertWindowNotification.cancel();
+ mAlertWindowNotification.cancel(true /* deleteChannel */);
mAlertWindowNotification = null;
}
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index ae5341b..a0d1480 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -21,6 +21,7 @@
import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
+import static android.app.WindowConfiguration.PINNED_WINDOWING_MODE_ELEVATION_IN_DIP;
import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET;
import static android.content.res.Configuration.DENSITY_DPI_UNDEFINED;
@@ -53,6 +54,7 @@
import android.graphics.Rect;
import android.graphics.Region;
import android.os.RemoteException;
+import android.util.DisplayMetrics;
import android.util.EventLog;
import android.util.Slog;
import android.util.SparseArray;
@@ -741,14 +743,32 @@
scheduleAnimation();
}
+ /**
+ * Calculate an amount by which to expand the stack bounds in each direction.
+ * Used to make room for shadows in the pinned windowing mode.
+ */
+ int getStackOutset() {
+ if (inPinnedWindowingMode()) {
+ final DisplayMetrics displayMetrics = getDisplayContent().getDisplayMetrics();
+ return mService.dipToPixel(PINNED_WINDOWING_MODE_ELEVATION_IN_DIP,
+ displayMetrics);
+ }
+ return 0;
+ }
+
private void updateSurfaceSize(SurfaceControl.Transaction transaction) {
if (mSurfaceControl == null) {
return;
}
final Rect stackBounds = getBounds();
- final int width = stackBounds.width();
- final int height = stackBounds.height();
+ int width = stackBounds.width();
+ int height = stackBounds.height();
+
+ final int outset = getStackOutset();
+ width += 2*outset;
+ height += 2*outset;
+
if (width == mLastSurfaceSize.x && height == mLastSurfaceSize.y) {
return;
}
@@ -1749,4 +1769,12 @@
mDimmer.stopDim(getPendingTransaction());
scheduleAnimation();
}
+
+ @Override
+ void getRelativePosition(Point outPos) {
+ super.getRelativePosition(outPos);
+ final int outset = getStackOutset();
+ outPos.x -= outset;
+ outPos.y -= outset;
+ }
}
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index cec13ab..b0d42f2 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -92,6 +92,7 @@
* executed and the corresponding transaction is closed and applied.
*/
private final ArrayList<Runnable> mAfterPrepareSurfacesRunnables = new ArrayList<>();
+ private boolean mInExecuteAfterPrepareSurfacesRunnables;
WindowAnimator(final WindowManagerService service) {
mService = service;
@@ -438,7 +439,13 @@
scheduleAnimation();
}
- private void executeAfterPrepareSurfacesRunnables() {
+ void executeAfterPrepareSurfacesRunnables() {
+
+ // Don't even think about to start recursing!
+ if (mInExecuteAfterPrepareSurfacesRunnables) {
+ return;
+ }
+ mInExecuteAfterPrepareSurfacesRunnables = true;
// Traverse in order they were added.
final int size = mAfterPrepareSurfacesRunnables.size();
@@ -446,5 +453,6 @@
mAfterPrepareSurfacesRunnables.get(i).run();
}
mAfterPrepareSurfacesRunnables.clear();
+ mInExecuteAfterPrepareSurfacesRunnables = false;
}
}
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 53a8d82..a9f2e03 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -1758,7 +1758,7 @@
* listeners and optionally animate it. Simply checking a change of position is not enough,
* because being move due to dock divider is not a trigger for animation.
*/
- void handleWindowMovedIfNeeded(Transaction t) {
+ void handleWindowMovedIfNeeded() {
if (!hasMoved()) {
return;
}
@@ -1776,7 +1776,7 @@
&& !isDragResizing() && !adjustedForMinimizedDockOrIme
&& getWindowConfiguration().hasMovementAnimations()
&& !mWinAnimator.mLastHidden) {
- startMoveAnimation(t, left, top);
+ startMoveAnimation(left, top);
}
//TODO (multidisplay): Accessibility supported only for the default display.
@@ -4360,7 +4360,7 @@
commitPendingTransaction();
}
- private void startMoveAnimation(Transaction t, int left, int top) {
+ private void startMoveAnimation(int left, int top) {
if (DEBUG_ANIM) Slog.v(TAG, "Setting move animation on " + this);
final Point oldPosition = new Point();
final Point newPosition = new Point();
@@ -4369,7 +4369,7 @@
final AnimationAdapter adapter = new LocalAnimationAdapter(
new MoveAnimationSpec(oldPosition.x, oldPosition.y, newPosition.x, newPosition.y),
mService.mSurfaceAnimationRunner);
- startAnimation(t, adapter);
+ startAnimation(getPendingTransaction(), adapter);
}
private void startAnimation(Transaction t, AnimationAdapter adapter) {
@@ -4576,6 +4576,17 @@
outPoint.offset(-parentBounds.left, -parentBounds.top);
}
+ TaskStack stack = getStack();
+
+ // If we have stack outsets, that means the top-left
+ // will be outset, and we need to inset ourselves
+ // to account for it. If we actually have shadows we will
+ // then un-inset ourselves by the surfaceInsets.
+ if (stack != null) {
+ final int outset = stack.getStackOutset();
+ outPoint.offset(outset, outset);
+ }
+
// Expand for surface insets. See WindowState.expandForSurfaceInsets.
outPoint.offset(-mAttrs.surfaceInsets.left, -mAttrs.surfaceInsets.top);
}
diff --git a/services/core/java/com/android/server/wm/WindowStateAnimator.java b/services/core/java/com/android/server/wm/WindowStateAnimator.java
index 1cfa956..5c9cfbb 100644
--- a/services/core/java/com/android/server/wm/WindowStateAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowStateAnimator.java
@@ -99,7 +99,6 @@
// Unchanging local convenience fields.
final WindowManagerService mService;
final WindowState mWin;
- private final WindowStateAnimator mParentWinAnimator;
final WindowAnimator mAnimator;
final Session mSession;
final WindowManagerPolicy mPolicy;
@@ -135,8 +134,6 @@
float mAlpha = 0;
float mLastAlpha = 0;
- boolean mHasClipRect;
- Rect mClipRect = new Rect();
Rect mTmpClipRect = new Rect();
Rect mTmpFinalClipRect = new Rect();
Rect mLastClipRect = new Rect();
@@ -150,7 +147,6 @@
* system decorations.
*/
private final Rect mSystemDecorRect = new Rect();
- private final Rect mLastSystemDecorRect = new Rect();
float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
private float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
@@ -224,7 +220,6 @@
mContext = service.mContext;
mWin = win;
- mParentWinAnimator = !win.isChildWindow() ? null : win.getParentWindow().mWinAnimator;
mSession = win.mSession;
mAttrType = win.mAttrs.type;
mIsWallpaper = win.mIsWallpaper;
@@ -455,9 +450,6 @@
}
// We may abort, so initialize to defaults.
- mLastSystemDecorRect.set(0, 0, 0, 0);
- mHasClipRect = false;
- mClipRect.set(0, 0, 0, 0);
mLastClipRect.set(0, 0, 0, 0);
// Set up surface control with initial size.
@@ -649,14 +641,12 @@
}
void computeShownFrameLocked() {
-
final int displayId = mWin.getDisplayId();
final ScreenRotationAnimation screenRotationAnimation =
mAnimator.getScreenRotationAnimationLocked(displayId);
final boolean screenAnimation =
screenRotationAnimation != null && screenRotationAnimation.isAnimating();
- mHasClipRect = false;
if (screenAnimation) {
// cache often used attributes locally
final Rect frame = mWin.mFrame;
@@ -796,9 +786,9 @@
// We use the clip rect as provided by the tranformation for non-fullscreen windows to
// avoid premature clipping with the system decor rect.
- clipRect.set((mHasClipRect && !fullscreen) ? mClipRect : mSystemDecorRect);
+ clipRect.set(mSystemDecorRect);
if (DEBUG_WINDOW_CROP) Slog.d(TAG, "win=" + w + " Initial clip rect: " + clipRect
- + " mHasClipRect=" + mHasClipRect + " fullscreen=" + fullscreen);
+ + " fullscreen=" + fullscreen);
if (isFreeformResizing && !w.isChildWindow()) {
// For freeform resizing non child windows, we are using the big surface positioned
@@ -808,12 +798,6 @@
w.expandForSurfaceInsets(clipRect);
- if (mHasClipRect && fullscreen) {
- // We intersect the clip rect specified by the transformation with the expanded system
- // decor rect to prevent artifacts from drawing during animation if the transformation
- // clip rect extends outside the system decor rect.
- clipRect.intersect(mClipRect);
- }
// The clip rect was generated assuming (0,0) as the window origin,
// so we need to translate to match the actual surface coordinates.
clipRect.offset(w.mAttrs.surfaceInsets.left, w.mAttrs.surfaceInsets.top);
@@ -1378,8 +1362,6 @@
pw.print(prefix); pw.print("mDrawState="); pw.print(drawStateToString());
pw.print(prefix); pw.print(" mLastHidden="); pw.println(mLastHidden);
pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
- pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
- pw.print(" mHasClipRect="); pw.print(mHasClipRect);
pw.print(" mLastClipRect="); mLastClipRect.printShortString(pw);
if (!mLastFinalClipRect.isEmpty()) {
diff --git a/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java
new file mode 100644
index 0000000..8502e69
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java
@@ -0,0 +1,443 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.display;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import android.hardware.display.AmbientBrightnessDayStats;
+import android.os.SystemClock;
+import android.os.UserManager;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDate;
+import java.util.ArrayList;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class AmbientBrightnessStatsTrackerTest {
+
+ private TestInjector mTestInjector;
+
+ @Before
+ public void setUp() {
+ mTestInjector = new TestInjector();
+ }
+
+ @Test
+ public void testBrightnessStatsTrackerOverSingleDay() {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ float[] expectedStats;
+ // Test case where no user data
+ userStats = statsTracker.getUserStats(0);
+ assertNull(userStats);
+ // Test after adding some user data
+ statsTracker.start();
+ statsTracker.add(0, 0);
+ mTestInjector.incrementTime(1000);
+ statsTracker.stop();
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(1, userStats.size());
+ assertEquals(mTestInjector.getLocalDate(), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 1;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ // Test after adding some more user data
+ statsTracker.start();
+ statsTracker.add(0, 0.05f);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 0.2f);
+ mTestInjector.incrementTime(1500);
+ statsTracker.add(0, 50000);
+ mTestInjector.incrementTime(2500);
+ statsTracker.stop();
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(1, userStats.size());
+ assertEquals(mTestInjector.getLocalDate(), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 2;
+ expectedStats[1] = 1.5f;
+ expectedStats[11] = 2.5f;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ }
+
+ @Test
+ public void testBrightnessStatsTrackerOverMultipleDays() {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ float[] expectedStats;
+ // Add data for day 1
+ statsTracker.start();
+ statsTracker.add(0, 0.05f);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 0.2f);
+ mTestInjector.incrementTime(1500);
+ statsTracker.add(0, 1);
+ mTestInjector.incrementTime(2500);
+ statsTracker.stop();
+ // Add data for day 2
+ mTestInjector.incrementDate(1);
+ statsTracker.start();
+ statsTracker.add(0, 0);
+ mTestInjector.incrementTime(3500);
+ statsTracker.add(0, 5);
+ mTestInjector.incrementTime(5000);
+ statsTracker.stop();
+ // Test that the data is tracked as expected
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(2, userStats.size());
+ assertEquals(mTestInjector.getLocalDate().minusDays(1), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 1;
+ expectedStats[1] = 1.5f;
+ expectedStats[3] = 2.5f;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ assertEquals(mTestInjector.getLocalDate(), userStats.get(1).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 3.5f;
+ expectedStats[4] = 5;
+ assertArrayEquals(expectedStats, userStats.get(1).getStats(), 0);
+ }
+
+ @Test
+ public void testBrightnessStatsTrackerOverMultipleUsers() {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ float[] expectedStats;
+ // Add data for user 1
+ statsTracker.start();
+ statsTracker.add(0, 0.05f);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 0.2f);
+ mTestInjector.incrementTime(1500);
+ statsTracker.add(0, 1);
+ mTestInjector.incrementTime(2500);
+ statsTracker.stop();
+ // Add data for user 2
+ mTestInjector.incrementDate(1);
+ statsTracker.start();
+ statsTracker.add(1, 0);
+ mTestInjector.incrementTime(3500);
+ statsTracker.add(1, 5);
+ mTestInjector.incrementTime(5000);
+ statsTracker.stop();
+ // Test that the data is tracked as expected
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(1, userStats.size());
+ assertEquals(mTestInjector.getLocalDate().minusDays(1), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 1;
+ expectedStats[1] = 1.5f;
+ expectedStats[3] = 2.5f;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ userStats = statsTracker.getUserStats(1);
+ assertEquals(1, userStats.size());
+ assertEquals(mTestInjector.getLocalDate(), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 3.5f;
+ expectedStats[4] = 5;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ }
+
+ @Test
+ public void testBrightnessStatsTrackerOverMaxDays() {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ // Add 10 extra days of data over the buffer limit
+ for (int i = 0; i < AmbientBrightnessStatsTracker.MAX_DAYS_TO_TRACK + 10; i++) {
+ mTestInjector.incrementDate(1);
+ statsTracker.start();
+ statsTracker.add(0, 10);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 20);
+ mTestInjector.incrementTime(1000);
+ statsTracker.stop();
+ }
+ // Assert that we are only tracking last "MAX_DAYS_TO_TRACK"
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(AmbientBrightnessStatsTracker.MAX_DAYS_TO_TRACK, userStats.size());
+ LocalDate runningDate = mTestInjector.getLocalDate();
+ for (int i = AmbientBrightnessStatsTracker.MAX_DAYS_TO_TRACK - 1; i >= 0; i--) {
+ assertEquals(runningDate, userStats.get(i).getLocalDate());
+ runningDate = runningDate.minusDays(1);
+ }
+ }
+
+ @Test
+ public void testReadAmbientBrightnessStats() throws IOException {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ LocalDate date = mTestInjector.getLocalDate();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ String statsFile =
+ "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\r\n"
+ + "<ambient-brightness-stats>\r\n"
+ // Old stats that shouldn't be read
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\""
+ + date.minusDays(AmbientBrightnessStatsTracker.MAX_DAYS_TO_TRACK)
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"1.088,0.0,0.726,0.0,25.868,0.0,0.0,"
+ + "0.0,0.0,0.0\" />\r\n"
+ // Valid stats that should get read
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\""
+ + date.minusDays(1)
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"1.088,0.0,0.726,0.0,25.868,0.0,0.0,"
+ + "0.0,0.0,0.0\" />\r\n"
+ // Valid stats that should get read
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\"" + date
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"0.0,0.0,0.0,0.0,4.482,0.0,0.0,0.0,0.0,"
+ + "0.0\" />\r\n"
+ + "</ambient-brightness-stats>";
+ statsTracker.readStats(getInputStream(statsFile));
+ userStats = statsTracker.getUserStats(0);
+ assertEquals(2, userStats.size());
+ assertEquals(new AmbientBrightnessDayStats(date.minusDays(1),
+ new float[]{0, 1, 3, 10, 30, 100, 300, 1000, 3000, 10000},
+ new float[]{1.088f, 0, 0.726f, 0, 25.868f, 0, 0, 0, 0, 0}), userStats.get(0));
+ assertEquals(new AmbientBrightnessDayStats(date,
+ new float[]{0, 1, 3, 10, 30, 100, 300, 1000, 3000, 10000},
+ new float[]{0, 0, 0, 0, 4.482f, 0, 0, 0, 0, 0}), userStats.get(1));
+ }
+
+ @Test
+ public void testFailedReadAmbientBrightnessStatsWithException() {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ LocalDate date = mTestInjector.getLocalDate();
+ String statsFile;
+ // Test with parse error
+ statsFile =
+ "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\r\n"
+ + "<ambient-brightness-stats>\r\n"
+ // Incorrect since bucket boundaries not parsable
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\"" + date
+ + "\" bucket-boundaries=\"asdf,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"1.088,0.0,0.726,0.0,25.868,0.0,0.0,"
+ + "0.0,0.0,0.0\" />\r\n"
+ + "</ambient-brightness-stats>";
+ try {
+ statsTracker.readStats(getInputStream(statsFile));
+ } catch (IOException e) {
+ // Expected
+ }
+ assertNull(statsTracker.getUserStats(0));
+ // Test with incorrect data (bucket boundaries length not equal to stats length)
+ statsFile =
+ "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\r\n"
+ + "<ambient-brightness-stats>\r\n"
+ // Correct data
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\""
+ + date.minusDays(1)
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"0.0,0.0,0.0,0.0,4.482,0.0,0.0,0.0,0.0,"
+ + "0.0\" />\r\n"
+ // Incorrect data
+ + "<ambient-brightness-day-stats user=\"10\" local-date=\"" + date
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,1000.0,"
+ + "3000.0,10000.0\" bucket-stats=\"1.088,0.0,0.726,0.0,25.868,0.0,0.0,"
+ + "0.0,0.0,0.0\" />\r\n"
+ + "</ambient-brightness-stats>";
+ try {
+ statsTracker.readStats(getInputStream(statsFile));
+ } catch (Exception e) {
+ // Expected
+ }
+ assertNull(statsTracker.getUserStats(0));
+ // Test with missing attribute
+ statsFile =
+ "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\r\n"
+ + "<ambient-brightness-stats>\r\n"
+ + "<ambientBrightnessDayStats user=\"10\" local-date=\"" + date
+ + "\" bucket-boundaries=\"0.0,1.0,3.0,10.0,30.0,100.0,300.0,1000.0,"
+ + "3000.0,10000.0\" />\r\n"
+ + "</ambient-brightness-stats>";
+ try {
+ statsTracker.readStats(getInputStream(statsFile));
+ } catch (Exception e) {
+ // Expected
+ }
+ assertNull(statsTracker.getUserStats(0));
+ }
+
+ @Test
+ public void testWriteThenReadAmbientBrightnessStats() throws IOException {
+ AmbientBrightnessStatsTracker statsTracker = getTestStatsTracker();
+ ArrayList<AmbientBrightnessDayStats> userStats;
+ float[] expectedStats;
+ // Generate some dummy data
+ // Data: very old which should not be read
+ statsTracker.start();
+ statsTracker.add(0, 0.05f);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 0.2f);
+ mTestInjector.incrementTime(1500);
+ statsTracker.add(0, 1);
+ mTestInjector.incrementTime(2500);
+ statsTracker.stop();
+ // Data: day 1 user 1
+ mTestInjector.incrementDate(AmbientBrightnessStatsTracker.MAX_DAYS_TO_TRACK - 1);
+ statsTracker.start();
+ statsTracker.add(0, 0.05f);
+ mTestInjector.incrementTime(1000);
+ statsTracker.add(0, 0.2f);
+ mTestInjector.incrementTime(1500);
+ statsTracker.add(0, 1);
+ mTestInjector.incrementTime(2500);
+ statsTracker.stop();
+ // Data: day 1 user 2
+ statsTracker.start();
+ statsTracker.add(1, 0);
+ mTestInjector.incrementTime(3500);
+ statsTracker.add(1, 5);
+ mTestInjector.incrementTime(5000);
+ statsTracker.stop();
+ // Data: day 2 user 1
+ mTestInjector.incrementDate(1);
+ statsTracker.start();
+ statsTracker.add(0, 0);
+ mTestInjector.incrementTime(3500);
+ statsTracker.add(0, 50000);
+ mTestInjector.incrementTime(5000);
+ statsTracker.stop();
+ // Write them
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ statsTracker.writeStats(baos);
+ baos.flush();
+ // Read them back and assert that it's the same
+ ByteArrayInputStream input = new ByteArrayInputStream(baos.toByteArray());
+ AmbientBrightnessStatsTracker newStatsTracker = getTestStatsTracker();
+ newStatsTracker.readStats(input);
+ userStats = newStatsTracker.getUserStats(0);
+ assertEquals(2, userStats.size());
+ // Check day 1 user 1
+ assertEquals(mTestInjector.getLocalDate().minusDays(1), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 1;
+ expectedStats[1] = 1.5f;
+ expectedStats[3] = 2.5f;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ // Check day 2 user 1
+ assertEquals(mTestInjector.getLocalDate(), userStats.get(1).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 3.5f;
+ expectedStats[11] = 5;
+ assertArrayEquals(expectedStats, userStats.get(1).getStats(), 0);
+ userStats = newStatsTracker.getUserStats(1);
+ assertEquals(1, userStats.size());
+ // Check day 1 user 2
+ assertEquals(mTestInjector.getLocalDate().minusDays(1), userStats.get(0).getLocalDate());
+ expectedStats = getEmptyStatsArray();
+ expectedStats[0] = 3.5f;
+ expectedStats[4] = 5;
+ assertArrayEquals(expectedStats, userStats.get(0).getStats(), 0);
+ }
+
+ @Test
+ public void testTimer() {
+ AmbientBrightnessStatsTracker.Timer timer = new AmbientBrightnessStatsTracker.Timer(
+ () -> mTestInjector.elapsedRealtimeMillis());
+ assertEquals(0, timer.totalDurationSec(), 0);
+ mTestInjector.incrementTime(1000);
+ assertEquals(0, timer.totalDurationSec(), 0);
+ assertFalse(timer.isRunning());
+ // Start timer
+ timer.start();
+ assertTrue(timer.isRunning());
+ assertEquals(0, timer.totalDurationSec(), 0);
+ mTestInjector.incrementTime(1000);
+ assertTrue(timer.isRunning());
+ assertEquals(1, timer.totalDurationSec(), 0);
+ // Reset timer
+ timer.reset();
+ assertEquals(0, timer.totalDurationSec(), 0);
+ assertFalse(timer.isRunning());
+ // Start again
+ timer.start();
+ assertTrue(timer.isRunning());
+ assertEquals(0, timer.totalDurationSec(), 0);
+ mTestInjector.incrementTime(2000);
+ assertTrue(timer.isRunning());
+ assertEquals(2, timer.totalDurationSec(), 0);
+ // Reset again
+ timer.reset();
+ assertEquals(0, timer.totalDurationSec(), 0);
+ assertFalse(timer.isRunning());
+ }
+
+ private class TestInjector extends AmbientBrightnessStatsTracker.Injector {
+
+ private long mElapsedRealtimeMillis = SystemClock.elapsedRealtime();
+ private LocalDate mLocalDate = LocalDate.now();
+
+ public void incrementTime(long timeMillis) {
+ mElapsedRealtimeMillis += timeMillis;
+ }
+
+ public void incrementDate(int numDays) {
+ mLocalDate = mLocalDate.plusDays(numDays);
+ }
+
+ @Override
+ public long elapsedRealtimeMillis() {
+ return mElapsedRealtimeMillis;
+ }
+
+ @Override
+ public int getUserSerialNumber(UserManager userManager, int userId) {
+ return userId + 10;
+ }
+
+ @Override
+ public int getUserId(UserManager userManager, int userSerialNumber) {
+ return userSerialNumber - 10;
+ }
+
+ @Override
+ public LocalDate getLocalDate() {
+ return LocalDate.from(mLocalDate);
+ }
+ }
+
+ private AmbientBrightnessStatsTracker getTestStatsTracker() {
+ return new AmbientBrightnessStatsTracker(
+ InstrumentationRegistry.getContext().getSystemService(UserManager.class),
+ mTestInjector);
+ }
+
+ private float[] getEmptyStatsArray() {
+ return new float[AmbientBrightnessStatsTracker.BUCKET_BOUNDARIES_FOR_NEW_STATS.length];
+ }
+
+ private InputStream getInputStream(String data) {
+ return new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java b/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
index edc7d74..501f966 100644
--- a/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/BrightnessTrackerTest.java
@@ -30,7 +30,6 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
-import android.database.ContentObserver;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.display.BrightnessChangeEvent;
@@ -195,7 +194,9 @@
mInjector.incrementTime(TimeUnit.SECONDS.toMillis(1));
final int systemUpdatedBrightness = 20;
- notifyBrightnessChanged(mTracker, systemUpdatedBrightness, false /*userInitiated*/);
+ notifyBrightnessChanged(mTracker, systemUpdatedBrightness, false /*userInitiated*/,
+ 0.5f /*powerBrightnessFactor(*/, false /*isUserSetBrightness*/,
+ false /*isDefaultBrightnessConfig*/);
List<BrightnessChangeEvent> events = mTracker.getEvents(0, true).getList();
// No events because we filtered out our change.
assertEquals(0, events.size());
@@ -285,7 +286,8 @@
+ "lastNits=\"32.333\" "
+ "batteryLevel=\"1.0\" nightMode=\"false\" colorTemperature=\"0\"\n"
+ "lux=\"32.2,31.1\" luxTimestamps=\""
- + Long.toString(someTimeAgo) + "," + Long.toString(someTimeAgo) + "\"/>"
+ + Long.toString(someTimeAgo) + "," + Long.toString(someTimeAgo) + "\""
+ + "defaultConfig=\"true\" powerSaveFactor=\"0.5\" userPoint=\"true\" />"
+ "<event nits=\"71\" timestamp=\""
+ Long.toString(someTimeAgo) + "\" packageName=\""
+ "com.android.anapp\" user=\"11\" "
@@ -315,6 +317,9 @@
assertFalse(event.nightMode);
assertEquals(1.0f, event.batteryLevel, FLOAT_DELTA);
assertEquals("com.example.app", event.packageName);
+ assertTrue(event.isDefaultBrightnessConfig);
+ assertEquals(0.5f, event.powerBrightnessFactor, FLOAT_DELTA);
+ assertTrue(event.isUserSetBrightness);
events = tracker.getEvents(1, true).getList();
assertEquals(1, events.size());
@@ -329,6 +334,10 @@
assertEquals(3235, event.colorTemperature);
assertEquals(0.5f, event.batteryLevel, FLOAT_DELTA);
assertEquals("com.android.anapp", event.packageName);
+ // Not present in the event so default to false.
+ assertFalse(event.isDefaultBrightnessConfig);
+ assertEquals(1.0, event.powerBrightnessFactor, FLOAT_DELTA);
+ assertFalse(event.isUserSetBrightness);
}
@Test
@@ -379,7 +388,9 @@
mInjector.mSensorListener.onSensorChanged(createSensorEvent(3000.0f));
final long secondSensorTime = mInjector.currentTimeMillis();
mInjector.incrementTime(TimeUnit.SECONDS.toMillis(3));
- notifyBrightnessChanged(mTracker, brightness);
+ notifyBrightnessChanged(mTracker, brightness, true /*userInitiated*/,
+ 0.5f /*powerPolicyDim(*/, true /*hasUserBrightnessPoints*/,
+ false /*isDefaultBrightnessConfig*/);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mTracker.writeEventsLocked(baos);
mTracker.stop();
@@ -399,6 +410,9 @@
assertEquals(0.3, event.batteryLevel, FLOAT_DELTA);
assertTrue(event.nightMode);
assertEquals(3339, event.colorTemperature);
+ assertEquals(0.5f, event.powerBrightnessFactor, FLOAT_DELTA);
+ assertTrue(event.isUserSetBrightness);
+ assertFalse(event.isDefaultBrightnessConfig);
}
@Test
@@ -539,12 +553,16 @@
}
private void notifyBrightnessChanged(BrightnessTracker tracker, float brightness) {
- notifyBrightnessChanged(tracker, brightness, true /*userInitiated*/);
+ notifyBrightnessChanged(tracker, brightness, true /*userInitiated*/,
+ 1.0f /*powerBrightnessFactor*/, false /*isUserSetBrightness*/,
+ false /*isDefaultBrightnessConfig*/);
}
private void notifyBrightnessChanged(BrightnessTracker tracker, float brightness,
- boolean userInitiated) {
- tracker.notifyBrightnessChanged(brightness, userInitiated);
+ boolean userInitiated, float powerBrightnessFactor, boolean isUserSetBrightness,
+ boolean isDefaultBrightnessConfig) {
+ tracker.notifyBrightnessChanged(brightness, userInitiated, powerBrightnessFactor,
+ isUserSetBrightness, isDefaultBrightnessConfig);
mInjector.waitForHandler();
}
@@ -573,7 +591,6 @@
private class TestInjector extends BrightnessTracker.Injector {
SensorEventListener mSensorListener;
BroadcastReceiver mBroadcastReceiver;
- Map<String, Integer> mSystemIntSettings = new HashMap<>();
Map<String, Integer> mSecureIntSettings = new HashMap<>();
long mCurrentTimeMillis = System.currentTimeMillis();
long mElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos();
@@ -639,7 +656,7 @@
}
@Override
- public AtomicFile getFile() {
+ public AtomicFile getFile(String filename) {
// Don't have the test write / read from anywhere.
return null;
}
diff --git a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
index c3714c8..f7516b2 100644
--- a/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
+++ b/services/tests/servicestests/src/com/android/server/power/batterysaver/BatterySavingStatsTest.java
@@ -63,6 +63,11 @@
return mBatteryLevel;
}
+ @Override
+ int injectBatteryPercent() {
+ return mBatteryLevel / 10;
+ }
+
void assertDumpable() {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
dump(new PrintWriter(out), ""); // Just make sure it won't crash.
@@ -102,7 +107,7 @@
target.assertDumpable();
target.advanceClock(1);
- target.drainBattery(2);
+ target.drainBattery(200);
target.transitionState(
BatterySaverState.OFF,
@@ -110,7 +115,7 @@
DozeState.NOT_DOZING);
target.advanceClock(4);
- target.drainBattery(1);
+ target.drainBattery(100);
target.transitionState(
BatterySaverState.OFF,
@@ -118,7 +123,7 @@
DozeState.NOT_DOZING);
target.advanceClock(2);
- target.drainBattery(5);
+ target.drainBattery(500);
target.transitionState(
BatterySaverState.OFF,
@@ -126,7 +131,7 @@
DozeState.NOT_DOZING);
target.advanceClock(4);
- target.drainBattery(1);
+ target.drainBattery(100);
target.transitionState(
BatterySaverState.OFF,
@@ -134,7 +139,7 @@
DozeState.NOT_DOZING);
target.advanceClock(2);
- target.drainBattery(5);
+ target.drainBattery(500);
target.transitionState(
BatterySaverState.OFF,
@@ -142,7 +147,7 @@
DozeState.NOT_DOZING);
target.advanceClock(3);
- target.drainBattery(1);
+ target.drainBattery(100);
target.transitionState(
BatterySaverState.OFF,
@@ -150,7 +155,7 @@
DozeState.LIGHT);
target.advanceClock(5);
- target.drainBattery(1);
+ target.drainBattery(100);
target.transitionState(
BatterySaverState.OFF,
@@ -158,7 +163,7 @@
DozeState.DEEP);
target.advanceClock(1);
- target.drainBattery(2);
+ target.drainBattery(200);
target.transitionState(
BatterySaverState.ON,
@@ -166,7 +171,7 @@
DozeState.NOT_DOZING);
target.advanceClock(1);
- target.drainBattery(3);
+ target.drainBattery(300);
target.transitionState(
BatterySaverState.OFF,
@@ -174,7 +179,7 @@
DozeState.NOT_DOZING);
target.advanceClock(3);
- target.drainBattery(5);
+ target.drainBattery(500);
target.transitionState(
BatterySaverState.ON,
@@ -182,12 +187,12 @@
DozeState.NOT_DOZING);
target.advanceClock(3);
- target.drainBattery(5);
+ target.drainBattery(500);
target.startCharging();
target.advanceClock(5);
- target.drainBattery(10);
+ target.drainBattery(1000);
target.transitionState(
BatterySaverState.ON,
@@ -195,25 +200,25 @@
DozeState.NOT_DOZING);
target.advanceClock(5);
- target.drainBattery(1);
+ target.drainBattery(100);
target.startCharging();
target.assertDumpable();
assertEquals(
- "BS=0,I=0,D=0:{4m,10,150.00}\n" +
- "BS=1,I=0,D=0:{0m,0,0.00}\n" +
- "BS=0,I=1,D=0:{14m,8,34.29}\n" +
- "BS=1,I=1,D=0:{9m,9,60.00}\n" +
- "BS=0,I=0,D=1:{5m,1,12.00}\n" +
- "BS=1,I=0,D=1:{0m,0,0.00}\n" +
- "BS=0,I=1,D=1:{0m,0,0.00}\n" +
- "BS=1,I=1,D=1:{0m,0,0.00}\n" +
- "BS=0,I=0,D=2:{1m,2,120.00}\n" +
- "BS=1,I=0,D=2:{0m,0,0.00}\n" +
- "BS=0,I=1,D=2:{0m,0,0.00}\n" +
- "BS=1,I=1,D=2:{0m,0,0.00}",
+ "BS=0,I=0,D=0:{4m,1000,15000.00uA/H,1500.00%}\n" +
+ "BS=1,I=0,D=0:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=0,I=1,D=0:{14m,800,3428.57uA/H,342.86%}\n" +
+ "BS=1,I=1,D=0:{9m,900,6000.00uA/H,600.00%}\n" +
+ "BS=0,I=0,D=1:{5m,100,1200.00uA/H,120.00%}\n" +
+ "BS=1,I=0,D=1:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=0,I=1,D=1:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=1,I=1,D=1:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=0,I=0,D=2:{1m,200,12000.00uA/H,1200.00%}\n" +
+ "BS=1,I=0,D=2:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=0,I=1,D=2:{0m,0,0.00uA/H,0.00%}\n" +
+ "BS=1,I=1,D=2:{0m,0,0.00uA/H,0.00%}",
target.toDebugString());
}
@@ -245,6 +250,7 @@
DozeState.NOT_DOZING);
assertMetricsLog(BatterySavingStats.COUNTER_POWER_MILLIAMPS_PREFIX + "01", 2);
+ assertMetricsLog(BatterySavingStats.COUNTER_POWER_PERCENT_PREFIX + "01", 200);
assertMetricsLog(BatterySavingStats.COUNTER_TIME_SECONDS_PREFIX + "01", 60);
target.advanceClock(1);
@@ -277,15 +283,17 @@
DozeState.NOT_DOZING);
assertMetricsLog(BatterySavingStats.COUNTER_POWER_MILLIAMPS_PREFIX + "00", 2 * 3);
+ assertMetricsLog(BatterySavingStats.COUNTER_POWER_PERCENT_PREFIX + "00", 200 * 3);
assertMetricsLog(BatterySavingStats.COUNTER_TIME_SECONDS_PREFIX + "00", 60 * 3);
target.advanceClock(10);
- target.drainBattery(10_000);
+ target.drainBattery(10000);
reset(mMetricsLogger);
target.startCharging();
assertMetricsLog(BatterySavingStats.COUNTER_POWER_MILLIAMPS_PREFIX + "11", 10);
+ assertMetricsLog(BatterySavingStats.COUNTER_POWER_PERCENT_PREFIX + "11", 1000);
assertMetricsLog(BatterySavingStats.COUNTER_TIME_SECONDS_PREFIX + "11", 60 * 10);
target.advanceClock(1);
@@ -305,6 +313,7 @@
target.startCharging();
assertMetricsLog(BatterySavingStats.COUNTER_POWER_MILLIAMPS_PREFIX + "10", 2);
+ assertMetricsLog(BatterySavingStats.COUNTER_POWER_PERCENT_PREFIX + "10", 200);
assertMetricsLog(BatterySavingStats.COUNTER_TIME_SECONDS_PREFIX + "10", 60);
}
}
diff --git a/services/tests/servicestests/src/com/android/server/wm/RemoteAnimationControllerTest.java b/services/tests/servicestests/src/com/android/server/wm/RemoteAnimationControllerTest.java
index f860195..26a7313 100644
--- a/services/tests/servicestests/src/com/android/server/wm/RemoteAnimationControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/RemoteAnimationControllerTest.java
@@ -19,12 +19,12 @@
import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import android.graphics.Point;
import android.graphics.Rect;
-import android.platform.test.annotations.Postsubmit;
import android.support.test.filters.FlakyTest;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
@@ -137,6 +137,32 @@
}
@Test
+ public void testTimeout_scaled() throws Exception {
+ sWm.setAnimationScale(2, 5.0f);
+ try{
+ final WindowState win = createWindow(null /* parent */, TYPE_BASE_APPLICATION, "testWin");
+ final AnimationAdapter adapter = mController.createAnimationAdapter(win.mAppToken,
+ new Point(50, 100), new Rect(50, 100, 150, 150));
+ adapter.startAnimation(mMockLeash, mMockTransaction, mFinishedCallback);
+ mController.goodToGo();
+
+ mClock.fastForward(2500);
+ mHandler.timeAdvance();
+
+ verify(mMockRunner, never()).onAnimationCancelled();
+
+ mClock.fastForward(10000);
+ mHandler.timeAdvance();
+
+ verify(mMockRunner).onAnimationCancelled();
+ verify(mFinishedCallback).onAnimationFinished(eq(adapter));
+ } finally {
+ sWm.setAnimationScale(2, 1.0f);
+ }
+
+ }
+
+ @Test
public void testZeroAnimations() throws Exception {
mController.goodToGo();
verifyZeroInteractions(mMockRunner);
diff --git a/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java b/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
index 7c14d08..b784c60 100644
--- a/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/slice/SliceFullAccessListTest.java
@@ -67,6 +67,15 @@
}
@Test
+ public void testRemoveAccess() {
+ mAccessList.grantFullAccess("pkg", 0);
+ assertTrue(mAccessList.hasFullAccess("pkg", 0));
+
+ mAccessList.removeGrant("pkg", 0);
+ assertFalse(mAccessList.hasFullAccess("pkg", 0));
+ }
+
+ @Test
public void testSerialization() throws XmlPullParserException, IOException {
mAccessList.grantFullAccess("pkg", 0);
mAccessList.grantFullAccess("pkg1", 0);
diff --git a/services/usb/java/com/android/server/usb/UsbDeviceManager.java b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
index e3e5e3e..55ffea6 100644
--- a/services/usb/java/com/android/server/usb/UsbDeviceManager.java
+++ b/services/usb/java/com/android/server/usb/UsbDeviceManager.java
@@ -41,7 +41,6 @@
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbPort;
import android.hardware.usb.UsbPortStatus;
-import android.hardware.usb.gadget.V1_0.GadgetFunction;
import android.hardware.usb.gadget.V1_0.IUsbGadget;
import android.hardware.usb.gadget.V1_0.IUsbGadgetCallback;
import android.hardware.usb.gadget.V1_0.Status;
@@ -68,6 +67,8 @@
import android.util.Slog;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
import com.android.internal.notification.SystemNotificationChannels;
import com.android.internal.os.SomeArgs;
@@ -86,21 +87,20 @@
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.Set;
-import java.util.StringJoiner;
/**
* UsbDeviceManager manages USB state in device mode.
*/
public class UsbDeviceManager implements ActivityManagerInternal.ScreenObserver {
- private static final String TAG = "UsbDeviceManager";
+ private static final String TAG = UsbDeviceManager.class.getSimpleName();
private static final boolean DEBUG = false;
/**
* The SharedPreference setting per user that stores the screen unlocked functions between
* sessions.
*/
- private static final String UNLOCKED_CONFIG_PREF = "usb-screen-unlocked-config-%d";
+ static final String UNLOCKED_CONFIG_PREF = "usb-screen-unlocked-config-%d";
/**
* ro.bootmode value when phone boots into usual Android.
@@ -156,8 +156,6 @@
private static final String ADB_NOTIFICATION_CHANNEL_ID_TV = "usbdevicemanager.adb.tv";
private UsbHandler mHandler;
- private boolean mBootCompleted;
- private boolean mSystemReady;
private final Object mLock = new Object();
@@ -165,22 +163,13 @@
private final ContentResolver mContentResolver;
@GuardedBy("mLock")
private UsbProfileGroupSettingsManager mCurrentSettings;
- private NotificationManager mNotificationManager;
private final boolean mHasUsbAccessory;
- private boolean mUseUsbNotification;
- private boolean mAdbEnabled;
- private boolean mAudioSourceEnabled;
- private boolean mMidiEnabled;
- private int mMidiCard;
- private int mMidiDevice;
+ @GuardedBy("mLock")
private String[] mAccessoryStrings;
private UsbDebuggingManager mDebuggingManager;
- private final UsbAlsaManager mUsbAlsaManager;
- private final UsbSettingsManager mSettingsManager;
- private Intent mBroadcastedIntent;
- private boolean mPendingBootBroadcast;
+ private final UEventObserver mUEventObserver;
+
private static Set<Integer> sBlackListedInterfaces;
- private SharedPreferences mSettings;
static {
sBlackListedInterfaces = new HashSet<>();
@@ -213,7 +202,7 @@
/*
* Listens for uevent messages from the kernel to monitor the USB state
*/
- private final UEventObserver mUEventObserver = new UEventObserver() {
+ private final class UsbUEventObserver extends UEventObserver {
@Override
public void onUEvent(UEventObserver.UEvent event) {
if (DEBUG) Slog.v(TAG, "USB UEVENT: " + event.toString());
@@ -227,7 +216,7 @@
startAccessoryMode();
}
}
- };
+ }
@Override
public void onKeyguardStateChanged(boolean isShowing) {
@@ -257,8 +246,6 @@
public UsbDeviceManager(Context context, UsbAlsaManager alsaManager,
UsbSettingsManager settingsManager) {
mContext = context;
- mUsbAlsaManager = alsaManager;
- mSettingsManager = settingsManager;
mContentResolver = context.getContentResolver();
PackageManager pm = mContext.getPackageManager();
mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
@@ -274,16 +261,24 @@
Slog.i(TAG, "USB GADGET HAL not present in the device", e);
}
+ boolean secureAdbEnabled = SystemProperties.getBoolean("ro.adb.secure", false);
+ boolean dataEncrypted = "1".equals(SystemProperties.get("vold.decrypt"));
+ if (secureAdbEnabled && !dataEncrypted) {
+ mDebuggingManager = new UsbDebuggingManager(context);
+ }
+
if (halNotPresent) {
/**
* Initialze the legacy UsbHandler
*/
- mHandler = new UsbHandlerLegacy(FgThread.get().getLooper(), mContext);
+ mHandler = new UsbHandlerLegacy(FgThread.get().getLooper(), mContext, this,
+ mDebuggingManager, alsaManager, settingsManager);
} else {
/**
* Initialize HAL based UsbHandler
*/
- mHandler = new UsbHandlerHal(FgThread.get().getLooper());
+ mHandler = new UsbHandlerHal(FgThread.get().getLooper(), mContext, this,
+ mDebuggingManager, alsaManager, settingsManager);
}
if (nativeIsStartRequested()) {
@@ -291,12 +286,6 @@
startAccessoryMode();
}
- boolean secureAdbEnabled = SystemProperties.getBoolean("ro.adb.secure", false);
- boolean dataEncrypted = "1".equals(SystemProperties.get("vold.decrypt"));
- if (secureAdbEnabled && !dataEncrypted) {
- mDebuggingManager = new UsbDebuggingManager(context);
- }
-
BroadcastReceiver portReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
@@ -347,41 +336,35 @@
mContext.registerReceiver(languageChangedReceiver,
new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
+
+ // Watch for USB configuration changes
+ mUEventObserver = new UsbUEventObserver();
+ mUEventObserver.startObserving(USB_STATE_MATCH);
+ mUEventObserver.startObserving(ACCESSORY_START_MATCH);
+
+ // register observer to listen for settings changes
+ mContentResolver.registerContentObserver(
+ Settings.Global.getUriFor(Settings.Global.ADB_ENABLED),
+ false, new AdbSettingsObserver());
}
- private UsbProfileGroupSettingsManager getCurrentSettings() {
+ UsbProfileGroupSettingsManager getCurrentSettings() {
synchronized (mLock) {
return mCurrentSettings;
}
}
+ String[] getAccessoryStrings() {
+ synchronized (mLock) {
+ return mAccessoryStrings;
+ }
+ }
+
public void systemReady() {
if (DEBUG) Slog.d(TAG, "systemReady");
LocalServices.getService(ActivityManagerInternal.class).registerScreenObserver(this);
- mNotificationManager = (NotificationManager)
- mContext.getSystemService(Context.NOTIFICATION_SERVICE);
-
- // Ensure that the notification channels are set up
- if (isTv()) {
- // TV-specific notification channel
- mNotificationManager.createNotificationChannel(
- new NotificationChannel(ADB_NOTIFICATION_CHANNEL_ID_TV,
- mContext.getString(
- com.android.internal.R.string
- .adb_debugging_notification_channel_tv),
- NotificationManager.IMPORTANCE_HIGH));
- }
-
- // We do not show the USB notification if the primary volume supports mass storage.
- // The legacy mass storage UI will be used instead.
- boolean massStorageSupported;
- final StorageManager storageManager = StorageManager.from(mContext);
- final StorageVolume primary = storageManager.getPrimaryVolume();
- massStorageSupported = primary != null && primary.allowMassStorage();
- mUseUsbNotification = !massStorageSupported && mContext.getResources().getBoolean(
- com.android.internal.R.bool.config_usbChargingMessage);
mHandler.sendEmptyMessage(MSG_SYSTEM_READY);
}
@@ -410,21 +393,19 @@
boolean enableAccessory = (mAccessoryStrings != null &&
mAccessoryStrings[UsbAccessory.MANUFACTURER_STRING] != null &&
mAccessoryStrings[UsbAccessory.MODEL_STRING] != null);
- String functions = null;
- if (enableAccessory && enableAudio) {
- functions = UsbManager.USB_FUNCTION_ACCESSORY + ","
- + UsbManager.USB_FUNCTION_AUDIO_SOURCE;
- } else if (enableAccessory) {
- functions = UsbManager.USB_FUNCTION_ACCESSORY;
- } else if (enableAudio) {
- functions = UsbManager.USB_FUNCTION_AUDIO_SOURCE;
+ long functions = UsbManager.FUNCTION_NONE;
+ if (enableAccessory) {
+ functions |= UsbManager.FUNCTION_ACCESSORY;
+ }
+ if (enableAudio) {
+ functions |= UsbManager.FUNCTION_AUDIO_SOURCE;
}
- if (functions != null) {
+ if (functions != UsbManager.FUNCTION_NONE) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_ACCESSORY_MODE_ENTER_TIMEOUT),
ACCESSORY_REQUEST_TIMEOUT);
- setCurrentFunctions(functions, false);
+ setCurrentFunctions(functions);
}
}
@@ -451,19 +432,7 @@
}
}
- private boolean isTv() {
- return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK);
- }
-
- private SharedPreferences getPinnedSharedPrefs(Context context) {
- final File prefsFile = new File(new File(
- Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
- context.getUserId(), context.getPackageName()), "shared_prefs"),
- UsbDeviceManager.class.getSimpleName() + ".xml");
- return context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE);
- }
-
- private abstract class UsbHandler extends Handler {
+ abstract static class UsbHandler extends Handler {
// current USB state
private boolean mConnected;
@@ -471,21 +440,40 @@
private boolean mSourcePower;
private boolean mSinkPower;
private boolean mConfigured;
- protected boolean mUsbDataUnlocked;
private boolean mAudioAccessoryConnected;
private boolean mAudioAccessorySupported;
- protected String mCurrentFunctions;
- protected boolean mCurrentFunctionsApplied;
+
private UsbAccessory mCurrentAccessory;
private int mUsbNotificationId;
private boolean mAdbNotificationShown;
- private int mCurrentUser;
private boolean mUsbCharging;
private boolean mHideUsbNotification;
private boolean mSupportsAllCombinations;
- private String mScreenUnlockedFunctions = UsbManager.USB_FUNCTION_NONE;
private boolean mScreenLocked;
- protected boolean mCurrentUsbFunctionsRequested;
+ private boolean mSystemReady;
+ private Intent mBroadcastedIntent;
+ private boolean mPendingBootBroadcast;
+ private boolean mAudioSourceEnabled;
+ private boolean mMidiEnabled;
+ private int mMidiCard;
+ private int mMidiDevice;
+
+ private final Context mContext;
+ private final UsbDebuggingManager mDebuggingManager;
+ private final UsbAlsaManager mUsbAlsaManager;
+ private final UsbSettingsManager mSettingsManager;
+ private NotificationManager mNotificationManager;
+
+ protected long mScreenUnlockedFunctions;
+ protected boolean mAdbEnabled;
+ protected boolean mBootCompleted;
+ protected boolean mCurrentFunctionsApplied;
+ protected boolean mUseUsbNotification;
+ protected long mCurrentFunctions;
+ protected final UsbDeviceManager mUsbDeviceManager;
+ protected final ContentResolver mContentResolver;
+ protected SharedPreferences mSettings;
+ protected int mCurrentUser;
protected boolean mCurrentUsbFunctionsReceived;
/**
@@ -494,31 +482,36 @@
*/
protected static final String USB_PERSISTENT_CONFIG_PROPERTY = "persist.sys.usb.config";
- public UsbHandler(Looper looper) {
+ UsbHandler(Looper looper, Context context, UsbDeviceManager deviceManager,
+ UsbDebuggingManager debuggingManager, UsbAlsaManager alsaManager,
+ UsbSettingsManager settingsManager) {
super(looper);
+ mContext = context;
+ mDebuggingManager = debuggingManager;
+ mUsbDeviceManager = deviceManager;
+ mUsbAlsaManager = alsaManager;
+ mSettingsManager = settingsManager;
+ mContentResolver = context.getContentResolver();
mCurrentUser = ActivityManager.getCurrentUser();
+ mScreenUnlockedFunctions = UsbManager.FUNCTION_NONE;
mScreenLocked = true;
/*
* Use the normal bootmode persistent prop to maintain state of adb across
* all boot modes.
*/
- mAdbEnabled = UsbManager.containsFunction(
- SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY),
- UsbManager.USB_FUNCTION_ADB);
+ mAdbEnabled = UsbHandlerLegacy.containsFunction(getSystemProperty(
+ USB_PERSISTENT_CONFIG_PROPERTY, ""), UsbManager.USB_FUNCTION_ADB);
- /*
- * Previous versions can set persist config to mtp/ptp but it does not
- * get reset on OTA. Reset the property here instead.
- */
- String persisted = SystemProperties.get(USB_PERSISTENT_CONFIG_PROPERTY);
- if (UsbManager.containsFunction(persisted, UsbManager.USB_FUNCTION_MTP)
- || UsbManager.containsFunction(persisted, UsbManager.USB_FUNCTION_PTP)) {
- SystemProperties.set(USB_PERSISTENT_CONFIG_PROPERTY,
- UsbManager.removeFunction(UsbManager.removeFunction(persisted,
- UsbManager.USB_FUNCTION_MTP), UsbManager.USB_FUNCTION_PTP));
- }
+ // We do not show the USB notification if the primary volume supports mass storage.
+ // The legacy mass storage UI will be used instead.
+ final StorageManager storageManager = StorageManager.from(mContext);
+ final StorageVolume primary = storageManager.getPrimaryVolume();
+
+ boolean massStorageSupported = primary != null && primary.allowMassStorage();
+ mUseUsbNotification = !massStorageSupported && mContext.getResources().getBoolean(
+ com.android.internal.R.bool.config_usbChargingMessage);
}
public void sendMessage(int what, boolean arg) {
@@ -602,20 +595,14 @@
if (DEBUG) Slog.d(TAG, "setAdbEnabled: " + enable);
if (enable != mAdbEnabled) {
mAdbEnabled = enable;
- String oldFunctions = mCurrentFunctions;
- // Persist the adb setting
- String newFunction = applyAdbFunction(SystemProperties.get(
- USB_PERSISTENT_CONFIG_PROPERTY, UsbManager.USB_FUNCTION_NONE));
- SystemProperties.set(USB_PERSISTENT_CONFIG_PROPERTY, newFunction);
-
- // Remove mtp from the config if file transfer is not enabled
- if (oldFunctions.equals(UsbManager.USB_FUNCTION_MTP) &&
- !mUsbDataUnlocked && enable) {
- oldFunctions = UsbManager.USB_FUNCTION_NONE;
+ if (enable) {
+ setSystemProperty(USB_PERSISTENT_CONFIG_PROPERTY, UsbManager.USB_FUNCTION_ADB);
+ } else {
+ setSystemProperty(USB_PERSISTENT_CONFIG_PROPERTY, "");
}
- setEnabledFunctions(oldFunctions, true, mUsbDataUnlocked);
+ setEnabledFunctions(mCurrentFunctions, true);
updateAdbNotification(false);
}
@@ -624,21 +611,7 @@
}
}
- protected String applyAdbFunction(String functions) {
- // Do not pass null pointer to the UsbManager.
- // There isnt a check there.
- if (functions == null) {
- functions = "";
- }
- if (mAdbEnabled) {
- functions = UsbManager.addFunction(functions, UsbManager.USB_FUNCTION_ADB);
- } else {
- functions = UsbManager.removeFunction(functions, UsbManager.USB_FUNCTION_ADB);
- }
- return functions;
- }
-
- private boolean isUsbTransferAllowed() {
+ protected boolean isUsbTransferAllowed() {
UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
return !userManager.hasUserRestriction(UserManager.DISALLOW_USB_FILE_TRANSFER);
}
@@ -650,12 +623,13 @@
if (mConfigured && enteringAccessoryMode) {
// successfully entered accessory mode
- if (mAccessoryStrings != null) {
- mCurrentAccessory = new UsbAccessory(mAccessoryStrings);
+ String[] accessoryStrings = mUsbDeviceManager.getAccessoryStrings();
+ if (accessoryStrings != null) {
+ mCurrentAccessory = new UsbAccessory(accessoryStrings);
Slog.d(TAG, "entering USB accessory mode: " + mCurrentAccessory);
// defer accessoryAttached if system is not ready
if (mBootCompleted) {
- getCurrentSettings().accessoryAttached(mCurrentAccessory);
+ mUsbDeviceManager.getCurrentSettings().accessoryAttached(mCurrentAccessory);
} // else handle in boot completed
} else {
Slog.e(TAG, "nativeGetAccessoryStrings failed");
@@ -673,17 +647,24 @@
// make sure accessory mode is off
// and restore default functions
Slog.d(TAG, "exited USB accessory mode");
- setEnabledFunctions(null, false, false);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
if (mCurrentAccessory != null) {
if (mBootCompleted) {
mSettingsManager.usbAccessoryRemoved(mCurrentAccessory);
}
mCurrentAccessory = null;
- mAccessoryStrings = null;
}
}
+ protected SharedPreferences getPinnedSharedPrefs(Context context) {
+ final File prefsFile = new File(new File(
+ Environment.getDataUserCePackageDirectory(StorageManager.UUID_PRIVATE_INTERNAL,
+ context.getUserId(), context.getPackageName()), "shared_prefs"),
+ UsbDeviceManager.class.getSimpleName() + ".xml");
+ return context.getSharedPreferences(prefsFile, Context.MODE_PRIVATE);
+ }
+
private boolean isUsbStateChanged(Intent intent) {
final Set<String> keySet = intent.getExtras().keySet();
if (mBroadcastedIntent == null) {
@@ -706,7 +687,8 @@
return false;
}
- protected void updateUsbStateBroadcastIfNeeded(boolean configChanged) {
+ protected void updateUsbStateBroadcastIfNeeded(long functions,
+ boolean configChanged) {
// send a sticky broadcast containing current USB state
Intent intent = new Intent(UsbManager.ACTION_USB_STATE);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
@@ -716,18 +698,14 @@
intent.putExtra(UsbManager.USB_HOST_CONNECTED, mHostConnected);
intent.putExtra(UsbManager.USB_CONFIGURED, mConfigured);
intent.putExtra(UsbManager.USB_DATA_UNLOCKED,
- isUsbTransferAllowed() && mUsbDataUnlocked);
+ isUsbTransferAllowed() && isUsbDataTransferActive(mCurrentFunctions));
intent.putExtra(UsbManager.USB_CONFIG_CHANGED, configChanged);
- if (mCurrentFunctions != null) {
- String[] functions = mCurrentFunctions.split(",");
- for (int i = 0; i < functions.length; i++) {
- final String function = functions[i];
- if (UsbManager.USB_FUNCTION_NONE.equals(function)) {
- continue;
- }
- intent.putExtra(function, true);
- }
+ long remainingFunctions = functions;
+ while (remainingFunctions != 0) {
+ intent.putExtra(UsbManager.usbFunctionsToString(
+ Long.highestOneBit(remainingFunctions)), true);
+ remainingFunctions -= Long.highestOneBit(remainingFunctions);
}
// send broadcast intent only if the USB state has changed
@@ -739,18 +717,21 @@
}
if (DEBUG) Slog.d(TAG, "broadcasting " + intent + " extras: " + intent.getExtras());
- mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+ sendStickyBroadcast(intent);
mBroadcastedIntent = intent;
}
+ protected void sendStickyBroadcast(Intent intent) {
+ mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
+ }
+
private void updateUsbFunctions() {
updateAudioSourceFunction();
updateMidiFunction();
}
private void updateAudioSourceFunction() {
- boolean enabled = UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_AUDIO_SOURCE);
+ boolean enabled = (mCurrentFunctions & UsbManager.FUNCTION_AUDIO_SOURCE) != 0;
if (enabled != mAudioSourceEnabled) {
int card = -1;
int device = -1;
@@ -775,8 +756,7 @@
}
private void updateMidiFunction() {
- boolean enabled = UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_MIDI);
+ boolean enabled = (mCurrentFunctions & UsbManager.FUNCTION_MIDI) != 0;
if (enabled != mMidiEnabled) {
if (enabled) {
Scanner scanner = null;
@@ -800,11 +780,21 @@
}
private void setScreenUnlockedFunctions() {
- setEnabledFunctions(mScreenUnlockedFunctions, false,
- UsbManager.containsFunction(mScreenUnlockedFunctions,
- UsbManager.USB_FUNCTION_MTP)
- || UsbManager.containsFunction(mScreenUnlockedFunctions,
- UsbManager.USB_FUNCTION_PTP));
+ setEnabledFunctions(mScreenUnlockedFunctions, false);
+ }
+
+ /**
+ * Returns the functions that are passed down to the low level driver once adb and
+ * charging are accounted for.
+ */
+ long getAppliedFunctions(long functions) {
+ if (functions == UsbManager.FUNCTION_NONE) {
+ return getChargingFunctions();
+ }
+ if (mAdbEnabled) {
+ return functions | UsbManager.FUNCTION_ADB;
+ }
+ return functions;
}
@Override
@@ -817,10 +807,10 @@
updateUsbNotification(false);
updateAdbNotification(false);
if (mBootCompleted) {
- updateUsbStateBroadcastIfNeeded(false);
+ updateUsbStateBroadcastIfNeeded(getAppliedFunctions(mCurrentFunctions),
+ false);
}
- if (UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_ACCESSORY)) {
+ if ((mCurrentFunctions & UsbManager.FUNCTION_ACCESSORY) != 0) {
updateCurrentAccessory();
}
if (mBootCompleted) {
@@ -828,11 +818,10 @@
&& !hasMessages(MSG_FUNCTION_SWITCH_TIMEOUT)) {
// restore defaults when USB is disconnected
if (!mScreenLocked
- && !UsbManager.USB_FUNCTION_NONE.equals(
- mScreenUnlockedFunctions)) {
+ && mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE) {
setScreenUnlockedFunctions();
} else {
- setEnabledFunctions(null, !mAdbEnabled, false);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, !mAdbEnabled);
}
}
updateUsbFunctions();
@@ -867,7 +856,8 @@
updateUsbNotification(false);
if (mBootCompleted) {
if (mHostConnected || prevHostConnected) {
- updateUsbStateBroadcastIfNeeded(false);
+ updateUsbStateBroadcastIfNeeded(getAppliedFunctions(mCurrentFunctions),
+ false);
}
} else {
mPendingBootBroadcast = true;
@@ -913,17 +903,17 @@
setAdbEnabled(msg.arg1 == 1);
break;
case MSG_SET_CURRENT_FUNCTIONS:
- String functions = (String) msg.obj;
- setEnabledFunctions(functions, false, msg.arg1 == 1);
+ long functions = (Long) msg.obj;
+ setEnabledFunctions(functions, false);
break;
case MSG_SET_SCREEN_UNLOCKED_FUNCTIONS:
- mScreenUnlockedFunctions = (String) msg.obj;
+ mScreenUnlockedFunctions = (Long) msg.obj;
SharedPreferences.Editor editor = mSettings.edit();
editor.putString(String.format(Locale.ENGLISH, UNLOCKED_CONFIG_PREF,
- mCurrentUser), mScreenUnlockedFunctions);
+ mCurrentUser),
+ UsbManager.usbFunctionsToString(mScreenUnlockedFunctions));
editor.commit();
- if (!mScreenLocked && !UsbManager.USB_FUNCTION_NONE.equals(
- mScreenUnlockedFunctions)) {
+ if (!mScreenLocked && mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE) {
// If the screen is unlocked, also set current functions.
setScreenUnlockedFunctions();
}
@@ -936,22 +926,21 @@
if (mSettings == null && !mScreenLocked) {
// Shared preferences aren't accessible until the user has been unlocked.
mSettings = getPinnedSharedPrefs(mContext);
- mScreenUnlockedFunctions = mSettings.getString(
+ mScreenUnlockedFunctions = UsbManager.usbFunctionsFromString(
+ mSettings.getString(
String.format(Locale.ENGLISH, UNLOCKED_CONFIG_PREF, mCurrentUser),
- UsbManager.USB_FUNCTION_NONE);
+ ""));
}
if (!mBootCompleted) {
break;
}
if (mScreenLocked) {
if (!mConnected) {
- setEnabledFunctions(null, false, false);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
}
} else {
- if (!UsbManager.USB_FUNCTION_NONE.equals(mScreenUnlockedFunctions)
- && (UsbManager.USB_FUNCTION_ADB.equals(mCurrentFunctions)
- || (UsbManager.USB_FUNCTION_MTP.equals(mCurrentFunctions)
- && !mUsbDataUnlocked))) {
+ if (mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE
+ && mCurrentFunctions == UsbManager.FUNCTION_NONE) {
// Set the screen unlocked functions if current function is charging.
setScreenUnlockedFunctions();
}
@@ -959,13 +948,24 @@
break;
case MSG_UPDATE_USER_RESTRICTIONS:
// Restart the USB stack if USB transfer is enabled but no longer allowed.
- final boolean forceRestart = mUsbDataUnlocked
- && isUsbDataTransferActive()
- && !isUsbTransferAllowed();
- setEnabledFunctions(
- mCurrentFunctions, forceRestart, mUsbDataUnlocked && !forceRestart);
+ if (isUsbDataTransferActive(mCurrentFunctions) && !isUsbTransferAllowed()) {
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, true);
+ }
break;
case MSG_SYSTEM_READY:
+ mNotificationManager = (NotificationManager)
+ mContext.getSystemService(Context.NOTIFICATION_SERVICE);
+
+ // Ensure that the notification channels are set up
+ if (isTv()) {
+ // TV-specific notification channel
+ mNotificationManager.createNotificationChannel(
+ new NotificationChannel(ADB_NOTIFICATION_CHANNEL_ID_TV,
+ mContext.getString(
+ com.android.internal.R.string
+ .adb_debugging_notification_channel_tv),
+ NotificationManager.IMPORTANCE_HIGH));
+ }
mSystemReady = true;
finishBoot();
break;
@@ -984,10 +984,14 @@
}
mCurrentUser = msg.arg1;
mScreenLocked = true;
- mScreenUnlockedFunctions = mSettings.getString(
- String.format(Locale.ENGLISH, UNLOCKED_CONFIG_PREF, mCurrentUser),
- UsbManager.USB_FUNCTION_NONE);
- setEnabledFunctions(null, false, false);
+ if (mSettings != null) {
+ mScreenUnlockedFunctions = UsbManager.usbFunctionsFromString(
+ mSettings.getString(
+ String.format(Locale.ENGLISH, UNLOCKED_CONFIG_PREF,
+ mCurrentUser),
+ ""));
+ }
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
}
break;
}
@@ -995,9 +999,7 @@
if (DEBUG) {
Slog.v(TAG, "Accessory mode enter timeout: " + mConnected);
}
- if (!mConnected || !UsbManager.containsFunction(
- mCurrentFunctions,
- UsbManager.USB_FUNCTION_ACCESSORY)) {
+ if (!mConnected || (mCurrentFunctions & UsbManager.FUNCTION_ACCESSORY) == 0) {
notifyAccessoryModeExit();
}
break;
@@ -1008,17 +1010,17 @@
protected void finishBoot() {
if (mBootCompleted && mCurrentUsbFunctionsReceived && mSystemReady) {
if (mPendingBootBroadcast) {
- updateUsbStateBroadcastIfNeeded(false);
+ updateUsbStateBroadcastIfNeeded(getAppliedFunctions(mCurrentFunctions), false);
mPendingBootBroadcast = false;
}
if (!mScreenLocked
- && !UsbManager.USB_FUNCTION_NONE.equals(mScreenUnlockedFunctions)) {
+ && mScreenUnlockedFunctions != UsbManager.FUNCTION_NONE) {
setScreenUnlockedFunctions();
} else {
- setEnabledFunctions(null, false, false);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
}
if (mCurrentAccessory != null) {
- getCurrentSettings().accessoryAttached(mCurrentAccessory);
+ mUsbDeviceManager.getCurrentSettings().accessoryAttached(mCurrentAccessory);
}
if (mDebuggingManager != null) {
mDebuggingManager.setAdbEnabled(mAdbEnabled);
@@ -1026,8 +1028,8 @@
// make sure the ADB_ENABLED setting value matches the current state
try {
- Settings.Global.putInt(mContentResolver,
- Settings.Global.ADB_ENABLED, mAdbEnabled ? 1 : 0);
+ putGlobalSettings(mContentResolver, Settings.Global.ADB_ENABLED,
+ mAdbEnabled ? 1 : 0);
} catch (SecurityException e) {
// If UserManager.DISALLOW_DEBUGGING_FEATURES is on, that this setting can't
// be changed.
@@ -1040,9 +1042,9 @@
}
}
- private boolean isUsbDataTransferActive() {
- return UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_MTP)
- || UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_PTP);
+ protected boolean isUsbDataTransferActive(long functions) {
+ return (functions & UsbManager.FUNCTION_MTP) != 0
+ || (functions & UsbManager.FUNCTION_PTP) != 0;
}
public UsbAccessory getCurrentAccessory() {
@@ -1051,7 +1053,7 @@
protected void updateUsbNotification(boolean force) {
if (mNotificationManager == null || !mUseUsbNotification
- || ("0".equals(SystemProperties.get("persist.charging.notify")))) {
+ || ("0".equals(getSystemProperty("persist.charging.notify", "")))) {
return;
}
@@ -1070,30 +1072,37 @@
int id = 0;
int titleRes = 0;
Resources r = mContext.getResources();
+ CharSequence message = r.getText(
+ com.android.internal.R.string.usb_notification_message);
if (mAudioAccessoryConnected && !mAudioAccessorySupported) {
titleRes = com.android.internal.R.string.usb_unsupported_audio_accessory_title;
id = SystemMessage.NOTE_USB_AUDIO_ACCESSORY_NOT_SUPPORTED;
} else if (mConnected) {
- if (UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_MTP) && mUsbDataUnlocked) {
+ if (mCurrentFunctions == UsbManager.FUNCTION_MTP) {
titleRes = com.android.internal.R.string.usb_mtp_notification_title;
id = SystemMessage.NOTE_USB_MTP;
- } else if (UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_PTP) && mUsbDataUnlocked) {
+ } else if (mCurrentFunctions == UsbManager.FUNCTION_PTP) {
titleRes = com.android.internal.R.string.usb_ptp_notification_title;
id = SystemMessage.NOTE_USB_PTP;
- } else if (UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_MIDI)) {
+ } else if (mCurrentFunctions == UsbManager.FUNCTION_MIDI) {
titleRes = com.android.internal.R.string.usb_midi_notification_title;
id = SystemMessage.NOTE_USB_MIDI;
- } else if (UsbManager.containsFunction(mCurrentFunctions,
- UsbManager.USB_FUNCTION_ACCESSORY)) {
+ } else if (mCurrentFunctions == UsbManager.FUNCTION_RNDIS) {
+ titleRes = com.android.internal.R.string.usb_tether_notification_title;
+ id = SystemMessage.NOTE_USB_TETHER;
+ } else if (mCurrentFunctions == UsbManager.FUNCTION_ACCESSORY) {
titleRes = com.android.internal.R.string.usb_accessory_notification_title;
id = SystemMessage.NOTE_USB_ACCESSORY;
- } else if (mSourcePower) {
- titleRes = com.android.internal.R.string.usb_supplying_notification_title;
- id = SystemMessage.NOTE_USB_SUPPLYING;
- } else {
+ }
+ if (mSourcePower) {
+ if (titleRes != 0) {
+ message = r.getText(
+ com.android.internal.R.string.usb_power_notification_message);
+ } else {
+ titleRes = com.android.internal.R.string.usb_supplying_notification_title;
+ id = SystemMessage.NOTE_USB_SUPPLYING;
+ }
+ } else if (titleRes == 0) {
titleRes = com.android.internal.R.string.usb_charging_notification_title;
id = SystemMessage.NOTE_USB_CHARGING;
}
@@ -1113,7 +1122,6 @@
mUsbNotificationId = 0;
}
if (id != 0) {
- CharSequence message;
CharSequence title = r.getText(titleRes);
PendingIntent pi;
String channel;
@@ -1123,12 +1131,10 @@
.usb_unsupported_audio_accessory_title) {
Intent intent = Intent.makeRestartActivityTask(
new ComponentName("com.android.settings",
- "com.android.settings.deviceinfo.UsbModeChooserActivity"));
+ "com.android.settings.Settings$UsbDetailsActivity"));
pi = PendingIntent.getActivityAsUser(mContext, 0,
intent, 0, null, UserHandle.CURRENT);
channel = SystemNotificationChannels.USB;
- message = r.getText(
- com.android.internal.R.string.usb_notification_message);
} else {
final Intent intent = new Intent();
intent.setClassName("com.android.settings",
@@ -1184,7 +1190,7 @@
final int titleRes = com.android.internal.R.string.adb_active_notification_title;
if (mAdbEnabled && mConnected) {
- if ("0".equals(SystemProperties.get("persist.adb.notify"))) return;
+ if ("0".equals(getSystemProperty("persist.adb.notify", ""))) return;
if (force && mAdbNotificationShown) {
mAdbNotificationShown = false;
@@ -1230,20 +1236,41 @@
}
}
- protected String getChargingFunctions() {
+ private boolean isTv() {
+ return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK);
+ }
+
+ protected long getChargingFunctions() {
// if ADB is enabled, reset functions to ADB
// else enable MTP as usual.
if (mAdbEnabled) {
- return UsbManager.USB_FUNCTION_ADB;
+ return UsbManager.FUNCTION_ADB;
} else {
- return UsbManager.USB_FUNCTION_MTP;
+ return UsbManager.FUNCTION_MTP;
}
}
- public boolean isFunctionEnabled(String function) {
- return UsbManager.containsFunction(mCurrentFunctions, function);
+ protected void setSystemProperty(String prop, String val) {
+ SystemProperties.set(prop, val);
}
+ protected String getSystemProperty(String prop, String def) {
+ return SystemProperties.get(prop, def);
+ }
+
+ protected void putGlobalSettings(ContentResolver contentResolver, String setting, int val) {
+ Settings.Global.putInt(contentResolver, setting, val);
+ }
+
+ public long getEnabledFunctions() {
+ return mCurrentFunctions;
+ }
+
+ public long getScreenUnlockedFunctions() {
+ return mScreenUnlockedFunctions;
+ }
+
+
public void dump(IndentingPrintWriter pw) {
pw.println("USB Device State:");
pw.println(" mCurrentFunctions: " + mCurrentFunctions);
@@ -1252,7 +1279,6 @@
pw.println(" mScreenLocked: " + mScreenLocked);
pw.println(" mConnected: " + mConnected);
pw.println(" mConfigured: " + mConfigured);
- pw.println(" mUsbDataUnlocked: " + mUsbDataUnlocked);
pw.println(" mCurrentAccessory: " + mCurrentAccessory);
pw.println(" mHostConnected: " + mHostConnected);
pw.println(" mSourcePower: " + mSourcePower);
@@ -1275,12 +1301,10 @@
/**
* Evaluates USB function policies and applies the change accordingly.
*/
- protected abstract void setEnabledFunctions(String functions, boolean forceRestart,
- boolean usbDataUnlocked);
-
+ protected abstract void setEnabledFunctions(long functions, boolean forceRestart);
}
- private final class UsbHandlerLegacy extends UsbHandler {
+ private static final class UsbHandlerLegacy extends UsbHandler {
/**
* The non-persistent property which stores the current USB settings.
*/
@@ -1293,46 +1317,44 @@
private HashMap<String, HashMap<String, Pair<String, String>>> mOemModeMap;
private String mCurrentOemFunctions;
+ private String mCurrentFunctionsStr;
+ private boolean mUsbDataUnlocked;
- UsbHandlerLegacy(Looper looper, Context context) {
- super(looper);
+ UsbHandlerLegacy(Looper looper, Context context, UsbDeviceManager deviceManager,
+ UsbDebuggingManager debuggingManager, UsbAlsaManager alsaManager,
+ UsbSettingsManager settingsManager) {
+ super(looper, context, deviceManager, debuggingManager, alsaManager, settingsManager);
try {
readOemUsbOverrideConfig(context);
// Restore default functions.
- mCurrentOemFunctions = SystemProperties.get(getPersistProp(false),
+ mCurrentOemFunctions = getSystemProperty(getPersistProp(false),
UsbManager.USB_FUNCTION_NONE);
if (isNormalBoot()) {
- mCurrentFunctions = SystemProperties.get(USB_CONFIG_PROPERTY,
+ mCurrentFunctionsStr = getSystemProperty(USB_CONFIG_PROPERTY,
UsbManager.USB_FUNCTION_NONE);
- mCurrentFunctionsApplied = mCurrentFunctions.equals(
- SystemProperties.get(USB_STATE_PROPERTY));
+ mCurrentFunctionsApplied = mCurrentFunctionsStr.equals(
+ getSystemProperty(USB_STATE_PROPERTY, UsbManager.USB_FUNCTION_NONE));
} else {
- mCurrentFunctions = SystemProperties.get(getPersistProp(true),
+ mCurrentFunctionsStr = getSystemProperty(getPersistProp(true),
UsbManager.USB_FUNCTION_NONE);
- mCurrentFunctionsApplied = SystemProperties.get(USB_CONFIG_PROPERTY,
+ mCurrentFunctionsApplied = getSystemProperty(USB_CONFIG_PROPERTY,
UsbManager.USB_FUNCTION_NONE).equals(
- SystemProperties.get(USB_STATE_PROPERTY));
+ getSystemProperty(USB_STATE_PROPERTY, UsbManager.USB_FUNCTION_NONE));
}
+ // Mask out adb, since it is stored in mAdbEnabled
+ mCurrentFunctions = UsbManager.usbFunctionsFromString(mCurrentFunctionsStr)
+ & ~UsbManager.FUNCTION_ADB;
mCurrentUsbFunctionsReceived = true;
String state = FileUtils.readTextFile(new File(STATE_PATH), 0, null).trim();
updateState(state);
-
- // register observer to listen for settings changes
- mContentResolver.registerContentObserver(
- Settings.Global.getUriFor(Settings.Global.ADB_ENABLED),
- false, new AdbSettingsObserver());
-
- // Watch for USB configuration changes
- mUEventObserver.startObserving(USB_STATE_MATCH);
- mUEventObserver.startObserving(ACCESSORY_START_MATCH);
} catch (Exception e) {
Slog.e(TAG, "Error initializing UsbHandler", e);
}
}
private void readOemUsbOverrideConfig(Context context) {
- String[] configList = mContext.getResources().getStringArray(
+ String[] configList = context.getResources().getStringArray(
com.android.internal.R.array.config_oemUsbModeOverride);
if (configList != null) {
@@ -1367,7 +1389,7 @@
return usbFunctions;
}
- String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
+ String bootMode = getSystemProperty(BOOT_MODE_PROPERTY, "unknown");
Slog.d(TAG, "applyOemOverride usbfunctions=" + usbFunctions + " bootmode=" + bootMode);
Map<String, Pair<String, String>> overridesMap =
@@ -1386,25 +1408,22 @@
if (!overrideFunctions.second.equals("")) {
String newFunction;
if (mAdbEnabled) {
- newFunction = UsbManager.addFunction(overrideFunctions.second,
+ newFunction = addFunction(overrideFunctions.second,
UsbManager.USB_FUNCTION_ADB);
} else {
newFunction = overrideFunctions.second;
}
Slog.d(TAG, "OEM USB override persisting: " + newFunction + "in prop: "
+ getPersistProp(false));
- SystemProperties.set(getPersistProp(false),
- newFunction);
+ setSystemProperty(getPersistProp(false), newFunction);
}
return overrideFunctions.first;
} else if (mAdbEnabled) {
- String newFunction = UsbManager.addFunction(UsbManager.USB_FUNCTION_NONE,
+ String newFunction = addFunction(UsbManager.USB_FUNCTION_NONE,
UsbManager.USB_FUNCTION_ADB);
- SystemProperties.set(getPersistProp(false),
- newFunction);
+ setSystemProperty(getPersistProp(false), newFunction);
} else {
- SystemProperties.set(getPersistProp(false),
- UsbManager.USB_FUNCTION_NONE);
+ setSystemProperty(getPersistProp(false), UsbManager.USB_FUNCTION_NONE);
}
}
// return passed in functions as is.
@@ -1417,7 +1436,7 @@
String value = null;
for (int i = 0; i < 20; i++) {
// State transition is done when sys.usb.state is set to the new configuration
- value = SystemProperties.get(USB_STATE_PROPERTY);
+ value = getSystemProperty(USB_STATE_PROPERTY, "");
if (state.equals(value)) return true;
SystemClock.sleep(50);
}
@@ -1432,14 +1451,14 @@
* we always set it due to b/23631400, where adbd was getting killed
* and not restarted due to property timeouts on some devices
*/
- SystemProperties.set(USB_CONFIG_PROPERTY, config);
+ setSystemProperty(USB_CONFIG_PROPERTY, config);
}
@Override
- protected void setEnabledFunctions(String functions, boolean forceRestart,
- boolean usbDataUnlocked) {
+ protected void setEnabledFunctions(long usbFunctions, boolean forceRestart) {
+ boolean usbDataUnlocked = isUsbDataTransferActive(usbFunctions);
if (DEBUG) {
- Slog.d(TAG, "setEnabledFunctions functions=" + functions + ", "
+ Slog.d(TAG, "setEnabledFunctions functions=" + usbFunctions + ", "
+ "forceRestart=" + forceRestart + ", usbDataUnlocked=" + usbDataUnlocked);
}
@@ -1452,9 +1471,9 @@
/**
* Try to set the enabled functions.
*/
- final String oldFunctions = mCurrentFunctions;
+ final long oldFunctions = mCurrentFunctions;
final boolean oldFunctionsApplied = mCurrentFunctionsApplied;
- if (trySetEnabledFunctions(functions, forceRestart)) {
+ if (trySetEnabledFunctions(usbFunctions, forceRestart)) {
return;
}
@@ -1464,7 +1483,7 @@
* user restrictions independently of any other new functions we were
* trying to activate.
*/
- if (oldFunctionsApplied && !oldFunctions.equals(functions)) {
+ if (oldFunctionsApplied && oldFunctions != usbFunctions) {
Slog.e(TAG, "Failsafe 1: Restoring previous USB functions.");
if (trySetEnabledFunctions(oldFunctions, false)) {
return;
@@ -1475,7 +1494,7 @@
* Still didn't work. Try to restore the default functions.
*/
Slog.e(TAG, "Failsafe 2: Restoring default USB functions.");
- if (trySetEnabledFunctions(null, false)) {
+ if (trySetEnabledFunctions(UsbManager.FUNCTION_NONE, false)) {
return;
}
@@ -1484,7 +1503,7 @@
* Try to get ADB working if enabled.
*/
Slog.e(TAG, "Failsafe 3: Restoring empty function list (with ADB if enabled).");
- if (trySetEnabledFunctions(UsbManager.USB_FUNCTION_NONE, false)) {
+ if (trySetEnabledFunctions(UsbManager.FUNCTION_NONE, false)) {
return;
}
@@ -1495,30 +1514,49 @@
}
private boolean isNormalBoot() {
- String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
+ String bootMode = getSystemProperty(BOOT_MODE_PROPERTY, "unknown");
return bootMode.equals(NORMAL_BOOT) || bootMode.equals("unknown");
}
- private boolean trySetEnabledFunctions(String functions, boolean forceRestart) {
+ protected String applyAdbFunction(String functions) {
+ // Do not pass null pointer to the UsbManager.
+ // There isn't a check there.
+ if (functions == null) {
+ functions = "";
+ }
+ if (mAdbEnabled) {
+ functions = addFunction(functions, UsbManager.USB_FUNCTION_ADB);
+ } else {
+ functions = removeFunction(functions, UsbManager.USB_FUNCTION_ADB);
+ }
+ return functions;
+ }
+
+ private boolean trySetEnabledFunctions(long usbFunctions, boolean forceRestart) {
+ String functions = null;
+ if (usbFunctions != UsbManager.FUNCTION_NONE) {
+ functions = UsbManager.usbFunctionsToString(usbFunctions);
+ }
+ mCurrentFunctions = usbFunctions;
if (functions == null || applyAdbFunction(functions)
.equals(UsbManager.USB_FUNCTION_NONE)) {
- functions = getChargingFunctions();
+ functions = UsbManager.usbFunctionsToString(getChargingFunctions());
}
functions = applyAdbFunction(functions);
String oemFunctions = applyOemOverrideFunction(functions);
- if (!isNormalBoot() && !mCurrentFunctions.equals(functions)) {
- SystemProperties.set(getPersistProp(true), functions);
+ if (!isNormalBoot() && !mCurrentFunctionsStr.equals(functions)) {
+ setSystemProperty(getPersistProp(true), functions);
}
if ((!functions.equals(oemFunctions)
&& !mCurrentOemFunctions.equals(oemFunctions))
- || !mCurrentFunctions.equals(functions)
+ || !mCurrentFunctionsStr.equals(functions)
|| !mCurrentFunctionsApplied
|| forceRestart) {
Slog.i(TAG, "Setting USB config to " + functions);
- mCurrentFunctions = functions;
+ mCurrentFunctionsStr = functions;
mCurrentOemFunctions = oemFunctions;
mCurrentFunctionsApplied = false;
@@ -1538,12 +1576,12 @@
setUsbConfig(oemFunctions);
if (mBootCompleted
- && (UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_MTP)
- || UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_PTP))) {
+ && (containsFunction(functions, UsbManager.USB_FUNCTION_MTP)
+ || containsFunction(functions, UsbManager.USB_FUNCTION_PTP))) {
/**
* Start up dependent services.
*/
- updateUsbStateBroadcastIfNeeded(true);
+ updateUsbStateBroadcastIfNeeded(getAppliedFunctions(mCurrentFunctions), true);
}
if (!waitForState(oemFunctions)) {
@@ -1557,7 +1595,7 @@
}
private String getPersistProp(boolean functions) {
- String bootMode = SystemProperties.get(BOOT_MODE_PROPERTY, "unknown");
+ String bootMode = getSystemProperty(BOOT_MODE_PROPERTY, "unknown");
String persistProp = USB_PERSISTENT_CONFIG_PROPERTY;
if (!(bootMode.equals(NORMAL_BOOT) || bootMode.equals("unknown"))) {
if (functions) {
@@ -1568,9 +1606,54 @@
}
return persistProp;
}
+
+ private static String addFunction(String functions, String function) {
+ if (UsbManager.USB_FUNCTION_NONE.equals(functions)) {
+ return function;
+ }
+ if (!containsFunction(functions, function)) {
+ if (functions.length() > 0) {
+ functions += ",";
+ }
+ functions += function;
+ }
+ return functions;
+ }
+
+ private static String removeFunction(String functions, String function) {
+ String[] split = functions.split(",");
+ for (int i = 0; i < split.length; i++) {
+ if (function.equals(split[i])) {
+ split[i] = null;
+ }
+ }
+ if (split.length == 1 && split[0] == null) {
+ return UsbManager.USB_FUNCTION_NONE;
+ }
+ StringBuilder builder = new StringBuilder();
+ for (int i = 0; i < split.length; i++) {
+ String s = split[i];
+ if (s != null) {
+ if (builder.length() > 0) {
+ builder.append(",");
+ }
+ builder.append(s);
+ }
+ }
+ return builder.toString();
+ }
+
+ static boolean containsFunction(String functions, String function) {
+ int index = functions.indexOf(function);
+ if (index < 0) return false;
+ if (index > 0 && functions.charAt(index - 1) != ',') return false;
+ int charAfter = index + function.length();
+ if (charAfter < functions.length() && functions.charAt(charAfter) != ',') return false;
+ return true;
+ }
}
- private final class UsbHandlerHal extends UsbHandler {
+ private static final class UsbHandlerHal extends UsbHandler {
/**
* Proxy object for the usb gadget hal daemon.
@@ -1627,9 +1710,12 @@
*/
protected static final String ADBD = "adbd";
+ protected boolean mCurrentUsbFunctionsRequested;
- UsbHandlerHal(Looper looper) {
- super(looper);
+ UsbHandlerHal(Looper looper, Context context, UsbDeviceManager deviceManager,
+ UsbDebuggingManager debuggingManager, UsbAlsaManager alsaManager,
+ UsbSettingsManager settingsManager) {
+ super(looper, context, deviceManager, debuggingManager, alsaManager, settingsManager);
try {
ServiceNotification serviceNotification = new ServiceNotification();
@@ -1645,25 +1731,12 @@
mGadgetProxy = IUsbGadget.getService(true);
mGadgetProxy.linkToDeath(new UsbGadgetDeathRecipient(),
USB_GADGET_HAL_DEATH_COOKIE);
- mCurrentFunctions = UsbManager.USB_FUNCTION_NONE;
+ mCurrentFunctions = UsbManager.FUNCTION_NONE;
mGadgetProxy.getCurrentUsbFunctions(new UsbGadgetCallback());
mCurrentUsbFunctionsRequested = true;
}
String state = FileUtils.readTextFile(new File(STATE_PATH), 0, null).trim();
updateState(state);
-
- /**
- * Register observer to listen for settings changes.
- */
- mContentResolver.registerContentObserver(
- Settings.Global.getUriFor(Settings.Global.ADB_ENABLED),
- false, new AdbSettingsObserver());
-
- /**
- * Watch for USB configuration changes.
- */
- mUEventObserver.startObserving(USB_STATE_MATCH);
- mUEventObserver.startObserving(ACCESSORY_START_MATCH);
} catch (NoSuchElementException e) {
Slog.e(TAG, "Usb gadget hal not found", e);
} catch (RemoteException e) {
@@ -1696,7 +1769,7 @@
mGadgetProxy.linkToDeath(new UsbGadgetDeathRecipient(),
USB_GADGET_HAL_DEATH_COOKIE);
if (!mCurrentFunctionsApplied) {
- setCurrentFunctions(mCurrentFunctions, mUsbDataUnlocked);
+ setEnabledFunctions(mCurrentFunctions, false);
}
} catch (NoSuchElementException e) {
Slog.e(TAG, "Usb gadget hal not found", e);
@@ -1711,12 +1784,12 @@
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_SET_CHARGING_FUNCTIONS:
- setEnabledFunctions(null, false, mUsbDataUnlocked);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
break;
case MSG_SET_FUNCTIONS_TIMEOUT:
Slog.e(TAG, "Set functions timed out! no reply from usb hal");
if (msg.arg1 != 1) {
- setEnabledFunctions(null, false, mUsbDataUnlocked);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, false);
}
break;
case MSG_GET_CURRENT_USB_FUNCTIONS:
@@ -1725,7 +1798,8 @@
if (mCurrentUsbFunctionsRequested) {
Slog.e(TAG, "updating mCurrentFunctions");
- mCurrentFunctions = functionListToString((Long) msg.obj);
+ // Mask out adb, since it is stored in mAdbEnabled
+ mCurrentFunctions = ((Long) msg.obj) & ~UsbManager.FUNCTION_ADB;
Slog.e(TAG,
"mCurrentFunctions:" + mCurrentFunctions + "applied:" + msg.arg1);
mCurrentFunctionsApplied = msg.arg1 == 1;
@@ -1737,7 +1811,7 @@
* Dont force to default when the configuration is already set to default.
*/
if (msg.arg1 != 1) {
- setEnabledFunctions(null, !mAdbEnabled, false);
+ setEnabledFunctions(UsbManager.FUNCTION_NONE, !mAdbEnabled);
}
break;
default:
@@ -1789,70 +1863,7 @@
}
}
- private long stringToFunctionList(String config) {
- long functionsMask = 0;
- String[] functions = config.split(",");
- for (int i = 0; i < functions.length; i++) {
- switch (functions[i]) {
- case "none":
- functionsMask |= GadgetFunction.NONE;
- break;
- case "adb":
- functionsMask |= GadgetFunction.ADB;
- break;
- case "mtp":
- functionsMask |= GadgetFunction.MTP;
- break;
- case "ptp":
- functionsMask |= GadgetFunction.PTP;
- break;
- case "midi":
- functionsMask |= GadgetFunction.MIDI;
- break;
- case "accessory":
- functionsMask |= GadgetFunction.ACCESSORY;
- break;
- case "rndis":
- functionsMask |= GadgetFunction.RNDIS;
- break;
- }
- }
- return functionsMask;
- }
-
- private String functionListToString(Long functionList) {
- StringJoiner functions = new StringJoiner(",");
- if (functionList == GadgetFunction.NONE) {
- functions.add("none");
- return functions.toString();
- }
- if ((functionList & GadgetFunction.ADB) != 0) {
- functions.add("adb");
- }
- if ((functionList & GadgetFunction.MTP) != 0) {
- functions.add("mtp");
- }
- if ((functionList & GadgetFunction.PTP) != 0) {
- functions.add("ptp");
- }
- if ((functionList & GadgetFunction.MIDI) != 0) {
- functions.add("midi");
- }
- if ((functionList & GadgetFunction.ACCESSORY) != 0) {
- functions.add("accessory");
- }
- if ((functionList & GadgetFunction.RNDIS) != 0) {
- functions.add("rndis");
- }
- /**
- * Remove the trailing comma.
- */
- return functions.toString();
- }
-
-
- private void setUsbConfig(String config, boolean chargingFunctions) {
- Long functions = stringToFunctionList(config);
+ private void setUsbConfig(long config, boolean chargingFunctions) {
if (true) Slog.d(TAG, "setUsbConfig(" + config + ") request:" + ++mCurrentRequest);
/**
* Cancel any ongoing requests, if present.
@@ -1867,20 +1878,20 @@
return;
}
try {
- if ((functions & GadgetFunction.ADB) != 0) {
+ if ((config & UsbManager.FUNCTION_ADB) != 0) {
/**
* Start adbd if ADB function is included in the configuration.
*/
- SystemProperties.set(CTL_START, ADBD);
+ setSystemProperty(CTL_START, ADBD);
} else {
/**
* Stop adbd otherwise.
*/
- SystemProperties.set(CTL_STOP, ADBD);
+ setSystemProperty(CTL_STOP, ADBD);
}
UsbGadgetCallback usbGadgetCallback = new UsbGadgetCallback(mCurrentRequest,
- functions, chargingFunctions);
- mGadgetProxy.setCurrentUsbFunctions(functions, usbGadgetCallback,
+ config, chargingFunctions);
+ mGadgetProxy.setCurrentUsbFunctions(config, usbGadgetCallback,
SET_FUNCTIONS_TIMEOUT_MS - SET_FUNCTIONS_LEEWAY_MS);
sendMessageDelayed(MSG_SET_FUNCTIONS_TIMEOUT, chargingFunctions,
SET_FUNCTIONS_TIMEOUT_MS);
@@ -1894,49 +1905,29 @@
}
@Override
- protected void setEnabledFunctions(String functions, boolean forceRestart,
- boolean usbDataUnlocked) {
+ protected void setEnabledFunctions(long functions, boolean forceRestart) {
if (DEBUG) {
Slog.d(TAG, "setEnabledFunctions functions=" + functions + ", "
- + "forceRestart=" + forceRestart + ", usbDataUnlocked=" + usbDataUnlocked);
+ + "forceRestart=" + forceRestart);
}
-
- if (usbDataUnlocked != mUsbDataUnlocked) {
- mUsbDataUnlocked = usbDataUnlocked;
- updateUsbNotification(false);
- forceRestart = true;
- }
-
- trySetEnabledFunctions(functions, forceRestart);
- }
-
- private void trySetEnabledFunctions(String functions, boolean forceRestart) {
- boolean chargingFunctions = false;
-
- if (functions == null || applyAdbFunction(functions)
- .equals(UsbManager.USB_FUNCTION_NONE)) {
- functions = getChargingFunctions();
- chargingFunctions = true;
- }
- functions = applyAdbFunction(functions);
-
- if (!mCurrentFunctions.equals(functions)
+ if (mCurrentFunctions != functions
|| !mCurrentFunctionsApplied
|| forceRestart) {
- Slog.i(TAG, "Setting USB config to " + functions);
+ Slog.i(TAG, "Setting USB config to " + UsbManager.usbFunctionsToString(functions));
mCurrentFunctions = functions;
mCurrentFunctionsApplied = false;
// set the flag to false as that would be stale value
mCurrentUsbFunctionsRequested = false;
- // Set the new USB configuration.
- setUsbConfig(mCurrentFunctions, chargingFunctions);
+ boolean chargingFunctions = functions == UsbManager.FUNCTION_NONE;
+ functions = getAppliedFunctions(functions);
- if (mBootCompleted
- && (UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_MTP)
- || UsbManager.containsFunction(functions, UsbManager.USB_FUNCTION_PTP))) {
+ // Set the new USB configuration.
+ setUsbConfig(functions, chargingFunctions);
+
+ if (mBootCompleted && isUsbDataTransferActive(functions)) {
// Start up dependent services.
- updateUsbStateBroadcastIfNeeded(true);
+ updateUsbStateBroadcastIfNeeded(functions, true);
}
}
}
@@ -1968,27 +1959,37 @@
return nativeOpenAccessory();
}
- /**
- * Checks whether the function is present in the USB configuration.
- *
- * @param function function to be checked.
- */
- public boolean isFunctionEnabled(String function) {
- return mHandler.isFunctionEnabled(function);
+ public long getCurrentFunctions() {
+ return mHandler.getEnabledFunctions();
+ }
+
+ public long getScreenUnlockedFunctions() {
+ return mHandler.getScreenUnlockedFunctions();
}
/**
* Adds function to the current USB configuration.
*
- * @param functions name of the USB function, or null to restore the default function.
- * @param usbDataUnlocked whether user data is accessible.
+ * @param functions The functions to set, or empty to set the charging function.
*/
- public void setCurrentFunctions(String functions, boolean usbDataUnlocked) {
+ public void setCurrentFunctions(long functions) {
if (DEBUG) {
- Slog.d(TAG, "setCurrentFunctions(" + functions + ", "
- + usbDataUnlocked + ")");
+ Slog.d(TAG, "setCurrentFunctions(" + UsbManager.usbFunctionsToString(functions) + ")");
}
- mHandler.sendMessage(MSG_SET_CURRENT_FUNCTIONS, functions, usbDataUnlocked);
+ if (functions == UsbManager.FUNCTION_NONE) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_CHARGING);
+ } else if (functions == UsbManager.FUNCTION_MTP) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_MTP);
+ } else if (functions == UsbManager.FUNCTION_PTP) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_PTP);
+ } else if (functions == UsbManager.FUNCTION_MIDI) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_MIDI);
+ } else if (functions == UsbManager.FUNCTION_RNDIS) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_RNDIS);
+ } else if (functions == UsbManager.FUNCTION_ACCESSORY) {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_USB_CONFIG_ACCESSORY);
+ }
+ mHandler.sendMessage(MSG_SET_CURRENT_FUNCTIONS, functions);
}
/**
@@ -1996,9 +1997,10 @@
*
* @param functions Functions to set.
*/
- public void setScreenUnlockedFunctions(String functions) {
+ public void setScreenUnlockedFunctions(long functions) {
if (DEBUG) {
- Slog.d(TAG, "setScreenUnlockedFunctions(" + functions + ")");
+ Slog.d(TAG, "setScreenUnlockedFunctions("
+ + UsbManager.usbFunctionsToString(functions) + ")");
}
mHandler.sendMessage(MSG_SET_SCREEN_UNLOCKED_FUNCTIONS, functions);
}
diff --git a/services/usb/java/com/android/server/usb/UsbService.java b/services/usb/java/com/android/server/usb/UsbService.java
index 1a20819..2f6e531 100644
--- a/services/usb/java/com/android/server/usb/UsbService.java
+++ b/services/usb/java/com/android/server/usb/UsbService.java
@@ -382,59 +382,44 @@
}
@Override
+ public void setCurrentFunctions(long functions) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ Preconditions.checkArgument(UsbManager.areSettableFunctions(functions));
+ Preconditions.checkState(mDeviceManager != null);
+ mDeviceManager.setCurrentFunctions(functions);
+ }
+
+ @Override
+ public void setCurrentFunction(String functions, boolean usbDataUnlocked) {
+ setCurrentFunctions(UsbManager.usbFunctionsFromString(functions));
+ }
+
+ @Override
public boolean isFunctionEnabled(String function) {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
- return mDeviceManager != null && mDeviceManager.isFunctionEnabled(function);
+ return (getCurrentFunctions() & UsbManager.usbFunctionsFromString(function)) != 0;
}
@Override
- public void setCurrentFunction(String function, boolean usbDataUnlocked) {
+ public long getCurrentFunctions() {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
-
- if (!isSupportedCurrentFunction(function)) {
- Slog.w(TAG, "Caller of setCurrentFunction() requested unsupported USB function: "
- + function);
- function = UsbManager.USB_FUNCTION_NONE;
- }
-
- if (mDeviceManager != null) {
- mDeviceManager.setCurrentFunctions(function, usbDataUnlocked);
- } else {
- throw new IllegalStateException("USB device mode not supported");
- }
+ Preconditions.checkState(mDeviceManager != null);
+ return mDeviceManager.getCurrentFunctions();
}
@Override
- public void setScreenUnlockedFunctions(String function) {
+ public void setScreenUnlockedFunctions(long functions) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ Preconditions.checkArgument(UsbManager.areSettableFunctions(functions));
+ Preconditions.checkState(mDeviceManager != null);
- if (!isSupportedCurrentFunction(function)) {
- Slog.w(TAG, "Caller of setScreenUnlockedFunctions() requested unsupported USB function:"
- + function);
- function = UsbManager.USB_FUNCTION_NONE;
- }
-
- if (mDeviceManager != null) {
- mDeviceManager.setScreenUnlockedFunctions(function);
- } else {
- throw new IllegalStateException("USB device mode not supported");
- }
+ mDeviceManager.setScreenUnlockedFunctions(functions);
}
- private static boolean isSupportedCurrentFunction(String function) {
- if (function == null) return true;
-
- switch (function) {
- case UsbManager.USB_FUNCTION_NONE:
- case UsbManager.USB_FUNCTION_AUDIO_SOURCE:
- case UsbManager.USB_FUNCTION_MIDI:
- case UsbManager.USB_FUNCTION_MTP:
- case UsbManager.USB_FUNCTION_PTP:
- case UsbManager.USB_FUNCTION_RNDIS:
- return true;
- }
-
- return false;
+ @Override
+ public long getScreenUnlockedFunctions() {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ Preconditions.checkState(mDeviceManager != null);
+ return mDeviceManager.getScreenUnlockedFunctions();
}
@Override
diff --git a/telephony/java/android/telephony/ServiceState.java b/telephony/java/android/telephony/ServiceState.java
index 90a3677..1176491 100644
--- a/telephony/java/android/telephony/ServiceState.java
+++ b/telephony/java/android/telephony/ServiceState.java
@@ -22,13 +22,13 @@
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
+import android.telephony.AccessNetworkConstants.AccessNetworkType;
import android.text.TextUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.Arrays;
-
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
/**
@@ -1340,6 +1340,39 @@
}
/** @hide */
+ public static int rilRadioTechnologyToAccessNetworkType(@RilRadioTechnology int rt) {
+ switch(rt) {
+ case RIL_RADIO_TECHNOLOGY_GPRS:
+ case RIL_RADIO_TECHNOLOGY_EDGE:
+ case RIL_RADIO_TECHNOLOGY_GSM:
+ return AccessNetworkType.GERAN;
+ case RIL_RADIO_TECHNOLOGY_UMTS:
+ case RIL_RADIO_TECHNOLOGY_HSDPA:
+ case RIL_RADIO_TECHNOLOGY_HSPAP:
+ case RIL_RADIO_TECHNOLOGY_HSUPA:
+ case RIL_RADIO_TECHNOLOGY_HSPA:
+ case RIL_RADIO_TECHNOLOGY_TD_SCDMA:
+ return AccessNetworkType.UTRAN;
+ case RIL_RADIO_TECHNOLOGY_IS95A:
+ case RIL_RADIO_TECHNOLOGY_IS95B:
+ case RIL_RADIO_TECHNOLOGY_1xRTT:
+ case RIL_RADIO_TECHNOLOGY_EVDO_0:
+ case RIL_RADIO_TECHNOLOGY_EVDO_A:
+ case RIL_RADIO_TECHNOLOGY_EVDO_B:
+ case RIL_RADIO_TECHNOLOGY_EHRPD:
+ return AccessNetworkType.CDMA2000;
+ case RIL_RADIO_TECHNOLOGY_LTE:
+ case RIL_RADIO_TECHNOLOGY_LTE_CA:
+ return AccessNetworkType.EUTRAN;
+ case RIL_RADIO_TECHNOLOGY_IWLAN:
+ return AccessNetworkType.IWLAN;
+ case RIL_RADIO_TECHNOLOGY_UNKNOWN:
+ default:
+ return AccessNetworkType.UNKNOWN;
+ }
+ }
+
+ /** @hide */
public int getDataNetworkType() {
return rilRadioTechnologyToNetworkType(mRilDataRadioTechnology);
}
diff --git a/telephony/java/com/android/internal/telephony/RILConstants.java b/telephony/java/com/android/internal/telephony/RILConstants.java
index cdee9e6..a3a3080 100644
--- a/telephony/java/com/android/internal/telephony/RILConstants.java
+++ b/telephony/java/com/android/internal/telephony/RILConstants.java
@@ -220,11 +220,6 @@
String SETUP_DATA_PROTOCOL_IPV6 = "IPV6";
String SETUP_DATA_PROTOCOL_IPV4V6 = "IPV4V6";
- /* Deactivate data call reasons */
- int DEACTIVATE_REASON_NONE = 0;
- int DEACTIVATE_REASON_RADIO_OFF = 1;
- int DEACTIVATE_REASON_PDP_RESET = 2;
-
/* NV config radio reset types. */
int NV_CONFIG_RELOAD_RESET = 1;
int NV_CONFIG_ERASE_RESET = 2;
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index ebf5f68..c8f96c9 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -285,7 +285,8 @@
<activity
android:name="ColoredShadowsActivity"
- android:label="View/ColoredShadows">
+ android:label="View/ColoredShadows"
+ android:theme="@style/ThemeColoredShadows">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="com.android.test.hwui.TEST" />
diff --git a/tests/HwAccelerationTest/res/values/styles.xml b/tests/HwAccelerationTest/res/values/styles.xml
index 108709b..fa5437f 100644
--- a/tests/HwAccelerationTest/res/values/styles.xml
+++ b/tests/HwAccelerationTest/res/values/styles.xml
@@ -34,4 +34,11 @@
<item name="android:translationZ">400dp</item>
<item name="android:layout_alignParentBottom">true</item>
</style>
+
+ <style name="ThemeColoredShadows" parent="@android:style/Theme.Material.Light">
+ <!--
+ <item name="android:ambientShadowAlpha">0</item>
+ <item name="android:spotShadowAlpha">1</item>
+ -->
+ </style>
</resources>
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java
index 135c93c..901d90e 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ColoredShadowsActivity.java
@@ -17,6 +17,9 @@
package com.android.test.hwui;
import android.app.Activity;
+import android.graphics.Color;
+import android.graphics.PixelFormat;
+import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
@@ -36,7 +39,9 @@
private void setShadowColors(ViewGroup row, int rowIndex) {
for (int i = 0; i < row.getChildCount(); i++) {
View view = row.getChildAt(i);
- view.setShadowColor(shadowColorFor(view));
+ //view.setBackground(new MyHackyBackground());
+ view.setOutlineSpotShadowColor(shadowColorFor(view));
+ view.setOutlineAmbientShadowColor(shadowColorFor(view));
view.setElevation(6.0f * (rowIndex + 1));
}
}
@@ -44,12 +49,27 @@
private int shadowColorFor(View view) {
switch (view.getId()) {
case R.id.grey: return 0xFF3C4043;
- case R.id.blue: return 0xFF185ABC;
- case R.id.red: return 0xFFB31412;
- case R.id.yellow: return 0xFFEA8600;
- case R.id.green: return 0xFF137333;
+ case R.id.blue: return Color.BLUE;
+ case R.id.red: return 0xFFEA4335;
+ case R.id.yellow: return 0xFFFBBC04;
+ case R.id.green: return 0xFF34A853;
default: return 0xFF000000;
}
}
+ private static class MyHackyBackground extends ColorDrawable {
+ MyHackyBackground() {
+ super(0);
+ }
+
+ @Override
+ public int getOpacity() {
+ return PixelFormat.TRANSLUCENT;
+ }
+
+ @Override
+ public int getAlpha() {
+ return 254;
+ }
+ }
}
diff --git a/tests/UsbTests/Android.mk b/tests/UsbTests/Android.mk
new file mode 100644
index 0000000..a04f32a
--- /dev/null
+++ b/tests/UsbTests/Android.mk
@@ -0,0 +1,44 @@
+#
+# 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.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_STATIC_JAVA_LIBRARIES := \
+ frameworks-base-testutils \
+ android-support-test \
+ mockito-target-inline-minus-junit4 \
+ platform-test-annotations \
+ services.core \
+ services.net \
+ services.usb \
+ truth-prebuilt \
+
+LOCAL_JNI_SHARED_LIBRARIES := \
+ libdexmakerjvmtiagent \
+
+LOCAL_CERTIFICATE := platform
+
+LOCAL_PACKAGE_NAME := UsbTests
+
+LOCAL_COMPATIBILITY_SUITE := device-tests
+
+include $(BUILD_PACKAGE)
diff --git a/tests/UsbTests/AndroidManifest.xml b/tests/UsbTests/AndroidManifest.xml
new file mode 100644
index 0000000..5d60695
--- /dev/null
+++ b/tests/UsbTests/AndroidManifest.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- 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.
+-->
+
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.server.usb" >
+
+ <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS" />
+ <uses-permission android:name="android.permission.MANAGE_USERS" />
+
+ <application android:debuggable="true">
+ <uses-library android:name="android.test.runner" />
+ </application>
+
+ <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"
+ android:targetPackage="com.android.server.usb"
+ android:label="UsbTests"/>
+</manifest>
diff --git a/tests/UsbTests/AndroidTest.xml b/tests/UsbTests/AndroidTest.xml
new file mode 100644
index 0000000..0b623fb
--- /dev/null
+++ b/tests/UsbTests/AndroidTest.xml
@@ -0,0 +1,29 @@
+<!-- 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.
+-->
+<configuration description="Runs sample instrumentation test.">
+ <target_preparer class="com.android.tradefed.targetprep.TestFilePushSetup"/>
+ <target_preparer class="com.android.tradefed.targetprep.TestAppInstallSetup">
+ <option name="test-file-name" value="UsbTests.apk"/>
+ </target_preparer>
+ <target_preparer class="com.android.tradefed.targetprep.PushFilePreparer"/>
+ <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer"/>
+ <option name="test-suite-tag" value="apct"/>
+ <option name="test-tag" value="UsbTests"/>
+
+ <test class="com.android.tradefed.testtype.AndroidJUnitTest">
+ <option name="package" value="com.android.server.usb"/>
+ <option name="runner" value="android.support.test.runner.AndroidJUnitRunner"/>
+ </test>
+</configuration>
\ No newline at end of file
diff --git a/tests/UsbTests/src/com/android/server/usb/UsbHandlerTest.java b/tests/UsbTests/src/com/android/server/usb/UsbHandlerTest.java
new file mode 100644
index 0000000..c491b46
--- /dev/null
+++ b/tests/UsbTests/src/com/android/server/usb/UsbHandlerTest.java
@@ -0,0 +1,316 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.server.usb;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.hardware.usb.UsbManager;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.UserHandle;
+import android.provider.Settings;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import com.android.server.FgThread;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+
+/**
+ * Tests for UsbHandler state changes.
+ */
+@RunWith(AndroidJUnit4.class)
+public class UsbHandlerTest {
+ private static final String TAG = UsbHandlerTest.class.getSimpleName();
+
+ @Mock
+ private UsbDeviceManager mUsbDeviceManager;
+ @Mock
+ private UsbDebuggingManager mUsbDebuggingManager;
+ @Mock
+ private UsbAlsaManager mUsbAlsaManager;
+ @Mock
+ private UsbSettingsManager mUsbSettingsManager;
+ @Mock
+ private SharedPreferences mSharedPreferences;
+ @Mock
+ private SharedPreferences.Editor mEditor;
+
+ private MockUsbHandler mUsbHandler;
+
+ private static final int MSG_UPDATE_STATE = 0;
+ private static final int MSG_ENABLE_ADB = 1;
+ private static final int MSG_SET_CURRENT_FUNCTIONS = 2;
+ private static final int MSG_SYSTEM_READY = 3;
+ private static final int MSG_BOOT_COMPLETED = 4;
+ private static final int MSG_USER_SWITCHED = 5;
+ private static final int MSG_UPDATE_USER_RESTRICTIONS = 6;
+ private static final int MSG_SET_SCREEN_UNLOCKED_FUNCTIONS = 12;
+ private static final int MSG_UPDATE_SCREEN_LOCK = 13;
+
+ private Map<String, String> mMockProperties;
+ private Map<String, Integer> mMockGlobalSettings;
+
+ private class MockUsbHandler extends UsbDeviceManager.UsbHandler {
+ boolean mIsUsbTransferAllowed;
+ Intent mBroadcastedIntent;
+
+ MockUsbHandler(Looper looper, Context context, UsbDeviceManager deviceManager,
+ UsbDebuggingManager debuggingManager, UsbAlsaManager alsaManager,
+ UsbSettingsManager settingsManager) {
+ super(looper, context, deviceManager, debuggingManager, alsaManager, settingsManager);
+ mUseUsbNotification = false;
+ mIsUsbTransferAllowed = true;
+ mCurrentUsbFunctionsReceived = true;
+ }
+
+ @Override
+ protected void setEnabledFunctions(long functions, boolean force) {
+ mCurrentFunctions = functions;
+ }
+
+ @Override
+ protected void setSystemProperty(String property, String value) {
+ mMockProperties.put(property, value);
+ }
+
+ @Override
+ protected void putGlobalSettings(ContentResolver resolver, String setting, int val) {
+ mMockGlobalSettings.put(setting, val);
+ }
+
+ @Override
+ protected String getSystemProperty(String property, String def) {
+ if (mMockProperties.containsKey(property)) {
+ return mMockProperties.get(property);
+ }
+ return def;
+ }
+
+ @Override
+ protected boolean isUsbTransferAllowed() {
+ return mIsUsbTransferAllowed;
+ }
+
+ @Override
+ protected SharedPreferences getPinnedSharedPrefs(Context context) {
+ return mSharedPreferences;
+ }
+
+ @Override
+ protected void sendStickyBroadcast(Intent intent) {
+ mBroadcastedIntent = intent;
+ }
+ }
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ mMockProperties = new HashMap<>();
+ mMockGlobalSettings = new HashMap<>();
+ when(mSharedPreferences.edit()).thenReturn(mEditor);
+
+ mUsbHandler = new MockUsbHandler(FgThread.get().getLooper(),
+ InstrumentationRegistry.getContext(), mUsbDeviceManager, mUsbDebuggingManager,
+ mUsbAlsaManager, mUsbSettingsManager);
+ }
+
+ @SmallTest
+ public void setFunctionsMtp() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+ }
+
+ @SmallTest
+ public void setFunctionsPtp() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_PTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_PTP, 0);
+ }
+
+ @SmallTest
+ public void setFunctionsMidi() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MIDI));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MIDI, 0);
+ }
+
+ @SmallTest
+ public void setFunctionsRndis() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_RNDIS));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_RNDIS, 0);
+ }
+
+ @SmallTest
+ public void enableAdb() {
+ sendBootCompleteMessages(mUsbHandler);
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_ENABLE_ADB, 1));
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ assertTrue(mUsbHandler.mAdbEnabled);
+ assertEquals(mMockProperties.get(UsbDeviceManager.UsbHandler
+ .USB_PERSISTENT_CONFIG_PROPERTY), UsbManager.USB_FUNCTION_ADB);
+ verify(mUsbDebuggingManager).setAdbEnabled(true);
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_STATE, 1, 1));
+
+ assertTrue(mUsbHandler.mBroadcastedIntent.getBooleanExtra(UsbManager.USB_CONNECTED, false));
+ assertTrue(mUsbHandler.mBroadcastedIntent
+ .getBooleanExtra(UsbManager.USB_CONFIGURED, false));
+ assertTrue(mUsbHandler.mBroadcastedIntent
+ .getBooleanExtra(UsbManager.USB_FUNCTION_ADB, false));
+ }
+
+ @SmallTest
+ public void disableAdb() {
+ mMockProperties.put(UsbDeviceManager.UsbHandler.USB_PERSISTENT_CONFIG_PROPERTY,
+ UsbManager.USB_FUNCTION_ADB);
+ mUsbHandler = new MockUsbHandler(FgThread.get().getLooper(),
+ InstrumentationRegistry.getContext(), mUsbDeviceManager, mUsbDebuggingManager,
+ mUsbAlsaManager, mUsbSettingsManager);
+
+ sendBootCompleteMessages(mUsbHandler);
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_ENABLE_ADB, 0));
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ assertFalse(mUsbHandler.mAdbEnabled);
+ assertEquals(mMockProperties.get(UsbDeviceManager.UsbHandler
+ .USB_PERSISTENT_CONFIG_PROPERTY), "");
+ verify(mUsbDebuggingManager).setAdbEnabled(false);
+ }
+
+ @SmallTest
+ public void bootCompletedCharging() {
+ sendBootCompleteMessages(mUsbHandler);
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ }
+
+ @Test
+ @SmallTest
+ public void bootCompletedAdbEnabled() {
+ mMockProperties.put(UsbDeviceManager.UsbHandler.USB_PERSISTENT_CONFIG_PROPERTY, "adb");
+ mUsbHandler = new MockUsbHandler(FgThread.get().getLooper(),
+ InstrumentationRegistry.getContext(), mUsbDeviceManager, mUsbDebuggingManager,
+ mUsbAlsaManager, mUsbSettingsManager);
+
+ sendBootCompleteMessages(mUsbHandler);
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ assertEquals(mMockGlobalSettings.get(Settings.Global.ADB_ENABLED).intValue(), 1);
+ assertTrue(mUsbHandler.mAdbEnabled);
+ verify(mUsbDebuggingManager).setAdbEnabled(true);
+ }
+
+ @SmallTest
+ public void userSwitchedDisablesMtp() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_USER_SWITCHED,
+ UserHandle.getCallingUserId() + 1));
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ }
+
+ @SmallTest
+ public void changedRestrictionsDisablesMtp() {
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+
+ mUsbHandler.mIsUsbTransferAllowed = false;
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_USER_RESTRICTIONS));
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ }
+
+ @SmallTest
+ public void disconnectResetsCharging() {
+ sendBootCompleteMessages(mUsbHandler);
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_STATE, 0, 0));
+
+ assertEquals(mUsbHandler.getEnabledFunctions(), UsbManager.FUNCTION_NONE);
+ }
+
+ @SmallTest
+ public void configuredSendsBroadcast() {
+ sendBootCompleteMessages(mUsbHandler);
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_CURRENT_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_STATE, 1, 1));
+
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+ assertTrue(mUsbHandler.mBroadcastedIntent.getBooleanExtra(UsbManager.USB_CONNECTED, false));
+ assertTrue(mUsbHandler.mBroadcastedIntent
+ .getBooleanExtra(UsbManager.USB_CONFIGURED, false));
+ assertTrue(mUsbHandler.mBroadcastedIntent
+ .getBooleanExtra(UsbManager.USB_FUNCTION_MTP, false));
+ }
+
+ @SmallTest
+ public void setScreenUnlockedFunctions() {
+ sendBootCompleteMessages(mUsbHandler);
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_SCREEN_LOCK, 0));
+
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_SET_SCREEN_UNLOCKED_FUNCTIONS,
+ UsbManager.FUNCTION_MTP));
+ assertNotEquals(mUsbHandler.getScreenUnlockedFunctions() & UsbManager.FUNCTION_MTP, 0);
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+ verify(mEditor).putString(String.format(Locale.ENGLISH,
+ UsbDeviceManager.UNLOCKED_CONFIG_PREF, mUsbHandler.mCurrentUser),
+ UsbManager.USB_FUNCTION_MTP);
+ }
+
+ @SmallTest
+ public void unlockScreen() {
+ when(mSharedPreferences.getString(String.format(Locale.ENGLISH,
+ UsbDeviceManager.UNLOCKED_CONFIG_PREF, mUsbHandler.mCurrentUser), ""))
+ .thenReturn(UsbManager.USB_FUNCTION_MTP);
+ sendBootCompleteMessages(mUsbHandler);
+ mUsbHandler.handleMessage(mUsbHandler.obtainMessage(MSG_UPDATE_SCREEN_LOCK, 0));
+
+ assertNotEquals(mUsbHandler.getScreenUnlockedFunctions() & UsbManager.FUNCTION_MTP, 0);
+ assertNotEquals(mUsbHandler.getEnabledFunctions() & UsbManager.FUNCTION_MTP, 0);
+ }
+
+ private static void sendBootCompleteMessages(Handler handler) {
+ handler.handleMessage(handler.obtainMessage(MSG_BOOT_COMPLETED));
+ handler.handleMessage(handler.obtainMessage(MSG_SYSTEM_READY));
+ }
+}
\ No newline at end of file
diff --git a/tests/net/java/com/android/server/connectivity/TetheringTest.java b/tests/net/java/com/android/server/connectivity/TetheringTest.java
index 099cfd4..e692652 100644
--- a/tests/net/java/com/android/server/connectivity/TetheringTest.java
+++ b/tests/net/java/com/android/server/connectivity/TetheringTest.java
@@ -311,7 +311,7 @@
// Emulate pressing the USB tethering button in Settings UI.
mTethering.startTethering(TETHERING_USB, null, false);
mLooper.dispatchAll();
- verify(mUsbManager, times(1)).setCurrentFunction(UsbManager.USB_FUNCTION_RNDIS, false);
+ verify(mUsbManager, times(1)).setCurrentFunctions(UsbManager.FUNCTION_RNDIS);
// Pretend we receive a USB connected broadcast. Here we also pretend
// that the RNDIS function is somehow enabled, so that we see if we