Merge "Register new AIDL SensorManager"
diff --git a/GAME_MANAGER_OWNERS b/GAME_MANAGER_OWNERS
index 502a9e36..b65c43a 100644
--- a/GAME_MANAGER_OWNERS
+++ b/GAME_MANAGER_OWNERS
@@ -1,2 +1,3 @@
lpy@google.com
-timvp@google.com
+chingtangyu@google.com
+xwxw@google.com
diff --git a/apct-tests/perftests/core/Android.bp b/apct-tests/perftests/core/Android.bp
index 23464f8..9366ff2d 100644
--- a/apct-tests/perftests/core/Android.bp
+++ b/apct-tests/perftests/core/Android.bp
@@ -43,6 +43,9 @@
"apct-perftests-resources-manager-apps",
"apct-perftests-utils",
"collector-device-lib",
+ "compatibility-device-util-axt",
+ "junit",
+ "junit-params",
"core-tests-support",
"guava",
],
@@ -59,4 +62,10 @@
test_suites: ["device-tests"],
certificate: "platform",
+
+ errorprone: {
+ javacflags: [
+ "-Xep:ReturnValueIgnored:WARN",
+ ],
+ },
}
diff --git a/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java
index 3f4f6af..3ebaa4c 100644
--- a/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/DeepArrayOpsPerfTest.java
@@ -20,18 +20,19 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class DeepArrayOpsPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -39,19 +40,14 @@
private Object[] mArray;
private Object[] mArray2;
- @Parameterized.Parameter(0)
- public int mArrayLength;
-
- @Parameterized.Parameters(name = "mArrayLength({0})")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{1}, {4}, {16}, {32}, {2048}});
}
- @Before
- public void setUp() throws Exception {
- mArray = new Object[mArrayLength * 14];
- mArray2 = new Object[mArrayLength * 14];
- for (int i = 0; i < mArrayLength; i += 14) {
+ public void setUp(int arrayLength) throws Exception {
+ mArray = new Object[arrayLength * 14];
+ mArray2 = new Object[arrayLength * 14];
+ for (int i = 0; i < arrayLength; i += 14) {
mArray[i] = new IntWrapper(i);
mArray2[i] = new IntWrapper(i);
@@ -99,7 +95,9 @@
}
@Test
- public void deepHashCode() {
+ @Parameters(method = "getData")
+ public void deepHashCode(int arrayLength) throws Exception {
+ setUp(arrayLength);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
Arrays.deepHashCode(mArray);
@@ -107,7 +105,9 @@
}
@Test
- public void deepEquals() {
+ @Parameters(method = "getData")
+ public void deepEquals(int arrayLength) throws Exception {
+ setUp(arrayLength);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
Arrays.deepEquals(mArray, mArray2);
diff --git a/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java b/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java
index 2ef68ca..05a3e12 100644
--- a/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/ReferencePerfTest.java
@@ -118,7 +118,7 @@
int got = count.get();
if (n != got) {
throw new IllegalStateException(
- String.format("Only %i of %i objects finalized?", got, n));
+ String.format("Only %d of %d objects finalized?", got, n));
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java b/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java
index 5aacfc2..20f1309 100644
--- a/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/SystemArrayCopyPerfTest.java
@@ -20,22 +20,22 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class SystemArrayCopyPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "arrayLength={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{2}, {4}, {8}, {16}, {32}, {64}, {128}, {256}, {512}, {1024}, {2048}, {4096},
@@ -43,12 +43,10 @@
});
}
- @Parameterized.Parameter(0)
- public int arrayLength;
-
// Provides benchmarking for different types of arrays using the arraycopy function.
@Test
- public void timeSystemCharArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemCharArrayCopy(int arrayLength) {
final int len = arrayLength;
char[] src = new char[len];
char[] dst = new char[len];
@@ -59,7 +57,8 @@
}
@Test
- public void timeSystemByteArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemByteArrayCopy(int arrayLength) {
final int len = arrayLength;
byte[] src = new byte[len];
byte[] dst = new byte[len];
@@ -70,7 +69,8 @@
}
@Test
- public void timeSystemShortArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemShortArrayCopy(int arrayLength) {
final int len = arrayLength;
short[] src = new short[len];
short[] dst = new short[len];
@@ -81,7 +81,8 @@
}
@Test
- public void timeSystemIntArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemIntArrayCopy(int arrayLength) {
final int len = arrayLength;
int[] src = new int[len];
int[] dst = new int[len];
@@ -92,7 +93,8 @@
}
@Test
- public void timeSystemLongArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemLongArrayCopy(int arrayLength) {
final int len = arrayLength;
long[] src = new long[len];
long[] dst = new long[len];
@@ -103,7 +105,8 @@
}
@Test
- public void timeSystemFloatArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemFloatArrayCopy(int arrayLength) {
final int len = arrayLength;
float[] src = new float[len];
float[] dst = new float[len];
@@ -114,7 +117,8 @@
}
@Test
- public void timeSystemDoubleArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemDoubleArrayCopy(int arrayLength) {
final int len = arrayLength;
double[] src = new double[len];
double[] dst = new double[len];
@@ -125,7 +129,8 @@
}
@Test
- public void timeSystemBooleanArrayCopy() {
+ @Parameters(method = "getData")
+ public void timeSystemBooleanArrayCopy(int arrayLength) {
final int len = arrayLength;
boolean[] src = new boolean[len];
boolean[] dst = new boolean[len];
diff --git a/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java b/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java
index eec0734..b1b594d 100644
--- a/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/XmlSerializePerfTest.java
@@ -20,42 +20,32 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import org.xmlpull.v1.XmlSerializer;
import java.io.CharArrayWriter;
import java.lang.reflect.Constructor;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.Random;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class XmlSerializePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mDatasetAsString({0}), mSeed({1})")
- public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {"0.99 0.7 0.7 0.7 0.7 0.7", 854328},
- {"0.999 0.3 0.3 0.95 0.9 0.9", 854328},
- {"0.99 0.7 0.7 0.7 0.7 0.7", 312547},
- {"0.999 0.3 0.3 0.95 0.9 0.9", 312547}
- });
+ private Object[] getParams() {
+ return new Object[][] {
+ new Object[] {"0.99 0.7 0.7 0.7 0.7 0.7", 854328},
+ new Object[] {"0.999 0.3 0.3 0.95 0.9 0.9", 854328},
+ new Object[] {"0.99 0.7 0.7 0.7 0.7 0.7", 312547},
+ new Object[] {"0.999 0.3 0.3 0.95 0.9 0.9", 312547}
+ };
}
- @Parameterized.Parameter(0)
- public String mDatasetAsString;
-
- @Parameterized.Parameter(1)
- public int mSeed;
-
double[] mDataset;
private Constructor<? extends XmlSerializer> mKxmlConstructor;
private Constructor<? extends XmlSerializer> mFastConstructor;
@@ -100,8 +90,7 @@
}
@SuppressWarnings("unchecked")
- @Before
- public void setUp() throws Exception {
+ public void setUp(String datasetAsString) throws Exception {
mKxmlConstructor =
(Constructor)
Class.forName("com.android.org.kxml2.io.KXmlSerializer").getConstructor();
@@ -109,28 +98,32 @@
(Constructor)
Class.forName("com.android.internal.util.FastXmlSerializer")
.getConstructor();
- String[] splitStrings = mDatasetAsString.split(" ");
+ String[] splitStrings = datasetAsString.split(" ");
mDataset = new double[splitStrings.length];
for (int i = 0; i < splitStrings.length; i++) {
mDataset[i] = Double.parseDouble(splitStrings[i]);
}
}
- private void internalTimeSerializer(Constructor<? extends XmlSerializer> ctor)
+ private void internalTimeSerializer(Constructor<? extends XmlSerializer> ctor, int seed)
throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- serializeRandomXml(ctor, mSeed);
+ serializeRandomXml(ctor, seed);
}
}
@Test
- public void timeKxml() throws Exception {
- internalTimeSerializer(mKxmlConstructor);
+ @Parameters(method = "getParams")
+ public void timeKxml(String datasetAsString, int seed) throws Exception {
+ setUp(datasetAsString);
+ internalTimeSerializer(mKxmlConstructor, seed);
}
@Test
- public void timeFast() throws Exception {
- internalTimeSerializer(mFastConstructor);
+ @Parameters(method = "getParams")
+ public void timeFast(String datasetAsString, int seed) throws Exception {
+ setUp(datasetAsString);
+ internalTimeSerializer(mFastConstructor, seed);
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java b/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java
index 31c92ba..3a45d40 100644
--- a/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/ZipFilePerfTest.java
@@ -20,12 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.FileOutputStream;
@@ -38,23 +38,18 @@
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class ZipFilePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
private File mFile;
- @Parameters(name = "numEntries={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{128}, {1024}, {8192}});
}
- @Parameterized.Parameter(0)
- public int numEntries;
-
- @Before
- public void setUp() throws Exception {
+ public void setUp(int numEntries) throws Exception {
mFile = File.createTempFile(getClass().getName(), ".zip");
mFile.deleteOnExit();
writeEntries(new ZipOutputStream(new FileOutputStream(mFile)), numEntries, 0);
@@ -66,7 +61,9 @@
}
@Test
- public void timeZipFileOpen() throws Exception {
+ @Parameters(method = "getData")
+ public void timeZipFileOpen(int numEntries) throws Exception {
+ setUp(numEntries);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
ZipFile zf = new ZipFile(mFile);
diff --git a/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java b/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java
index faa9628..2e89518 100644
--- a/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/ZipFileReadPerfTest.java
@@ -20,12 +20,13 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.FileOutputStream;
@@ -39,21 +40,17 @@
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class ZipFileReadPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "readBufferSize={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{1024}, {16384}, {65536}});
}
private File mFile;
- @Parameterized.Parameter(0)
- public int readBufferSize;
-
@Before
public void setUp() throws Exception {
mFile = File.createTempFile(getClass().getName(), ".zip");
@@ -90,7 +87,8 @@
}
@Test
- public void timeZipFileRead() throws Exception {
+ @Parameters(method = "getData")
+ public void timeZipFileRead(int readBufferSize) throws Exception {
byte[] readBuffer = new byte[readBufferSize];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java
index db5462c..2c0473e 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/BitSetPerfTest.java
@@ -20,96 +20,99 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class BitSetPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mSize={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{1000}, {10000}});
}
- @Parameterized.Parameter(0)
- public int mSize;
-
- private BitSet mBitSet;
-
- @Before
- public void setUp() throws Exception {
- mBitSet = new BitSet(mSize);
- }
-
@Test
- public void timeIsEmptyTrue() {
+ @Parameters(method = "getData")
+ public void timeIsEmptyTrue(int size) {
+ BitSet bitSet = new BitSet(size);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- if (!mBitSet.isEmpty()) throw new RuntimeException();
+ if (!bitSet.isEmpty()) throw new RuntimeException();
}
}
@Test
- public void timeIsEmptyFalse() {
- mBitSet.set(mBitSet.size() - 1);
+ @Parameters(method = "getData")
+ public void timeIsEmptyFalse(int size) {
+ BitSet bitSet = new BitSet(size);
+ bitSet.set(bitSet.size() - 1);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- if (mBitSet.isEmpty()) throw new RuntimeException();
+ if (bitSet.isEmpty()) throw new RuntimeException();
}
}
@Test
- public void timeGet() {
+ @Parameters(method = "getData")
+ public void timeGet(int size) {
+ BitSet bitSet = new BitSet(size);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
int i = 1;
while (state.keepRunning()) {
- mBitSet.get(++i % mSize);
+ bitSet.get(++i % size);
}
}
@Test
- public void timeClear() {
+ @Parameters(method = "getData")
+ public void timeClear(int size) {
+ BitSet bitSet = new BitSet(size);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
int i = 1;
while (state.keepRunning()) {
- mBitSet.clear(++i % mSize);
+ bitSet.clear(++i % size);
}
}
@Test
- public void timeSet() {
+ @Parameters(method = "getData")
+ public void timeSet(int size) {
+ BitSet bitSet = new BitSet(size);
int i = 1;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mBitSet.set(++i % mSize);
+ bitSet.set(++i % size);
}
}
@Test
- public void timeSetOn() {
+ @Parameters(method = "getData")
+ public void timeSetOn(int size) {
+ BitSet bitSet = new BitSet(size);
int i = 1;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mBitSet.set(++i % mSize, true);
+ bitSet.set(++i % size, true);
}
}
@Test
- public void timeSetOff() {
+ @Parameters(method = "getData")
+ public void timeSetOff(int size) {
+ BitSet bitSet = new BitSet(size);
int i = 1;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mBitSet.set(++i % mSize, false);
+ bitSet.set(++i % size, false);
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java
index 3952c12..6a2ce58 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/BreakIteratorPerfTest.java
@@ -20,18 +20,19 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.text.BreakIterator;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public final class BreakIteratorPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -41,36 +42,37 @@
Locale.US,
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi mollis consequat"
+ " nisl non pharetra. Praesent pretium vehicula odio sed ultrices. Aenean a"
- + " felis libero. Vivamus sed commodo nibh. Pellentesque turpis lectus, euismod"
- + " vel ante nec, cursus posuere orci. Suspendisse velit neque, fermentum"
- + " luctus ultrices in, ultrices vitae arcu. Duis tincidunt cursus lorem. Nam"
- + " ultricies accumsan quam vitae imperdiet. Pellentesque habitant morbi"
- + " tristique senectus et netus et malesuada fames ac turpis egestas. Quisque"
- + " aliquet pretium nisi, eget laoreet enim molestie sit amet. Class aptent"
- + " taciti sociosqu ad litora torquent per conubia nostra, per inceptos"
+ + " felis libero. Vivamus sed commodo nibh. Pellentesque turpis lectus,"
+ + " euismod vel ante nec, cursus posuere orci. Suspendisse velit neque,"
+ + " fermentum luctus ultrices in, ultrices vitae arcu. Duis tincidunt cursus"
+ + " lorem. Nam ultricies accumsan quam vitae imperdiet. Pellentesque habitant"
+ + " morbi tristique senectus et netus et malesuada fames ac turpis egestas."
+ + " Quisque aliquet pretium nisi, eget laoreet enim molestie sit amet. Class"
+ + " aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos"
+ " himenaeos.\n"
+ "Nam dapibus aliquam lacus ac suscipit. Proin in nibh sit amet purus congue"
+ " laoreet eget quis nisl. Morbi gravida dignissim justo, a venenatis ante"
- + " pulvinar at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin"
- + " ultrices vestibulum dui, vel aliquam lacus aliquam quis. Duis fringilla"
- + " sapien ac lacus egestas, vel adipiscing elit euismod. Donec non tellus"
- + " odio. Donec gravida eu massa ac feugiat. Aliquam erat volutpat. Praesent id"
- + " adipiscing metus, nec laoreet enim. Aliquam vitae posuere turpis. Mauris ac"
- + " pharetra sem. In at placerat tortor. Vivamus ac vehicula neque. Cras"
- + " volutpat ullamcorper massa et varius. Praesent sagittis neque vitae nulla"
- + " euismod pharetra.\n"
+ + " pulvinar at. Lorem ipsum dolor sit amet, consectetur adipiscing elit."
+ + " Proin ultrices vestibulum dui, vel aliquam lacus aliquam quis. Duis"
+ + " fringilla sapien ac lacus egestas, vel adipiscing elit euismod. Donec non"
+ + " tellus odio. Donec gravida eu massa ac feugiat. Aliquam erat volutpat."
+ + " Praesent id adipiscing metus, nec laoreet enim. Aliquam vitae posuere"
+ + " turpis. Mauris ac pharetra sem. In at placerat tortor. Vivamus ac vehicula"
+ + " neque. Cras volutpat ullamcorper massa et varius. Praesent sagittis neque"
+ + " vitae nulla euismod pharetra.\n"
+ "Sed placerat sapien non molestie sollicitudin. Nullam sit amet dictum quam."
+ " Etiam tincidunt tortor vel pretium vehicula. Praesent fringilla ipsum vel"
+ " velit luctus dignissim. Nulla massa ligula, mattis in enim et, mattis"
+ " lacinia odio. Suspendisse tristique urna a orci commodo tempor. Duis"
+ " lacinia egestas arcu a sollicitudin.\n"
+ "In ac feugiat lacus. Nunc fermentum eu est at tristique. Pellentesque quis"
- + " ligula et orci placerat lacinia. Maecenas quis mauris diam. Etiam mi ipsum,"
- + " tempus in purus quis, euismod faucibus orci. Nulla facilisi. Praesent sit"
- + " amet sapien vel elit porta adipiscing. Phasellus sit amet volutpat diam.\n"
- + "Proin bibendum elit non lacus pharetra, quis eleifend tellus placerat. Nulla"
- + " facilisi. Maecenas ante diam, pellentesque mattis mattis in, porta ut"
- + " lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices"
+ + " ligula et orci placerat lacinia. Maecenas quis mauris diam. Etiam mi"
+ + " ipsum, tempus in purus quis, euismod faucibus orci. Nulla facilisi."
+ + " Praesent sit amet sapien vel elit porta adipiscing. Phasellus sit amet"
+ + " volutpat diam.\n"
+ + "Proin bibendum elit non lacus pharetra, quis eleifend tellus placerat."
+ + " Nulla facilisi. Maecenas ante diam, pellentesque mattis mattis in, porta"
+ + " ut lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices"
+ " posuere cubilia Curae; Nunc interdum tristique metus, in scelerisque odio"
+ " fermentum eget. Cras nec venenatis lacus. Aenean euismod eget metus quis"
+ " molestie. Cras tincidunt dolor ut massa ornare, in elementum lacus auctor."
@@ -80,29 +82,29 @@
LONGPARA(
Locale.US,
"During dinner, Mr. Bennet scarcely spoke at all; but when the servants were"
- + " withdrawn, he thought it time to have some conversation with his guest, and"
- + " therefore started a subject in which he expected him to shine, by observing"
- + " that he seemed very fortunate in his patroness. Lady Catherine de Bourgh's"
- + " attention to his wishes, and consideration for his comfort, appeared very"
- + " remarkable. Mr. Bennet could not have chosen better. Mr. Collins was"
- + " eloquent in her praise. The subject elevated him to more than usual"
- + " solemnity of manner, and with a most important aspect he protested that"
- + " \"he had never in his life witnessed such behaviour in a person of"
- + " rank--such affability and condescension, as he had himself experienced from"
- + " Lady Catherine. She had been graciously pleased to approve of both of the"
- + " discourses which he had already had the honour of preaching before her. She"
- + " had also asked him twice to dine at Rosings, and had sent for him only the"
- + " Saturday before, to make up her pool of quadrille in the evening. Lady"
- + " Catherine was reckoned proud by many people he knew, but _he_ had never"
- + " seen anything but affability in her. She had always spoken to him as she"
- + " would to any other gentleman; she made not the smallest objection to his"
- + " joining in the society of the neighbourhood nor to his leaving the parish"
- + " occasionally for a week or two, to visit his relations. She had even"
- + " condescended to advise him to marry as soon as he could, provided he chose"
- + " with discretion; and had once paid him a visit in his humble parsonage,"
- + " where she had perfectly approved all the alterations he had been making,"
- + " and had even vouchsafed to suggest some herself--some shelves in the closet"
- + " up stairs.\""),
+ + " withdrawn, he thought it time to have some conversation with his guest,"
+ + " and therefore started a subject in which he expected him to shine, by"
+ + " observing that he seemed very fortunate in his patroness. Lady Catherine"
+ + " de Bourgh's attention to his wishes, and consideration for his comfort,"
+ + " appeared very remarkable. Mr. Bennet could not have chosen better. Mr."
+ + " Collins was eloquent in her praise. The subject elevated him to more than"
+ + " usual solemnity of manner, and with a most important aspect he protested"
+ + " that \"he had never in his life witnessed such behaviour in a person of"
+ + " rank--such affability and condescension, as he had himself experienced"
+ + " from Lady Catherine. She had been graciously pleased to approve of both of"
+ + " the discourses which he had already had the honour of preaching before"
+ + " her. She had also asked him twice to dine at Rosings, and had sent for him"
+ + " only the Saturday before, to make up her pool of quadrille in the evening."
+ + " Lady Catherine was reckoned proud by many people he knew, but _he_ had"
+ + " never seen anything but affability in her. She had always spoken to him as"
+ + " she would to any other gentleman; she made not the smallest objection to"
+ + " his joining in the society of the neighbourhood nor to his leaving the"
+ + " parish occasionally for a week or two, to visit his relations. She had"
+ + " even condescended to advise him to marry as soon as he could, provided he"
+ + " chose with discretion; and had once paid him a visit in his humble"
+ + " parsonage, where she had perfectly approved all the alterations he had"
+ + " been making, and had even vouchsafed to suggest some herself--some shelves"
+ + " in the closet up stairs.\""),
GERMAN(
Locale.GERMANY,
"Aber dieser Freiheit setzte endlich der Winter ein Ziel. Draußen auf den Feldern"
@@ -119,15 +121,14 @@
+ " เดิมทีเป็นการผสมผสานกันระหว่างสำเนียงอยุธยาและชาวไทยเชื้อสายจีนรุ่นหลังที่"
+ "พูดไทยแทนกลุ่มภาษาจีน"
+ " ลักษณะเด่นคือมีการออกเสียงที่ชัดเจนและแข็งกระด้างซึ่งได้รับอิทธิพลจากภาษาแต"
- + "้จิ๋ว"
- + " การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน"
+ + "้จิ๋ว การออกเสียงพยัญชนะ สระ การผันวรรณยุกต์ที่ในภาษาไทยมาตรฐาน"
+ " มาจากสำเนียงถิ่นนี้ในขณะที่ภาษาไทยสำเนียงอื่นล้วนเหน่อทั้งสิ้น"
+ " คำศัพท์ที่ใช้ในสำเนียงกรุงเทพจำนวนมากได้รับมาจากกลุ่มภาษาจีนเช่นคำว่า โป๊,"
+ " เฮ็ง, อาหมวย, อาซิ่ม ซึ่งมาจากภาษาแต้จิ๋ว และจากภาษาจีนเช่น ถู(涂), ชิ่ว(去"
+ " อ่านว่า\"ชู่\") และคำว่า ทาย(猜 อ่านว่า \"ชาย\") เป็นต้น"
+ " เนื่องจากสำเนียงกรุงเทพได้รับอิทธิพลมาจากภาษาจีนดังนั้นตัวอักษร \"ร\""
- + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้ เป็น"
- + " ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ"
+ + " มักออกเสียงเหมารวมเป็น \"ล\" หรือคำควบกล่ำบางคำถูกละทิ้งไปด้วยเช่น รู้"
+ + " เป็น ลู้, เรื่อง เป็น เลื่อง หรือ ประเทศ เป็น ปะเทศ"
+ " เป็นต้นสร้างความลำบากให้แก่ต่างชาติที่ต้องการเรียนภาษาไทย"
+ " แต่อย่างไรก็ตามผู้ที่พูดสำเนียงถิ่นนี้ก็สามารถออกอักขระภาษาไทยตามมาตรฐานได"
+ "้อย่างถูกต้องเพียงแต่มักเผลอไม่ค่อยออกเสียง"),
@@ -151,8 +152,7 @@
}
}
- @Parameters(name = "mText={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{Text.ACCENT}, {Text.BIDI}, {Text.EMOJI}, {Text.EMPTY}, {Text.GERMAN},
@@ -161,15 +161,13 @@
});
}
- @Parameterized.Parameter(0)
- public Text mText;
-
@Test
- public void timeBreakIterator() {
+ @Parameters(method = "getData")
+ public void timeBreakIterator(Text text) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- BreakIterator it = BreakIterator.getLineInstance(mText.mLocale);
- it.setText(mText.mText);
+ BreakIterator it = BreakIterator.getLineInstance(text.mLocale);
+ it.setText(text.mText);
while (it.next() != BreakIterator.DONE) {
// Keep iterating
@@ -178,12 +176,13 @@
}
@Test
- public void timeIcuBreakIterator() {
+ @Parameters(method = "getData")
+ public void timeIcuBreakIterator(Text text) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
android.icu.text.BreakIterator it =
- android.icu.text.BreakIterator.getLineInstance(mText.mLocale);
- it.setText(mText.mText);
+ android.icu.text.BreakIterator.getLineInstance(text.mLocale);
+ it.setText(text.mText);
while (it.next() != android.icu.text.BreakIterator.DONE) {
// Keep iterating
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java
index 855bb9a..b7b7e83 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/BulkPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
@@ -34,13 +35,12 @@
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class BulkPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mAlign({0}), mSBuf({1}), mDBuf({2}), mSize({3})")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{true, MyBufferType.DIRECT, MyBufferType.DIRECT, 4096},
@@ -82,24 +82,12 @@
});
}
- @Parameterized.Parameter(0)
- public boolean mAlign;
-
enum MyBufferType {
DIRECT,
HEAP,
MAPPED
}
- @Parameterized.Parameter(1)
- public MyBufferType mSBuf;
-
- @Parameterized.Parameter(2)
- public MyBufferType mDBuf;
-
- @Parameterized.Parameter(3)
- public int mSize;
-
public static ByteBuffer newBuffer(boolean aligned, MyBufferType bufferType, int bsize)
throws IOException {
int size = aligned ? bsize : bsize + 8 + 1;
@@ -126,13 +114,15 @@
}
@Test
- public void timePut() throws Exception {
- ByteBuffer src = BulkPerfTest.newBuffer(mAlign, mSBuf, mSize);
- ByteBuffer data = BulkPerfTest.newBuffer(mAlign, mDBuf, mSize);
+ @Parameters(method = "getData")
+ public void timePut(boolean align, MyBufferType sBuf, MyBufferType dBuf, int size)
+ throws Exception {
+ ByteBuffer src = BulkPerfTest.newBuffer(align, sBuf, size);
+ ByteBuffer data = BulkPerfTest.newBuffer(align, dBuf, size);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAlign ? 0 : 1);
- data.position(mAlign ? 0 : 1);
+ src.position(align ? 0 : 1);
+ data.position(align ? 0 : 1);
src.put(data);
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java
index 4bd7c4e..9ac36d0 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
@@ -41,7 +42,7 @@
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class ByteBufferPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -49,15 +50,14 @@
public enum MyByteOrder {
BIG(ByteOrder.BIG_ENDIAN),
LITTLE(ByteOrder.LITTLE_ENDIAN);
- final ByteOrder mByteOrder;
+ final ByteOrder byteOrder;
- MyByteOrder(ByteOrder mByteOrder) {
- this.mByteOrder = mByteOrder;
+ MyByteOrder(ByteOrder byteOrder) {
+ this.byteOrder = byteOrder;
}
}
- @Parameters(name = "mByteOrder={0}, mAligned={1}, mBufferType={2}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{MyByteOrder.BIG, true, MyBufferType.DIRECT},
@@ -75,21 +75,12 @@
});
}
- @Parameterized.Parameter(0)
- public MyByteOrder mByteOrder;
-
- @Parameterized.Parameter(1)
- public boolean mAligned;
-
enum MyBufferType {
DIRECT,
HEAP,
MAPPED;
}
- @Parameterized.Parameter(2)
- public MyBufferType mBufferType;
-
public static ByteBuffer newBuffer(
MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws IOException {
int size = aligned ? 8192 : 8192 + 8 + 1;
@@ -115,7 +106,7 @@
result = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
break;
}
- result.order(byteOrder.mByteOrder);
+ result.order(byteOrder.byteOrder);
result.position(aligned ? 0 : 1);
return result;
}
@@ -125,11 +116,13 @@
//
@Test
- public void timeByteBuffer_getByte() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getByte(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.get();
}
@@ -137,24 +130,28 @@
}
@Test
- public void timeByteBuffer_getByteArray() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getByteArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
byte[] dst = new byte[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
for (int i = 0; i < 1024; ++i) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
src.get(dst);
}
}
}
@Test
- public void timeByteBuffer_getByte_indexed() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getByte_indexed(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.get(i);
}
@@ -162,11 +159,13 @@
}
@Test
- public void timeByteBuffer_getChar() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getChar(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getChar();
}
@@ -174,9 +173,11 @@
}
@Test
- public void timeCharBuffer_getCharArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeCharBuffer_getCharArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
CharBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asCharBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asCharBuffer();
char[] dst = new char[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -188,11 +189,13 @@
}
@Test
- public void timeByteBuffer_getChar_indexed() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getChar_indexed(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getChar(i * 2);
}
@@ -200,11 +203,13 @@
}
@Test
- public void timeByteBuffer_getDouble() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getDouble(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getDouble();
}
@@ -212,9 +217,11 @@
}
@Test
- public void timeDoubleBuffer_getDoubleArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeDoubleBuffer_getDoubleArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
DoubleBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asDoubleBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asDoubleBuffer();
double[] dst = new double[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -226,11 +233,13 @@
}
@Test
- public void timeByteBuffer_getFloat() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getFloat(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getFloat();
}
@@ -238,9 +247,11 @@
}
@Test
- public void timeFloatBuffer_getFloatArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeFloatBuffer_getFloatArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
FloatBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asFloatBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asFloatBuffer();
float[] dst = new float[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -252,11 +263,13 @@
}
@Test
- public void timeByteBuffer_getInt() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getInt(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getInt();
}
@@ -264,9 +277,10 @@
}
@Test
- public void timeIntBuffer_getIntArray() throws Exception {
- IntBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asIntBuffer();
+ @Parameters(method = "getData")
+ public void timeIntBuffer_getIntArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ IntBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asIntBuffer();
int[] dst = new int[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -278,11 +292,13 @@
}
@Test
- public void timeByteBuffer_getLong() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getLong(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getLong();
}
@@ -290,9 +306,11 @@
}
@Test
- public void timeLongBuffer_getLongArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeLongBuffer_getLongArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
LongBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asLongBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asLongBuffer();
long[] dst = new long[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -304,11 +322,13 @@
}
@Test
- public void timeByteBuffer_getShort() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_getShort(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.getShort();
}
@@ -316,9 +336,11 @@
}
@Test
- public void timeShortBuffer_getShortArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeShortBuffer_getShortArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
ShortBuffer src =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asShortBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asShortBuffer();
short[] dst = new short[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -334,8 +356,10 @@
//
@Test
- public void timeByteBuffer_putByte() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putByte(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
src.position(0);
@@ -346,24 +370,28 @@
}
@Test
- public void timeByteBuffer_putByteArray() throws Exception {
- ByteBuffer dst = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putByteArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
byte[] src = new byte[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
for (int i = 0; i < 1024; ++i) {
- dst.position(mAligned ? 0 : 1);
+ dst.position(aligned ? 0 : 1);
dst.put(src);
}
}
}
@Test
- public void timeByteBuffer_putChar() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putChar(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putChar(' ');
}
@@ -371,9 +399,11 @@
}
@Test
- public void timeCharBuffer_putCharArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeCharBuffer_putCharArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
CharBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asCharBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asCharBuffer();
char[] src = new char[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -385,11 +415,13 @@
}
@Test
- public void timeByteBuffer_putDouble() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putDouble(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putDouble(0.0);
}
@@ -397,9 +429,11 @@
}
@Test
- public void timeDoubleBuffer_putDoubleArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeDoubleBuffer_putDoubleArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
DoubleBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asDoubleBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asDoubleBuffer();
double[] src = new double[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -411,11 +445,13 @@
}
@Test
- public void timeByteBuffer_putFloat() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putFloat(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putFloat(0.0f);
}
@@ -423,9 +459,11 @@
}
@Test
- public void timeFloatBuffer_putFloatArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeFloatBuffer_putFloatArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
FloatBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asFloatBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asFloatBuffer();
float[] src = new float[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -437,11 +475,13 @@
}
@Test
- public void timeByteBuffer_putInt() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putInt(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putInt(0);
}
@@ -449,9 +489,10 @@
}
@Test
- public void timeIntBuffer_putIntArray() throws Exception {
- IntBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asIntBuffer();
+ @Parameters(method = "getData")
+ public void timeIntBuffer_putIntArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ IntBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asIntBuffer();
int[] src = new int[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -463,11 +504,13 @@
}
@Test
- public void timeByteBuffer_putLong() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putLong(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putLong(0L);
}
@@ -475,9 +518,11 @@
}
@Test
- public void timeLongBuffer_putLongArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeLongBuffer_putLongArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
LongBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asLongBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asLongBuffer();
long[] src = new long[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -489,11 +534,13 @@
}
@Test
- public void timeByteBuffer_putShort() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeByteBuffer_putShort(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
for (int i = 0; i < 1024; ++i) {
src.putShort((short) 0);
}
@@ -501,9 +548,11 @@
}
@Test
- public void timeShortBuffer_putShortArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeShortBuffer_putShortArray(
+ MyByteOrder byteOrder, boolean aligned, MyBufferType bufferType) throws Exception {
ShortBuffer dst =
- ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType).asShortBuffer();
+ ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType).asShortBuffer();
short[] src = new short[1024];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -515,6 +564,7 @@
}
@Test
+ @Parameters(method = "getData")
public void time_new_byteArray() throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -523,6 +573,7 @@
}
@Test
+ @Parameters(method = "getData")
public void time_ByteBuffer_allocate() throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java
index 81f9e59..5dd9d6e 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/ByteBufferScalarVersusVectorPerfTest.java
@@ -20,23 +20,23 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class ByteBufferScalarVersusVectorPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mByteOrder={0}, mAligned={1}, mBufferType={2}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{
@@ -102,19 +102,15 @@
});
}
- @Parameterized.Parameter(0)
- public ByteBufferPerfTest.MyByteOrder mByteOrder;
-
- @Parameterized.Parameter(1)
- public boolean mAligned;
-
- @Parameterized.Parameter(2)
- public ByteBufferPerfTest.MyBufferType mBufferType;
-
@Test
- public void timeManualByteBufferCopy() throws Exception {
- ByteBuffer src = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
- ByteBuffer dst = ByteBufferPerfTest.newBuffer(mByteOrder, mAligned, mBufferType);
+ @Parameters(method = "getData")
+ public void timeManualByteBufferCopy(
+ ByteBufferPerfTest.MyByteOrder byteOrder,
+ boolean aligned,
+ ByteBufferPerfTest.MyBufferType bufferType)
+ throws Exception {
+ ByteBuffer src = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
+ ByteBuffer dst = ByteBufferPerfTest.newBuffer(byteOrder, aligned, bufferType);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
src.position(0);
@@ -126,23 +122,25 @@
}
@Test
- public void timeByteBufferBulkGet() throws Exception {
- ByteBuffer src = ByteBuffer.allocate(mAligned ? 8192 : 8192 + 1);
+ @Parameters({"true", "false"})
+ public void timeByteBufferBulkGet(boolean aligned) throws Exception {
+ ByteBuffer src = ByteBuffer.allocate(aligned ? 8192 : 8192 + 1);
byte[] dst = new byte[8192];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
src.get(dst, 0, dst.length);
}
}
@Test
- public void timeDirectByteBufferBulkGet() throws Exception {
- ByteBuffer src = ByteBuffer.allocateDirect(mAligned ? 8192 : 8192 + 1);
+ @Parameters({"true", "false"})
+ public void timeDirectByteBufferBulkGet(boolean aligned) throws Exception {
+ ByteBuffer src = ByteBuffer.allocateDirect(aligned ? 8192 : 8192 + 1);
byte[] dst = new byte[8192];
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- src.position(mAligned ? 0 : 1);
+ src.position(aligned ? 0 : 1);
src.get(dst, 0, dst.length);
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java
index 28ec6de..0a59899 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/CharacterPerfTest.java
@@ -20,12 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@@ -34,13 +34,12 @@
* Tests various Character methods, intended for testing multiple implementations against each
* other.
*/
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class CharacterPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mCharacterSet({0}), mOverload({1})")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{CharacterSet.ASCII, Overload.CHAR},
@@ -50,17 +49,10 @@
});
}
- @Parameterized.Parameter(0)
- public CharacterSet mCharacterSet;
-
- @Parameterized.Parameter(1)
- public Overload mOverload;
-
private char[] mChars;
- @Before
- public void setUp() throws Exception {
- this.mChars = mCharacterSet.mChars;
+ public void setUp(CharacterSet characterSet) {
+ this.mChars = characterSet.mChars;
}
public enum Overload {
@@ -87,10 +79,12 @@
// A fake benchmark to give us a baseline.
@Test
- public void timeIsSpace() {
+ @Parameters(method = "getData")
+ public void timeIsSpace(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
boolean fake = false;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
fake ^= ((char) ch == ' ');
@@ -106,9 +100,11 @@
}
@Test
- public void timeDigit() {
+ @Parameters(method = "getData")
+ public void timeDigit(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.digit(mChars[ch], 10);
@@ -124,9 +120,11 @@
}
@Test
- public void timeGetNumericValue() {
+ @Parameters(method = "getData")
+ public void timeGetNumericValue(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.getNumericValue(mChars[ch]);
@@ -142,9 +140,11 @@
}
@Test
- public void timeIsDigit() {
+ @Parameters(method = "getData")
+ public void timeIsDigit(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isDigit(mChars[ch]);
@@ -160,9 +160,11 @@
}
@Test
- public void timeIsIdentifierIgnorable() {
+ @Parameters(method = "getData")
+ public void timeIsIdentifierIgnorable(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isIdentifierIgnorable(mChars[ch]);
@@ -178,9 +180,11 @@
}
@Test
- public void timeIsJavaIdentifierPart() {
+ @Parameters(method = "getData")
+ public void timeIsJavaIdentifierPart(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isJavaIdentifierPart(mChars[ch]);
@@ -196,9 +200,11 @@
}
@Test
- public void timeIsJavaIdentifierStart() {
+ @Parameters(method = "getData")
+ public void timeIsJavaIdentifierStart(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isJavaIdentifierStart(mChars[ch]);
@@ -214,9 +220,11 @@
}
@Test
- public void timeIsLetter() {
+ @Parameters(method = "getData")
+ public void timeIsLetter(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isLetter(mChars[ch]);
@@ -232,9 +240,11 @@
}
@Test
- public void timeIsLetterOrDigit() {
+ @Parameters(method = "getData")
+ public void timeIsLetterOrDigit(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isLetterOrDigit(mChars[ch]);
@@ -250,9 +260,11 @@
}
@Test
- public void timeIsLowerCase() {
+ @Parameters(method = "getData")
+ public void timeIsLowerCase(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isLowerCase(mChars[ch]);
@@ -268,9 +280,11 @@
}
@Test
- public void timeIsSpaceChar() {
+ @Parameters(method = "getData")
+ public void timeIsSpaceChar(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isSpaceChar(mChars[ch]);
@@ -286,9 +300,11 @@
}
@Test
- public void timeIsUpperCase() {
+ @Parameters(method = "getData")
+ public void timeIsUpperCase(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isUpperCase(mChars[ch]);
@@ -304,9 +320,11 @@
}
@Test
- public void timeIsWhitespace() {
+ @Parameters(method = "getData")
+ public void timeIsWhitespace(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.isWhitespace(mChars[ch]);
@@ -322,9 +340,11 @@
}
@Test
- public void timeToLowerCase() {
+ @Parameters(method = "getData")
+ public void timeToLowerCase(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.toLowerCase(mChars[ch]);
@@ -340,9 +360,11 @@
}
@Test
- public void timeToUpperCase() {
+ @Parameters(method = "getData")
+ public void timeToUpperCase(CharacterSet characterSet, Overload overload) {
+ setUp(characterSet);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- if (mOverload == Overload.CHAR) {
+ if (overload == Overload.CHAR) {
while (state.keepRunning()) {
for (int ch = 0; ch < 65536; ++ch) {
Character.toUpperCase(mChars[ch]);
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java
index 603b182..8da13a9 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/CharsetForNamePerfTest.java
@@ -20,44 +20,40 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class CharsetForNamePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameterized.Parameters(name = "mCharsetName({0})")
- public static Collection<Object[]> data() {
- return Arrays.asList(
- new Object[][] {
- {"UTF-16"},
- {"UTF-8"},
- {"UTF8"},
- {"ISO-8859-1"},
- {"8859_1"},
- {"ISO-8859-2"},
- {"8859_2"},
- {"US-ASCII"},
- {"ASCII"},
- });
+ public static String[] charsetNames() {
+ return new String[] {
+ "UTF-16",
+ "UTF-8",
+ "UTF8",
+ "ISO-8859-1",
+ "8859_1",
+ "ISO-8859-2",
+ "8859_2",
+ "US-ASCII",
+ "ASCII",
+ };
}
- @Parameterized.Parameter(0)
- public String mCharsetName;
-
@Test
- public void timeCharsetForName() throws Exception {
+ @Parameters(method = "charsetNames")
+ public void timeCharsetForName(String charsetName) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- Charset.forName(mCharsetName);
+ Charset.forName(charsetName);
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java
index 437d186..048c50f 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/CharsetPerfTest.java
@@ -20,22 +20,22 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class CharsetPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mLength({0}), mName({1})")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{1, "UTF-16"},
@@ -86,24 +86,20 @@
});
}
- @Parameterized.Parameter(0)
- public int mLength;
-
- @Parameterized.Parameter(1)
- public String mName;
-
@Test
- public void time_new_String_BString() throws Exception {
- byte[] bytes = makeBytes(makeString(mLength));
+ @Parameters(method = "getData")
+ public void time_new_String_BString(int length, String name) throws Exception {
+ byte[] bytes = makeBytes(makeString(length));
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- new String(bytes, mName);
+ new String(bytes, name);
}
}
@Test
- public void time_new_String_BII() throws Exception {
- byte[] bytes = makeBytes(makeString(mLength));
+ @Parameters(method = "getData")
+ public void time_new_String_BII(int length, String name) throws Exception {
+ byte[] bytes = makeBytes(makeString(length));
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
new String(bytes, 0, bytes.length);
@@ -111,20 +107,22 @@
}
@Test
- public void time_new_String_BIIString() throws Exception {
- byte[] bytes = makeBytes(makeString(mLength));
+ @Parameters(method = "getData")
+ public void time_new_String_BIIString(int length, String name) throws Exception {
+ byte[] bytes = makeBytes(makeString(length));
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- new String(bytes, 0, bytes.length, mName);
+ new String(bytes, 0, bytes.length, name);
}
}
@Test
- public void time_String_getBytes() throws Exception {
- String string = makeString(mLength);
+ @Parameters(method = "getData")
+ public void time_String_getBytes(int length, String name) throws Exception {
+ String string = makeString(length);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- string.getBytes(mName);
+ string.getBytes(name);
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java
index 15c27f2..42b0588 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/CipherPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
@@ -42,17 +43,13 @@
* Cipher benchmarks. Only runs on AES currently because of the combinatorial explosion of the test
* as it stands.
*/
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class CipherPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameterized.Parameters(
- name =
- "mMode({0}), mPadding({1}), mKeySize({2}), mInputSize({3}),"
- + " mImplementation({4})")
- public static Collection cases() {
- int[] mKeySizes = new int[] {128, 192, 256};
+ public static Collection getCases() {
+ int[] keySizes = new int[] {128, 192, 256};
int[] inputSizes = new int[] {16, 32, 64, 128, 1024, 8192};
final List<Object[]> params = new ArrayList<>();
for (Mode mode : Mode.values()) {
@@ -71,11 +68,11 @@
&& implementation == Implementation.OpenSSL) {
continue;
}
- for (int mKeySize : mKeySizes) {
+ for (int keySize : keySizes) {
for (int inputSize : inputSizes) {
params.add(
new Object[] {
- mode, padding, mKeySize, inputSize, implementation
+ mode, padding, keySize, inputSize, implementation
});
}
}
@@ -107,9 +104,6 @@
AES,
};
- @Parameterized.Parameter(0)
- public Mode mMode;
-
public enum Mode {
CBC,
CFB,
@@ -118,23 +112,11 @@
OFB,
};
- @Parameterized.Parameter(1)
- public Padding mPadding;
-
public enum Padding {
NOPADDING,
PKCS1PADDING,
};
- @Parameterized.Parameter(2)
- public int mKeySize;
-
- @Parameterized.Parameter(3)
- public int mInputSize;
-
- @Parameterized.Parameter(4)
- public Implementation mImplementation;
-
public enum Implementation {
OpenSSL,
BouncyCastle
@@ -156,21 +138,20 @@
private AlgorithmParameterSpec mSpec;
- @Before
- public void setUp() throws Exception {
- mCipherAlgorithm =
- mAlgorithm.toString() + "/" + mMode.toString() + "/" + mPadding.toString();
+ public void setUp(Mode mode, Padding padding, int keySize, Implementation implementation)
+ throws Exception {
+ mCipherAlgorithm = mAlgorithm.toString() + "/" + mode.toString() + "/" + padding.toString();
String mKeyAlgorithm = mAlgorithm.toString();
- mKey = sKeySizes.get(mKeySize);
+ mKey = sKeySizes.get(keySize);
if (mKey == null) {
KeyGenerator generator = KeyGenerator.getInstance(mKeyAlgorithm);
- generator.init(mKeySize);
+ generator.init(keySize);
mKey = generator.generateKey();
- sKeySizes.put(mKeySize, mKey);
+ sKeySizes.put(keySize, mKey);
}
- switch (mImplementation) {
+ switch (implementation) {
case OpenSSL:
mProviderName = "AndroidOpenSSL";
break;
@@ -178,10 +159,10 @@
mProviderName = "BC";
break;
default:
- throw new RuntimeException(mImplementation.toString());
+ throw new RuntimeException(implementation.toString());
}
- if (mMode != Mode.ECB) {
+ if (mode != Mode.ECB) {
mSpec = new IvParameterSpec(IV);
}
@@ -193,18 +174,26 @@
}
@Test
- public void timeEncrypt() throws Exception {
+ @Parameters(method = "getCases")
+ public void timeEncrypt(
+ Mode mode, Padding padding, int keySize, int inputSize, Implementation implementation)
+ throws Exception {
+ setUp(mode, padding, keySize, implementation);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mCipherEncrypt.doFinal(DATA, 0, mInputSize, mOutput);
+ mCipherEncrypt.doFinal(DATA, 0, inputSize, mOutput);
}
}
@Test
- public void timeDecrypt() throws Exception {
+ @Parameters(method = "getCases")
+ public void timeDecrypt(
+ Mode mode, Padding padding, int keySize, int inputSize, Implementation implementation)
+ throws Exception {
+ setUp(mode, padding, keySize, implementation);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mCipherDecrypt.doFinal(DATA, 0, mInputSize, mOutput);
+ mCipherDecrypt.doFinal(DATA, 0, inputSize, mOutput);
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java
index a89efff..69197c3 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/CollectionsPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.Arrays;
@@ -35,19 +36,15 @@
import java.util.Random;
import java.util.Vector;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class CollectionsPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mArrayListLength({0})")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{4}, {16}, {64}, {256}, {1024}});
}
- @Parameterized.Parameter(0)
- public int arrayListLength;
-
public static Comparator<Integer> REVERSE =
new Comparator<Integer>() {
@Override
@@ -59,7 +56,8 @@
};
@Test
- public void timeSort_arrayList() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSort_arrayList(int arrayListLength) throws Exception {
List<Integer> input = buildList(arrayListLength, ArrayList.class);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -68,7 +66,8 @@
}
@Test
- public void timeSortWithComparator_arrayList() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSortWithComparator_arrayList(int arrayListLength) throws Exception {
List<Integer> input = buildList(arrayListLength, ArrayList.class);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -77,7 +76,8 @@
}
@Test
- public void timeSort_vector() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSort_vector(int arrayListLength) throws Exception {
List<Integer> input = buildList(arrayListLength, Vector.class);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
@@ -86,7 +86,8 @@
}
@Test
- public void timeSortWithComparator_vector() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSortWithComparator_vector(int arrayListLength) throws Exception {
List<Integer> input = buildList(arrayListLength, Vector.class);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java
index 4ff3ba5..8391203 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/EqualsHashCodePerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
import java.net.URI;
import java.net.URL;
@@ -32,39 +33,39 @@
import java.util.Collection;
import java.util.List;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public final class EqualsHashCodePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
private enum Type {
URI() {
- @Override Object newInstance(String text) throws Exception {
+ @Override
+ Object newInstance(String text) throws Exception {
return new URI(text);
}
},
URL() {
- @Override Object newInstance(String text) throws Exception {
+ @Override
+ Object newInstance(String text) throws Exception {
return new URL(text);
}
};
+
abstract Object newInstance(String text) throws Exception;
}
- private static final String QUERY = "%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9%2C+%E0%AE%9A%E0%AF%81%E0%AE%B5%E0%AE%BE%E0%AE%B0%E0%AE%B8%E0%AF%8D%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D%2C+%E0%AE%86%E0%AE%A9%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AF%87%E0%AE%B0%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%82%E0%AE%B4%E0%AF%8D%E0%AE%A8%E0%AE%BF%E0%AE%B2%E0%AF%88+%E0%AE%8F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%8E%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%A4%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%AA%E0%AE%A3%E0%AE%BF%E0%AE%AF%E0%AF%88%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%B5%E0%AE%B2%E0%AE%BF+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%88+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%AA%E0%AF%86%E0%AE%B0%E0%AE%BF%E0%AE%AF+%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%AE%E0%AF%81%E0%AE%A4%E0%AE%B2%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%9F%E0%AE%BF%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D.+%E0%AE%85%E0%AE%A4%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%95%E0%AE%B3%E0%AF%88+%E0%AE%AA%E0%AF%86%E0%AE%B1+%E0%AE%A4%E0%AE%B5%E0%AE%BF%E0%AE%B0%2C+%E0%AE%8E%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%89%E0%AE%B4%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%89%E0%AE%9F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%AF%E0%AE%BF%E0%AE%B1%E0%AF%8D%E0%AE%9A%E0%AE%BF+%E0%AE%AE%E0%AF%87%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AE%A4%E0%AF%81+%E0%AE%8E%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81+%E0%AE%87%E0%AE%A4%E0%AF%81+%E0%AE%92%E0%AE%B0%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B1%E0%AE%BF%E0%AE%AF+%E0%AE%89%E0%AE%A4%E0%AE%BE%E0%AE%B0%E0%AE%A3%E0%AE%AE%E0%AF%8D%2C+%E0%AE%8E%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95.+%E0%AE%B0%E0%AE%AF%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%8E%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%B5%E0%AE%BF%E0%AE%B3%E0%AF%88%E0%AE%B5%E0%AE%BE%E0%AE%95+%E0%AE%87%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%AE%E0%AF%8D+%E0%AE%86%E0%AE%A9%E0%AF%8D%E0%AE%B2%E0%AF%88%E0%AE%A9%E0%AF%8D+%E0%AE%AA%E0%AE%AF%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%BE%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AF%87%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%AF%E0%AE%BE%E0%AE%B0%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%95%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AA%E0%AE%BF%E0%AE%9F%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AE%B0%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D.+%E0%AE%87%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%A8%E0%AE%BF%E0%AE%95%E0%AE%B4%E0%AF%8D%E0%AE%B5%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%86%E0%AE%AF%E0%AF%8D%E0%AE%A4%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%85%E0%AE%AE%E0%AF%88%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%95%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%2C+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%B5%E0%AE%BF%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AF%81+quae+%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%B1%E0%AF%88+%E0%AE%A8%E0%AF%80%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%AA%E0%AE%B0%E0%AE%BF%E0%AE%A8%E0%AF%8D%E0%AE%A4%E0%AF%81%E0%AE%B0%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%86%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95+%E0%AE%AE%E0%AE%BE%E0%AE%B1%E0%AF%81%E0%AE%AE%E0%AF%8D";
+ private static final String QUERY =
+ "%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9%2C+%E0%AE%9A%E0%AF%81%E0%AE%B5%E0%AE%BE%E0%AE%B0%E0%AE%B8%E0%AF%8D%E0%AE%AF%E0%AE%AE%E0%AE%BE%E0%AE%A9+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D%2C+%E0%AE%86%E0%AE%A9%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AF%87%E0%AE%B0%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%82%E0%AE%B4%E0%AF%8D%E0%AE%A8%E0%AE%BF%E0%AE%B2%E0%AF%88+%E0%AE%8F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%8E%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%A4%E0%AE%BE%E0%AE%B2%E0%AF%8D+%E0%AE%AA%E0%AE%A3%E0%AE%BF%E0%AE%AF%E0%AF%88%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%B5%E0%AE%B2%E0%AE%BF+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%88+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%AA%E0%AF%86%E0%AE%B0%E0%AE%BF%E0%AE%AF+%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%AE%E0%AF%81%E0%AE%A4%E0%AE%B2%E0%AF%8D+%E0%AE%AE%E0%AF%81%E0%AE%9F%E0%AE%BF%E0%AE%AF%E0%AF%81%E0%AE%AE%E0%AF%8D.+%E0%AE%85%E0%AE%A4%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B2+%E0%AE%A8%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%95%E0%AE%B3%E0%AF%88+%E0%AE%AA%E0%AF%86%E0%AE%B1+%E0%AE%A4%E0%AE%B5%E0%AE%BF%E0%AE%B0%2C+%E0%AE%8E%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%89%E0%AE%B4%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%89%E0%AE%9F%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AE%AF%E0%AE%BF%E0%AE%B1%E0%AF%8D%E0%AE%9A%E0%AE%BF+%E0%AE%AE%E0%AF%87%E0%AE%B1%E0%AF%8D%E0%AE%95%E0%AF%86%E0%AE%BE%E0%AE%B3%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AE%A4%E0%AF%81+%E0%AE%8E%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81+%E0%AE%87%E0%AE%A4%E0%AF%81+%E0%AE%92%E0%AE%B0%E0%AF%81+%E0%AE%9A%E0%AE%BF%E0%AE%B1%E0%AE%BF%E0%AE%AF+%E0%AE%89%E0%AE%A4%E0%AE%BE%E0%AE%B0%E0%AE%A3%E0%AE%AE%E0%AF%8D%2C+%E0%AE%8E%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95.+%E0%AE%B0%E0%AE%AF%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%8E%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%B5%E0%AE%BF%E0%AE%B3%E0%AF%88%E0%AE%B5%E0%AE%BE%E0%AE%95+%E0%AE%87%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%AE%E0%AF%8D+%E0%AE%86%E0%AE%A9%E0%AF%8D%E0%AE%B2%E0%AF%88%E0%AE%A9%E0%AF%8D+%E0%AE%AA%E0%AE%AF%E0%AE%A9%E0%AF%8D%E0%AE%AA%E0%AE%BE%E0%AE%9F%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AF%87%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%AF%E0%AE%BE%E0%AE%B0%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%95%E0%AE%A3%E0%AF%8D%E0%AE%9F%E0%AF%81%E0%AE%AA%E0%AE%BF%E0%AE%9F%E0%AE%BF%E0%AE%95%E0%AF%8D%E0%AE%95+%E0%AE%B5%E0%AE%B0%E0%AF%81%E0%AE%AE%E0%AF%8D+%E0%AE%A8%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%A4%E0%AE%B1%E0%AF%8D%E0%AE%AA%E0%AF%87%E0%AE%BE%E0%AE%A4%E0%AF%81+%E0%AE%87%E0%AE%B0%E0%AF%81%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D.+%E0%AE%87%E0%AE%A8%E0%AF%8D%E0%AE%A4+%E0%AE%A8%E0%AE%BF%E0%AE%95%E0%AE%B4%E0%AF%8D%E0%AE%B5%E0%AF%81%E0%AE%95%E0%AE%B3%E0%AE%BF%E0%AE%B2%E0%AF%8D+%E0%AE%9A%E0%AF%86%E0%AE%AF%E0%AF%8D%E0%AE%A4%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%85%E0%AE%AE%E0%AF%88%E0%AE%AA%E0%AF%8D%E0%AE%AA%E0%AE%BF%E0%AE%A9%E0%AF%8D+%E0%AE%95%E0%AE%A3%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AF%81%2C+%E0%AE%85%E0%AE%B5%E0%AE%B0%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%A4%E0%AE%B5%E0%AE%B1%E0%AF%81+%E0%AE%B5%E0%AE%BF%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AF%81+quae+%E0%AE%AA%E0%AE%9F%E0%AF%8D%E0%AE%9F%E0%AE%B1%E0%AF%88+%E0%AE%A8%E0%AF%80%E0%AE%99%E0%AF%8D%E0%AE%95%E0%AE%B3%E0%AF%8D+%E0%AE%AA%E0%AE%B0%E0%AE%BF%E0%AE%A8%E0%AF%8D%E0%AE%A4%E0%AF%81%E0%AE%B0%E0%AF%88%E0%AE%95%E0%AF%8D%E0%AE%95%E0%AE%BF%E0%AE%B1%E0%AF%87%E0%AE%BE%E0%AE%AE%E0%AF%8D+%E0%AE%AE%E0%AF%86%E0%AE%A9%E0%AF%8D%E0%AE%AE%E0%AF%88%E0%AE%AF%E0%AE%BE%E0%AE%95+%E0%AE%AE%E0%AE%BE%E0%AE%B1%E0%AF%81%E0%AE%AE%E0%AF%8D";
- @Parameterized.Parameters(name = "mType({0})")
- public static Collection cases() {
+ public static Collection getCases() {
final List<Object[]> params = new ArrayList<>();
for (Type type : Type.values()) {
- params.add(new Object[]{type});
+ params.add(new Object[] {type});
}
return params;
}
- @Parameterized.Parameter(0)
- public Type mType;
-
Object mA1;
Object mA2;
Object mB1;
@@ -73,20 +74,13 @@
Object mC1;
Object mC2;
- @Before
- public void setUp() throws Exception {
- mA1 = mType.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox");
- mA2 = mType.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox");
- mB1 = mType.newInstance("http://developer.android.com/reference/java/net/URI.html");
- mB2 = mType.newInstance("http://developer.android.com/reference/java/net/URI.html");
-
- mC1 = mType.newInstance("http://developer.android.com/query?q=" + QUERY);
- // Replace the very last char.
- mC2 = mType.newInstance("http://developer.android.com/query?q=" + QUERY.substring(0, QUERY.length() - 3) + "%AF");
- }
-
@Test
- public void timeEquals() {
+ @Parameters(method = "getCases")
+ public void timeEquals(Type type) throws Exception {
+ mA1 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox");
+ mA2 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox");
+ mB1 = type.newInstance("http://developer.android.com/reference/java/net/URI.html");
+ mB2 = type.newInstance("http://developer.android.com/reference/java/net/URI.html");
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
mA1.equals(mB1);
@@ -96,7 +90,10 @@
}
@Test
- public void timeHashCode() {
+ @Parameters(method = "getCases")
+ public void timeHashCode(Type type) throws Exception {
+ mA1 = type.newInstance("https://mail.google.com/mail/u/0/?shva=1#inbox");
+ mB1 = type.newInstance("http://developer.android.com/reference/java/net/URI.html");
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
mA1.hashCode();
@@ -105,7 +102,15 @@
}
@Test
- public void timeEqualsWithHeavilyEscapedComponent() {
+ @Parameters(method = "getCases")
+ public void timeEqualsWithHeavilyEscapedComponent(Type type) throws Exception {
+ mC1 = type.newInstance("http://developer.android.com/query?q=" + QUERY);
+ // Replace the very last char.
+ mC2 =
+ type.newInstance(
+ "http://developer.android.com/query?q="
+ + QUERY.substring(0, QUERY.length() - 3)
+ + "%AF");
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
mC1.equals(mC2);
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java
index 6fe9059..80c4487 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/KeyPairGeneratorPerfTest.java
@@ -20,26 +20,24 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
-import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class KeyPairGeneratorPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mAlgorithm={0}, mImplementation={1}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{Algorithm.RSA, Implementation.BouncyCastle},
@@ -48,12 +46,6 @@
});
}
- @Parameterized.Parameter(0)
- public Algorithm mAlgorithm;
-
- @Parameterized.Parameter(1)
- public Implementation mImplementation;
-
public enum Algorithm {
RSA,
DSA,
@@ -66,26 +58,25 @@
private String mGeneratorAlgorithm;
private KeyPairGenerator mGenerator;
- private SecureRandom mRandom;
- @Before
- public void setUp() throws Exception {
- this.mGeneratorAlgorithm = mAlgorithm.toString();
+ public void setUp(Algorithm algorithm, Implementation implementation) throws Exception {
+ this.mGeneratorAlgorithm = algorithm.toString();
final String provider;
- if (mImplementation == Implementation.BouncyCastle) {
+ if (implementation == Implementation.BouncyCastle) {
provider = "BC";
} else {
provider = "AndroidOpenSSL";
}
this.mGenerator = KeyPairGenerator.getInstance(mGeneratorAlgorithm, provider);
- this.mRandom = SecureRandom.getInstance("SHA1PRNG");
this.mGenerator.initialize(1024);
}
@Test
- public void time() throws Exception {
+ @Parameters(method = "getData")
+ public void time(Algorithm algorithm, Implementation implementation) throws Exception {
+ setUp(algorithm, implementation);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
KeyPair keyPair = mGenerator.generateKeyPair();
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java
index 414764d..c9b0cbe 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/LoopingBackwardsPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@@ -34,36 +35,34 @@
*
* @author Kevin Bourrillion
*/
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class LoopingBackwardsPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mMax={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{2}, {20}, {2000}, {20000000}});
}
- @Parameterized.Parameter(0)
- public int mMax;
-
@Test
- public void timeForwards() {
+ @Parameters(method = "getData")
+ public void timeForwards(int max) {
int fake = 0;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- for (int j = 0; j < mMax; j++) {
+ for (int j = 0; j < max; j++) {
fake += j;
}
}
}
@Test
- public void timeBackwards() {
+ @Parameters(method = "getData")
+ public void timeBackwards(int max) {
int fake = 0;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- for (int j = mMax - 1; j >= 0; j--) {
+ for (int j = max - 1; j >= 0; j--) {
fake += j;
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java
index 279681b..2dc947a 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/MessageDigestPerfTest.java
@@ -20,24 +20,24 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class MessageDigestPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mAlgorithm={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{Algorithm.MD5},
@@ -48,9 +48,6 @@
});
}
- @Parameterized.Parameter(0)
- public Algorithm mAlgorithm;
-
public String mProvider = "AndroidOpenSSL";
private static final int DATA_SIZE = 8192;
@@ -97,44 +94,44 @@
};
@Test
- public void time() throws Exception {
+ @Parameters(method = "getData")
+ public void time(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
digest.update(DATA, 0, DATA_SIZE);
digest.digest();
}
}
@Test
- public void timeLargeArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeLargeArray(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
digest.update(LARGE_DATA, 0, LARGE_DATA_SIZE);
digest.digest();
}
}
@Test
- public void timeSmallChunkOfLargeArray() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSmallChunkOfLargeArray(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
digest.update(LARGE_DATA, LARGE_DATA_SIZE / 2, DATA_SIZE);
digest.digest();
}
}
@Test
- public void timeSmallByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSmallByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
SMALL_BUFFER.position(0);
SMALL_BUFFER.limit(SMALL_BUFFER.capacity());
digest.update(SMALL_BUFFER);
@@ -143,11 +140,11 @@
}
@Test
- public void timeSmallDirectByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSmallDirectByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
SMALL_DIRECT_BUFFER.position(0);
SMALL_DIRECT_BUFFER.limit(SMALL_DIRECT_BUFFER.capacity());
digest.update(SMALL_DIRECT_BUFFER);
@@ -156,11 +153,11 @@
}
@Test
- public void timeLargeByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeLargeByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
LARGE_BUFFER.position(0);
LARGE_BUFFER.limit(LARGE_BUFFER.capacity());
digest.update(LARGE_BUFFER);
@@ -169,11 +166,11 @@
}
@Test
- public void timeLargeDirectByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeLargeDirectByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
LARGE_DIRECT_BUFFER.position(0);
LARGE_DIRECT_BUFFER.limit(LARGE_DIRECT_BUFFER.capacity());
digest.update(LARGE_DIRECT_BUFFER);
@@ -182,11 +179,11 @@
}
@Test
- public void timeSmallChunkOfLargeByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSmallChunkOfLargeByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
LARGE_BUFFER.position(LARGE_BUFFER.capacity() / 2);
LARGE_BUFFER.limit(LARGE_BUFFER.position() + DATA_SIZE);
digest.update(LARGE_BUFFER);
@@ -195,11 +192,11 @@
}
@Test
- public void timeSmallChunkOfLargeDirectByteBuffer() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSmallChunkOfLargeDirectByteBuffer(Algorithm algorithm) throws Exception {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- MessageDigest digest =
- MessageDigest.getInstance(mAlgorithm.toString(), mProvider);
+ MessageDigest digest = MessageDigest.getInstance(algorithm.toString(), mProvider);
LARGE_DIRECT_BUFFER.position(LARGE_DIRECT_BUFFER.capacity() / 2);
LARGE_DIRECT_BUFFER.limit(LARGE_DIRECT_BUFFER.position() + DATA_SIZE);
digest.update(LARGE_DIRECT_BUFFER);
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java
index 37bd73c..d9d4bb5 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/MutableIntPerfTest.java
@@ -20,17 +20,18 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public final class MutableIntPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -96,29 +97,28 @@
abstract int timeGet(BenchmarkState state);
}
- @Parameters(name = "mKind={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{Kind.ARRAY}, {Kind.ATOMIC}});
}
- @Parameterized.Parameter(0)
- public Kind mKind;
-
@Test
- public void timeCreate() {
+ @Parameters(method = "getData")
+ public void timeCreate(Kind kind) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- mKind.timeCreate(state);
+ kind.timeCreate(state);
}
@Test
- public void timeIncrement() {
+ @Parameters(method = "getData")
+ public void timeIncrement(Kind kind) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- mKind.timeIncrement(state);
+ kind.timeIncrement(state);
}
@Test
- public void timeGet() {
+ @Parameters(method = "getData")
+ public void timeGet(Kind kind) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
- mKind.timeGet(state);
+ kind.timeGet(state);
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java
index 8801a56..48450b4 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/PriorityQueuePerfTest.java
@@ -20,12 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.ArrayList;
import java.util.Arrays;
@@ -35,13 +35,12 @@
import java.util.PriorityQueue;
import java.util.Random;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class PriorityQueuePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mQueueSize={0}, mHitRate={1}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{100, 0},
@@ -62,26 +61,19 @@
});
}
- @Parameterized.Parameter(0)
- public int mQueueSize;
-
- @Parameterized.Parameter(1)
- public int mHitRate;
-
private PriorityQueue<Integer> mPq;
private PriorityQueue<Integer> mUsepq;
private List<Integer> mSeekElements;
private Random mRandom = new Random(189279387L);
- @Before
- public void setUp() throws Exception {
+ public void setUp(int queueSize, int hitRate) throws Exception {
mPq = new PriorityQueue<Integer>();
mUsepq = new PriorityQueue<Integer>();
mSeekElements = new ArrayList<Integer>();
List<Integer> allElements = new ArrayList<Integer>();
- int numShared = (int) (mQueueSize * ((double) mHitRate / 100));
- // the total number of elements we require to engineer a hit rate of mHitRate%
- int totalElements = 2 * mQueueSize - numShared;
+ int numShared = (int) (queueSize * ((double) hitRate / 100));
+ // the total number of elements we require to engineer a hit rate of hitRate%
+ int totalElements = 2 * queueSize - numShared;
for (int i = 0; i < totalElements; i++) {
allElements.add(i);
}
@@ -93,11 +85,11 @@
mSeekElements.add(allElements.get(i));
}
// add priority queue only elements (these won't be touched)
- for (int i = numShared; i < mQueueSize; i++) {
+ for (int i = numShared; i < queueSize; i++) {
mPq.add(allElements.get(i));
}
// add non-priority queue elements (these will be misses)
- for (int i = mQueueSize; i < totalElements; i++) {
+ for (int i = queueSize; i < totalElements; i++) {
mSeekElements.add(allElements.get(i));
}
mUsepq = new PriorityQueue<Integer>(mPq);
@@ -107,16 +99,18 @@
}
@Test
- public void timeRemove() {
+ @Parameters(method = "getData")
+ public void timeRemove(int queueSize, int hitRate) throws Exception {
+ setUp(queueSize, hitRate);
boolean fake = false;
int elementsSize = mSeekElements.size();
// At most allow the queue to empty 10%.
- int resizingThreshold = mQueueSize / 10;
+ int resizingThreshold = queueSize / 10;
int i = 0;
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
// Reset queue every so often. This will be called more often for smaller
- // mQueueSizes, but since a copy is linear, it will also cost proportionally
+ // queueSizes, but since a copy is linear, it will also cost proportionally
// less, and hopefully it will approximately balance out.
if (++i % resizingThreshold == 0) {
mUsepq = new PriorityQueue<Integer>(mPq);
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java
index 42dc581..5ad62de 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/SchemePrefixPerfTest.java
@@ -20,11 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
@@ -32,7 +33,7 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public final class SchemePrefixPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -85,19 +86,16 @@
abstract String execute(String spec);
}
- @Parameters(name = "mStrategy={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(new Object[][] {{Strategy.REGEX}, {Strategy.JAVA}});
}
- @Parameterized.Parameter(0)
- public Strategy mStrategy;
-
@Test
- public void timeSchemePrefix() {
+ @Parameters(method = "getData")
+ public void timeSchemePrefix(Strategy strategy) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStrategy.execute("http://android.com");
+ strategy.execute("http://android.com");
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java
index 96e7cb2..a9a0788 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/SignaturePerfTest.java
@@ -19,12 +19,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
@@ -37,13 +37,12 @@
import java.util.Map;
/** Tests RSA and DSA mSignature creation and verification. */
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class SignaturePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mAlgorithm={0}, mImplementation={1}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{Algorithm.MD5WithRSA, Implementation.OpenSSL},
@@ -55,12 +54,6 @@
});
}
- @Parameterized.Parameter(0)
- public Algorithm mAlgorithm;
-
- @Parameterized.Parameter(1)
- public Implementation mImplementation;
-
private static final int DATA_SIZE = 8192;
private static final byte[] DATA = new byte[DATA_SIZE];
@@ -94,9 +87,8 @@
private PrivateKey mPrivateKey;
private PublicKey mPublicKey;
- @Before
- public void setUp() throws Exception {
- this.mSignatureAlgorithm = mAlgorithm.toString();
+ public void setUp(Algorithm algorithm) throws Exception {
+ this.mSignatureAlgorithm = algorithm.toString();
String keyAlgorithm =
mSignatureAlgorithm.substring(
@@ -121,11 +113,13 @@
}
@Test
- public void timeSign() throws Exception {
+ @Parameters(method = "getData")
+ public void timeSign(Algorithm algorithm, Implementation implementation) throws Exception {
+ setUp(algorithm);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
Signature signer;
- switch (mImplementation) {
+ switch (implementation) {
case OpenSSL:
signer = Signature.getInstance(mSignatureAlgorithm, "AndroidOpenSSL");
break;
@@ -133,7 +127,7 @@
signer = Signature.getInstance(mSignatureAlgorithm, "BC");
break;
default:
- throw new RuntimeException(mImplementation.toString());
+ throw new RuntimeException(implementation.toString());
}
signer.initSign(mPrivateKey);
signer.update(DATA);
@@ -142,11 +136,13 @@
}
@Test
- public void timeVerify() throws Exception {
+ @Parameters(method = "getData")
+ public void timeVerify(Algorithm algorithm, Implementation implementation) throws Exception {
+ setUp(algorithm);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
Signature verifier;
- switch (mImplementation) {
+ switch (implementation) {
case OpenSSL:
verifier = Signature.getInstance(mSignatureAlgorithm, "AndroidOpenSSL");
break;
@@ -154,7 +150,7 @@
verifier = Signature.getInstance(mSignatureAlgorithm, "BC");
break;
default:
- throw new RuntimeException(mImplementation.toString());
+ throw new RuntimeException(implementation.toString());
}
verifier.initVerify(mPublicKey);
verifier.update(DATA);
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java
index 02194b1..36db014 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/StringPerfTest.java
@@ -20,16 +20,17 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class StringPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -46,8 +47,7 @@
}
}
- @Parameters(name = "mStringLengths={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{StringLengths.EIGHT_KI},
@@ -57,9 +57,6 @@
});
}
- @Parameterized.Parameter(0)
- public StringLengths mStringLengths;
-
private static String makeString(int length) {
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; ++i) {
@@ -69,10 +66,11 @@
}
@Test
- public void timeHashCode() {
+ @Parameters(method = "getData")
+ public void timeHashCode(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.hashCode();
+ stringLengths.mValue.hashCode();
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java
index b0d1ee4..5b4423a 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/StringReplaceAllPerfTest.java
@@ -20,16 +20,17 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class StringReplaceAllPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -69,8 +70,7 @@
return stringBuilder.toString();
}
- @Parameters(name = "mStringLengths={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{StringLengths.BOOT_IMAGE},
@@ -82,30 +82,30 @@
});
}
- @Parameterized.Parameter(0)
- public StringLengths mStringLengths;
-
@Test
- public void timeReplaceAllTrivialPatternNonExistent() {
+ @Parameters(method = "getData")
+ public void timeReplaceAllTrivialPatternNonExistent(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replaceAll("fish", "0");
+ stringLengths.mValue.replaceAll("fish", "0");
}
}
@Test
- public void timeReplaceTrivialPatternAllRepeated() {
+ @Parameters(method = "getData")
+ public void timeReplaceTrivialPatternAllRepeated(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replaceAll("jklm", "0");
+ stringLengths.mValue.replaceAll("jklm", "0");
}
}
@Test
- public void timeReplaceAllTrivialPatternSingleOccurrence() {
+ @Parameters(method = "getData")
+ public void timeReplaceAllTrivialPatternSingleOccurrence(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replaceAll("qrst", "0");
+ stringLengths.mValue.replaceAll("qrst", "0");
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java
index d2e657a..4d5c792 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/StringReplacePerfTest.java
@@ -20,16 +20,17 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class StringReplacePerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -64,8 +65,7 @@
return stringBuilder.toString();
}
- @Parameters(name = "mStringLengths={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{StringLengths.EMPTY},
@@ -76,54 +76,57 @@
});
}
- @Parameterized.Parameter(0)
- public StringLengths mStringLengths;
-
@Test
- public void timeReplaceCharNonExistent() {
+ @Parameters(method = "getData")
+ public void timeReplaceCharNonExistent(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace('z', '0');
+ stringLengths.mValue.replace('z', '0');
}
}
@Test
- public void timeReplaceCharRepeated() {
+ @Parameters(method = "getData")
+ public void timeReplaceCharRepeated(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace('a', '0');
+ stringLengths.mValue.replace('a', '0');
}
}
@Test
- public void timeReplaceSingleChar() {
+ @Parameters(method = "getData")
+ public void timeReplaceSingleChar(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace('q', '0');
+ stringLengths.mValue.replace('q', '0');
}
}
@Test
- public void timeReplaceSequenceNonExistent() {
+ @Parameters(method = "getData")
+ public void timeReplaceSequenceNonExistent(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace("fish", "0");
+ stringLengths.mValue.replace("fish", "0");
}
}
@Test
- public void timeReplaceSequenceRepeated() {
+ @Parameters(method = "getData")
+ public void timeReplaceSequenceRepeated(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace("jklm", "0");
+ stringLengths.mValue.replace("jklm", "0");
}
}
@Test
- public void timeReplaceSingleSequence() {
+ @Parameters(method = "getData")
+ public void timeReplaceSingleSequence(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.replace("qrst", "0");
+ stringLengths.mValue.replace("qrst", "0");
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java
index 1efc188..c004d95 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/StringToBytesPerfTest.java
@@ -20,17 +20,18 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class StringToBytesPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@@ -53,8 +54,7 @@
}
}
- @Parameters(name = "mStringLengths={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{StringLengths.EMPTY},
@@ -69,9 +69,6 @@
});
}
- @Parameterized.Parameter(0)
- public StringLengths mStringLengths;
-
private static String makeString(int length) {
char[] chars = new char[length];
for (int i = 0; i < length; ++i) {
@@ -89,26 +86,29 @@
}
@Test
- public void timeGetBytesUtf8() {
+ @Parameters(method = "getData")
+ public void timeGetBytesUtf8(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.getBytes(StandardCharsets.UTF_8);
+ stringLengths.mValue.getBytes(StandardCharsets.UTF_8);
}
}
@Test
- public void timeGetBytesIso88591() {
+ @Parameters(method = "getData")
+ public void timeGetBytesIso88591(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.getBytes(StandardCharsets.ISO_8859_1);
+ stringLengths.mValue.getBytes(StandardCharsets.ISO_8859_1);
}
}
@Test
- public void timeGetBytesAscii() {
+ @Parameters(method = "getData")
+ public void timeGetBytesAscii(StringLengths stringLengths) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- mStringLengths.mValue.getBytes(StandardCharsets.US_ASCII);
+ stringLengths.mValue.getBytes(StandardCharsets.US_ASCII);
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java
index b01948a..15516fc 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/StringToRealPerfTest.java
@@ -20,22 +20,22 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public class StringToRealPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mString={0}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{"NaN"},
@@ -49,22 +49,21 @@
});
}
- @Parameterized.Parameter(0)
- public String mString;
-
@Test
- public void timeFloat_parseFloat() {
+ @Parameters(method = "getData")
+ public void timeFloat_parseFloat(String string) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- Float.parseFloat(mString);
+ Float.parseFloat(string);
}
}
@Test
- public void timeDouble_parseDouble() {
+ @Parameters(method = "getData")
+ public void timeDouble_parseDouble(String string) {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
- Double.parseDouble(mString);
+ Double.parseDouble(string);
}
}
}
diff --git a/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java b/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java
index 2ea834d..ae1e8bc 100644
--- a/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java
+++ b/apct-tests/perftests/core/src/android/libcore/regression/XMLEntitiesPerfTest.java
@@ -20,12 +20,12 @@
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
-import org.junit.Before;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.InputSource;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
@@ -38,13 +38,12 @@
import javax.xml.parsers.DocumentBuilderFactory;
// http://code.google.com/p/android/issues/detail?id=18102
-@RunWith(Parameterized.class)
+@RunWith(JUnitParamsRunner.class)
@LargeTest
public final class XMLEntitiesPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
- @Parameters(name = "mLength={0}, mEntityFraction={1}")
- public static Collection<Object[]> data() {
+ public static Collection<Object[]> getData() {
return Arrays.asList(
new Object[][] {
{10, 0},
@@ -59,29 +58,22 @@
});
}
- @Parameterized.Parameter(0)
- public int mLength;
-
- @Parameterized.Parameter(1)
- public float mEntityFraction;
-
private XmlPullParserFactory mXmlPullParserFactory;
private DocumentBuilderFactory mDocumentBuilderFactory;
/** a string like {@code <doc>&&++</doc>}. */
private String mXml;
- @Before
- public void setUp() throws Exception {
+ public void setUp(int length, float entityFraction) throws Exception {
mXmlPullParserFactory = XmlPullParserFactory.newInstance();
mDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<doc>");
- for (int i = 0; i < (mLength * mEntityFraction); i++) {
+ for (int i = 0; i < (length * entityFraction); i++) {
xmlBuilder.append("&");
}
- while (xmlBuilder.length() < mLength) {
+ while (xmlBuilder.length() < length) {
xmlBuilder.append("+");
}
xmlBuilder.append("</doc>");
@@ -89,7 +81,9 @@
}
@Test
- public void timeXmlParser() throws Exception {
+ @Parameters(method = "getData")
+ public void timeXmlParser(int length, float entityFraction) throws Exception {
+ setUp(length, entityFraction);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
XmlPullParser parser = mXmlPullParserFactory.newPullParser();
@@ -101,7 +95,9 @@
}
@Test
- public void timeDocumentBuilder() throws Exception {
+ @Parameters(method = "getData")
+ public void timeDocumentBuilder(int length, float entityFraction) throws Exception {
+ setUp(length, entityFraction);
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
DocumentBuilder documentBuilder = mDocumentBuilderFactory.newDocumentBuilder();
diff --git a/api/Android.bp b/api/Android.bp
index 210b8f5..ef88790 100644
--- a/api/Android.bp
+++ b/api/Android.bp
@@ -109,6 +109,7 @@
"framework-sdksandbox",
"framework-tethering",
"framework-uwb",
+ "framework-virtualization",
"framework-wifi",
"i18n.module.public.api",
],
diff --git a/api/api.go b/api/api.go
index 6a6c493..ba0fdc1 100644
--- a/api/api.go
+++ b/api/api.go
@@ -27,8 +27,16 @@
const art = "art.module.public.api"
const conscrypt = "conscrypt.module.public.api"
const i18n = "i18n.module.public.api"
+const virtualization = "framework-virtualization"
var core_libraries_modules = []string{art, conscrypt, i18n}
+// List of modules that are not yet updatable, and hence they can still compile
+// against hidden APIs. These modules are filtered out when building the
+// updatable-framework-module-impl (because updatable-framework-module-impl is
+// built against module_current SDK). Instead they are directly statically
+// linked into the all-framework-module-lib, which is building against hidden
+// APIs.
+var non_updatable_modules = []string{virtualization}
// The intention behind this soong plugin is to generate a number of "merged"
// API-related modules that would otherwise require a large amount of very
@@ -249,12 +257,31 @@
func createMergedFrameworkImpl(ctx android.LoadHookContext, modules []string) {
// This module is for the "framework-all" module, which should not include the core libraries.
modules = removeAll(modules, core_libraries_modules)
- props := libraryProps{}
- props.Name = proptools.StringPtr("all-framework-module-impl")
- props.Static_libs = transformArray(modules, "", ".impl")
- props.Sdk_version = proptools.StringPtr("module_current")
- props.Visibility = []string{"//frameworks/base"}
- ctx.CreateModule(java.LibraryFactory, &props)
+ // Remove the modules that belong to non-updatable APEXes since those are allowed to compile
+ // against unstable APIs.
+ modules = removeAll(modules, non_updatable_modules)
+ // First create updatable-framework-module-impl, which contains all updatable modules.
+ // This module compiles against module_lib SDK.
+ {
+ props := libraryProps{}
+ props.Name = proptools.StringPtr("updatable-framework-module-impl")
+ props.Static_libs = transformArray(modules, "", ".impl")
+ props.Sdk_version = proptools.StringPtr("module_current")
+ props.Visibility = []string{"//frameworks/base"}
+ ctx.CreateModule(java.LibraryFactory, &props)
+ }
+
+ // Now create all-framework-module-impl, which contains updatable-framework-module-impl
+ // and all non-updatable modules. This module compiles against hidden APIs.
+ {
+ props := libraryProps{}
+ props.Name = proptools.StringPtr("all-framework-module-impl")
+ props.Static_libs = transformArray(non_updatable_modules, "", ".impl")
+ props.Static_libs = append(props.Static_libs, "updatable-framework-module-impl")
+ props.Sdk_version = proptools.StringPtr("core_platform")
+ props.Visibility = []string{"//frameworks/base"}
+ ctx.CreateModule(java.LibraryFactory, &props)
+ }
}
func createMergedFrameworkModuleLibStubs(ctx android.LoadHookContext, modules []string) {
diff --git a/boot/Android.bp b/boot/Android.bp
index 3f14ebc..24ad9de 100644
--- a/boot/Android.bp
+++ b/boot/Android.bp
@@ -120,6 +120,10 @@
apex: "com.android.car.framework",
module: "com.android.car.framework-bootclasspath-fragment",
},
+ {
+ apex: "com.android.virt",
+ module: "com.android.virt-bootclasspath-fragment",
+ },
],
// Additional information needed by hidden api processing.
diff --git a/core/api/current.txt b/core/api/current.txt
index ffecc09..2f1845f 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -31933,6 +31933,7 @@
method public static final boolean is64Bit();
method public static boolean isApplicationUid(int);
method public static final boolean isIsolated();
+ method public static final boolean isIsolatedUid(int);
method public static final boolean isSdkSandbox();
method public static final void killProcess(int);
method public static final int myPid();
@@ -41323,7 +41324,7 @@
field public static final String KEY_GSM_ROAMING_NETWORKS_STRING_ARRAY = "gsm_roaming_networks_string_array";
field public static final String KEY_HAS_IN_CALL_NOISE_SUPPRESSION_BOOL = "has_in_call_noise_suppression_bool";
field public static final String KEY_HIDE_CARRIER_NETWORK_SETTINGS_BOOL = "hide_carrier_network_settings_bool";
- field public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool";
+ field @Deprecated public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool";
field public static final String KEY_HIDE_ENHANCED_4G_LTE_BOOL = "hide_enhanced_4g_lte_bool";
field public static final String KEY_HIDE_IMS_APN_BOOL = "hide_ims_apn_bool";
field public static final String KEY_HIDE_LTE_PLUS_DATA_ICON_BOOL = "hide_lte_plus_data_icon_bool";
diff --git a/core/api/module-lib-current.txt b/core/api/module-lib-current.txt
index 068b40a..9b556d8 100644
--- a/core/api/module-lib-current.txt
+++ b/core/api/module-lib-current.txt
@@ -348,6 +348,7 @@
}
public final class ServiceManager {
+ method @NonNull public static String[] getDeclaredInstances(@NonNull String);
method public static boolean isDeclared(@NonNull String);
method @Nullable public static android.os.IBinder waitForDeclaredService(@NonNull String);
}
@@ -382,6 +383,7 @@
method public static void traceBegin(long, @NonNull String);
method public static void traceCounter(long, @NonNull String, int);
method public static void traceEnd(long);
+ field public static final long TRACE_TAG_AIDL = 16777216L; // 0x1000000L
field public static final long TRACE_TAG_NETWORK = 2097152L; // 0x200000L
}
diff --git a/core/api/system-current.txt b/core/api/system-current.txt
index 4a0d771..d5e7892 100644
--- a/core/api/system-current.txt
+++ b/core/api/system-current.txt
@@ -3406,6 +3406,7 @@
field public static final String FEATURE_REBOOT_ESCROW = "android.hardware.reboot_escrow";
field public static final String FEATURE_TELEPHONY_CARRIERLOCK = "android.hardware.telephony.carrierlock";
field public static final String FEATURE_TELEPHONY_IMS_SINGLE_REGISTRATION = "android.hardware.telephony.ims.singlereg";
+ field public static final String FEATURE_VIRTUALIZATION_FRAMEWORK = "android.software.virtualization_framework";
field public static final int FLAGS_PERMISSION_RESERVED_PERMISSION_CONTROLLER = -268435456; // 0xf0000000
field public static final int FLAG_PERMISSION_APPLY_RESTRICTION = 16384; // 0x4000
field public static final int FLAG_PERMISSION_AUTO_REVOKED = 131072; // 0x20000
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index c0aebee..7bfb1b5 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -48,6 +48,13 @@
private String mPkg;
/**
+ * The maximum string length for any string contained in this automatic zen rule. This pertains
+ * both to fields in the rule itself (such as its name) and items with sub-fields.
+ * @hide
+ */
+ public static final int MAX_STRING_LENGTH = 1000;
+
+ /**
* Creates an automatic zen rule.
*
* @param name The name of the rule.
@@ -93,10 +100,10 @@
public AutomaticZenRule(@NonNull String name, @Nullable ComponentName owner,
@Nullable ComponentName configurationActivity, @NonNull Uri conditionId,
@Nullable ZenPolicy policy, int interruptionFilter, boolean enabled) {
- this.name = name;
- this.owner = owner;
- this.configurationActivity = configurationActivity;
- this.conditionId = conditionId;
+ this.name = getTrimmedString(name);
+ this.owner = getTrimmedComponentName(owner);
+ this.configurationActivity = getTrimmedComponentName(configurationActivity);
+ this.conditionId = getTrimmedUri(conditionId);
this.interruptionFilter = interruptionFilter;
this.enabled = enabled;
this.mZenPolicy = policy;
@@ -115,12 +122,14 @@
public AutomaticZenRule(Parcel source) {
enabled = source.readInt() == ENABLED;
if (source.readInt() == ENABLED) {
- name = source.readString();
+ name = getTrimmedString(source.readString());
}
interruptionFilter = source.readInt();
- conditionId = source.readParcelable(null, android.net.Uri.class);
- owner = source.readParcelable(null, android.content.ComponentName.class);
- configurationActivity = source.readParcelable(null, android.content.ComponentName.class);
+ conditionId = getTrimmedUri(source.readParcelable(null, android.net.Uri.class));
+ owner = getTrimmedComponentName(
+ source.readParcelable(null, android.content.ComponentName.class));
+ configurationActivity = getTrimmedComponentName(
+ source.readParcelable(null, android.content.ComponentName.class));
creationTime = source.readLong();
mZenPolicy = source.readParcelable(null, android.service.notification.ZenPolicy.class);
mModified = source.readInt() == ENABLED;
@@ -196,7 +205,7 @@
* Sets the representation of the state that causes this rule to become active.
*/
public void setConditionId(Uri conditionId) {
- this.conditionId = conditionId;
+ this.conditionId = getTrimmedUri(conditionId);
}
/**
@@ -211,7 +220,7 @@
* Sets the name of this rule.
*/
public void setName(String name) {
- this.name = name;
+ this.name = getTrimmedString(name);
}
/**
@@ -243,7 +252,7 @@
* that are not backed by {@link android.service.notification.ConditionProviderService}.
*/
public void setConfigurationActivity(@Nullable ComponentName componentName) {
- this.configurationActivity = componentName;
+ this.configurationActivity = getTrimmedComponentName(componentName);
}
/**
@@ -333,4 +342,35 @@
return new AutomaticZenRule[size];
}
};
+
+ /**
+ * If the package or class name of the provided ComponentName are longer than MAX_STRING_LENGTH,
+ * return a trimmed version that truncates each of the package and class name at the max length.
+ */
+ private static ComponentName getTrimmedComponentName(ComponentName cn) {
+ if (cn == null) return null;
+ return new ComponentName(getTrimmedString(cn.getPackageName()),
+ getTrimmedString(cn.getClassName()));
+ }
+
+ /**
+ * Returns a truncated copy of the string if the string is longer than MAX_STRING_LENGTH.
+ */
+ private static String getTrimmedString(String input) {
+ if (input != null && input.length() > MAX_STRING_LENGTH) {
+ return input.substring(0, MAX_STRING_LENGTH);
+ }
+ return input;
+ }
+
+ /**
+ * Returns a truncated copy of the Uri by trimming the string representation to the maximum
+ * string length.
+ */
+ private static Uri getTrimmedUri(Uri input) {
+ if (input != null && input.toString().length() > MAX_STRING_LENGTH) {
+ return Uri.parse(getTrimmedString(input.toString()));
+ }
+ return input;
+ }
}
diff --git a/core/java/android/app/OWNERS b/core/java/android/app/OWNERS
index 2012948..8ec313ec 100644
--- a/core/java/android/app/OWNERS
+++ b/core/java/android/app/OWNERS
@@ -30,10 +30,12 @@
per-file Service* = file:/services/core/java/com/android/server/am/OWNERS
per-file SystemServiceRegistry.java = file:/services/core/java/com/android/server/am/OWNERS
per-file *UserSwitchObserver* = file:/services/core/java/com/android/server/am/OWNERS
-per-file UiAutomation* = file:/services/accessibility/OWNERS
+per-file *UiAutomation* = file:/services/accessibility/OWNERS
per-file GameManager* = file:/GAME_MANAGER_OWNERS
+per-file GameMode* = file:/GAME_MANAGER_OWNERS
per-file GameState* = file:/GAME_MANAGER_OWNERS
per-file IGameManager* = file:/GAME_MANAGER_OWNERS
+per-file IGameMode* = file:/GAME_MANAGER_OWNERS
# ActivityThread
per-file ActivityThread.java = file:/services/core/java/com/android/server/am/OWNERS
diff --git a/core/java/android/app/SearchableInfo.java b/core/java/android/app/SearchableInfo.java
index 5388282..bd5d105 100644
--- a/core/java/android/app/SearchableInfo.java
+++ b/core/java/android/app/SearchableInfo.java
@@ -396,6 +396,17 @@
private final String mSuggestActionMsg;
private final String mSuggestActionMsgColumn;
+ public static final Parcelable.Creator<ActionKeyInfo> CREATOR =
+ new Parcelable.Creator<ActionKeyInfo>() {
+ public ActionKeyInfo createFromParcel(Parcel in) {
+ return new ActionKeyInfo(in);
+ }
+
+ public ActionKeyInfo[] newArray(int size) {
+ return new ActionKeyInfo[size];
+ }
+ };
+
/**
* Create one object using attributeset as input data.
* @param activityContext runtime context of the activity that the action key information
diff --git a/core/java/android/content/ActivityNotFoundException.java b/core/java/android/content/ActivityNotFoundException.java
index 16149bb..5b50189 100644
--- a/core/java/android/content/ActivityNotFoundException.java
+++ b/core/java/android/content/ActivityNotFoundException.java
@@ -31,5 +31,4 @@
{
super(name);
}
-};
-
+}
diff --git a/core/java/android/content/AttributionSource.java b/core/java/android/content/AttributionSource.java
index b0c6cbc..e981581 100644
--- a/core/java/android/content/AttributionSource.java
+++ b/core/java/android/content/AttributionSource.java
@@ -29,6 +29,7 @@
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Process;
+import android.os.UserHandle;
import android.permission.PermissionManager;
import android.util.ArraySet;
@@ -297,7 +298,7 @@
public boolean checkCallingUid() {
final int callingUid = Binder.getCallingUid();
if (callingUid != Process.ROOT_UID
- && callingUid != Process.SYSTEM_UID
+ && UserHandle.getAppId(callingUid) != Process.SYSTEM_UID
&& callingUid != mAttributionSourceState.uid) {
return false;
}
diff --git a/core/java/android/content/integrity/AtomicFormula.java b/core/java/android/content/integrity/AtomicFormula.java
index f888813..1b5f64c 100644
--- a/core/java/android/content/integrity/AtomicFormula.java
+++ b/core/java/android/content/integrity/AtomicFormula.java
@@ -261,8 +261,8 @@
}
LongAtomicFormula that = (LongAtomicFormula) o;
return getKey() == that.getKey()
- && mValue == that.mValue
- && mOperator == that.mOperator;
+ && Objects.equals(mValue, that.mValue)
+ && Objects.equals(mOperator, that.mOperator);
}
@Override
@@ -628,7 +628,7 @@
return false;
}
BooleanAtomicFormula that = (BooleanAtomicFormula) o;
- return getKey() == that.getKey() && mValue == that.mValue;
+ return getKey() == that.getKey() && Objects.equals(mValue, that.mValue);
}
@Override
diff --git a/core/java/android/content/pm/OWNERS b/core/java/android/content/pm/OWNERS
index 25efdc6..a6674370 100644
--- a/core/java/android/content/pm/OWNERS
+++ b/core/java/android/content/pm/OWNERS
@@ -1,12 +1,10 @@
# Bug component: 36137
-patb@google.com
+file:/PACKAGE_MANAGER_OWNERS
-per-file Package* = file:/PACKAGE_MANAGER_OWNERS
per-file PackageParser.java = set noparent
per-file PackageParser.java = chiuwinson@google.com,patb@google.com
per-file *Capability* = file:/core/java/android/content/pm/SHORTCUT_OWNERS
per-file *Shortcut* = file:/core/java/android/content/pm/SHORTCUT_OWNERS
-per-file AppSearchPerson.java = file:/core/java/android/content/pm/SHORTCUT_OWNERS
per-file *Launcher* = file:/core/java/android/content/pm/LAUNCHER_OWNERS
per-file UserInfo* = file:/MULTIUSER_OWNERS
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index a90f6d6..6c53618 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -189,12 +189,12 @@
@VisibleForTesting
public Property(@NonNull String name, int type,
@NonNull String packageName, @Nullable String className) {
- assert name != null;
- assert type >= TYPE_BOOLEAN && type <= TYPE_STRING;
- assert packageName != null;
- this.mName = name;
+ if (type < TYPE_BOOLEAN || type > TYPE_STRING) {
+ throw new IllegalArgumentException("Invalid type");
+ }
+ this.mName = Objects.requireNonNull(name);
this.mType = type;
- this.mPackageName = packageName;
+ this.mPackageName = Objects.requireNonNull(packageName);
this.mClassName = className;
}
/** @hide */
@@ -442,9 +442,8 @@
*/
public ComponentEnabledSetting(@NonNull ComponentName componentName,
@EnabledState int newState, @EnabledFlags int flags) {
- Objects.nonNull(componentName);
mPackageName = null;
- mComponentName = componentName;
+ mComponentName = Objects.requireNonNull(componentName);
mEnabledState = newState;
mEnabledFlags = flags;
}
@@ -460,8 +459,7 @@
*/
public ComponentEnabledSetting(@NonNull String packageName,
@EnabledState int newState, @EnabledFlags int flags) {
- Objects.nonNull(packageName);
- mPackageName = packageName;
+ mPackageName = Objects.requireNonNull(packageName);
mComponentName = null;
mEnabledState = newState;
mEnabledFlags = flags;
@@ -2947,6 +2945,18 @@
public static final String FEATURE_OPENGLES_EXTENSION_PACK = "android.hardware.opengles.aep";
/**
+ * Feature for {@link #getSystemAvailableFeatures()} and {@link #hasSystemFeature(String)}.
+ * This feature indicates whether device supports
+ * <a href="https://source.android.com/docs/core/virtualization">Android Virtualization Framework</a>.
+ *
+ * @hide
+ */
+ @SystemApi
+ @SdkConstant(SdkConstantType.FEATURE)
+ public static final String FEATURE_VIRTUALIZATION_FRAMEWORK =
+ "android.software.virtualization_framework";
+
+ /**
* Feature for {@link #getSystemAvailableFeatures} and
* {@link #hasSystemFeature(String, int)}: If this feature is supported, the Vulkan
* implementation on this device is hardware accelerated, and the Vulkan native API will
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index 1f83d75..295df5c 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -50,6 +50,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.Preconditions;
+import java.lang.IllegalArgumentException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
@@ -1360,7 +1361,9 @@
@NonNull
public Builder setIntents(@NonNull Intent[] intents) {
Objects.requireNonNull(intents, "intents cannot be null");
- Objects.requireNonNull(intents.length, "intents cannot be empty");
+ if (intents.length == 0) {
+ throw new IllegalArgumentException("intents cannot be empty");
+ }
for (Intent intent : intents) {
Objects.requireNonNull(intent, "intents cannot contain null");
Objects.requireNonNull(intent.getAction(), "intent's action must be set");
@@ -1398,7 +1401,9 @@
@NonNull
public Builder setPersons(@NonNull Person[] persons) {
Objects.requireNonNull(persons, "persons cannot be null");
- Objects.requireNonNull(persons.length, "persons cannot be empty");
+ if (persons.length == 0) {
+ throw new IllegalArgumentException("persons cannot be empty");
+ }
for (Person person : persons) {
Objects.requireNonNull(person, "persons cannot contain null");
}
diff --git a/core/java/android/hardware/CameraInfo.java b/core/java/android/hardware/CameraInfo.java
index 072be50..41ef6aa 100644
--- a/core/java/android/hardware/CameraInfo.java
+++ b/core/java/android/hardware/CameraInfo.java
@@ -60,4 +60,4 @@
return new CameraInfo[size];
}
};
-};
+}
diff --git a/core/java/android/hardware/CameraStatus.java b/core/java/android/hardware/CameraStatus.java
index 874af29..fa35efb 100644
--- a/core/java/android/hardware/CameraStatus.java
+++ b/core/java/android/hardware/CameraStatus.java
@@ -68,4 +68,4 @@
return new CameraStatus[size];
}
};
-};
+}
diff --git a/core/java/android/hardware/biometrics/CryptoObject.java b/core/java/android/hardware/biometrics/CryptoObject.java
index d415706..267ef36 100644
--- a/core/java/android/hardware/biometrics/CryptoObject.java
+++ b/core/java/android/hardware/biometrics/CryptoObject.java
@@ -118,4 +118,4 @@
}
return AndroidKeyStoreProvider.getKeyStoreOperationHandle(mCrypto);
}
-};
+}
diff --git a/core/java/android/hardware/camera2/impl/FrameNumberTracker.java b/core/java/android/hardware/camera2/impl/FrameNumberTracker.java
index 7b6a457..8304796 100644
--- a/core/java/android/hardware/camera2/impl/FrameNumberTracker.java
+++ b/core/java/android/hardware/camera2/impl/FrameNumberTracker.java
@@ -26,6 +26,7 @@
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.TreeMap;
/**
@@ -63,11 +64,11 @@
}
private void update() {
- Iterator iter = mFutureErrorMap.entrySet().iterator();
+ Iterator<Map.Entry<Long, Integer>> iter = mFutureErrorMap.entrySet().iterator();
while (iter.hasNext()) {
- TreeMap.Entry pair = (TreeMap.Entry)iter.next();
- Long errorFrameNumber = (Long)pair.getKey();
- int requestType = (int) pair.getValue();
+ Map.Entry<Long, Integer> pair = iter.next();
+ long errorFrameNumber = pair.getKey();
+ int requestType = pair.getValue();
Boolean removeError = false;
if (errorFrameNumber == mCompletedFrameNumber[requestType] + 1) {
removeError = true;
diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java
index 621a418..92a2fb6 100644
--- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java
+++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java
@@ -103,6 +103,7 @@
return new MarshalerEnum(managedType, nativeType);
}
+ @SuppressWarnings("ReturnValueIgnored")
@Override
public boolean isTypeMappingSupported(TypeReference<T> managedType, int nativeType) {
if (nativeType == TYPE_INT32 || nativeType == TYPE_BYTE) {
diff --git a/core/java/android/hardware/camera2/params/OutputConfiguration.java b/core/java/android/hardware/camera2/params/OutputConfiguration.java
index 4a25177..bbe2319 100644
--- a/core/java/android/hardware/camera2/params/OutputConfiguration.java
+++ b/core/java/android/hardware/camera2/params/OutputConfiguration.java
@@ -1270,7 +1270,8 @@
return false;
}
for (int j = 0; j < mSensorPixelModesUsed.size(); j++) {
- if (mSensorPixelModesUsed.get(j) != other.mSensorPixelModesUsed.get(j)) {
+ if (!Objects.equals(
+ mSensorPixelModesUsed.get(j), other.mSensorPixelModesUsed.get(j))) {
return false;
}
}
diff --git a/core/java/android/hardware/fingerprint/Fingerprint.java b/core/java/android/hardware/fingerprint/Fingerprint.java
index 9ce834ca..c01c94c 100644
--- a/core/java/android/hardware/fingerprint/Fingerprint.java
+++ b/core/java/android/hardware/fingerprint/Fingerprint.java
@@ -69,4 +69,4 @@
return new Fingerprint[size];
}
};
-};
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/core/java/android/hardware/radio/OWNERS b/core/java/android/hardware/radio/OWNERS
index d2bdd64..302fdd7 100644
--- a/core/java/android/hardware/radio/OWNERS
+++ b/core/java/android/hardware/radio/OWNERS
@@ -1,3 +1,4 @@
xuweilin@google.com
oscarazu@google.com
+ericjeong@google.com
keunyoung@google.com
diff --git a/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java b/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
index 76ee097..5eeb607 100644
--- a/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
+++ b/core/java/android/net/netstats/NetworkStatsDataMigrationUtils.java
@@ -53,8 +53,8 @@
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
/**
@@ -89,12 +89,10 @@
@Retention(RetentionPolicy.SOURCE)
public @interface Prefix {}
- private static final HashMap<String, String> sPrefixLegacyFileNameMap =
- new HashMap<String, String>() {{
- put(PREFIX_XT, "netstats_xt.bin");
- put(PREFIX_UID, "netstats_uid.bin");
- put(PREFIX_UID_TAG, "netstats_uid.bin");
- }};
+ private static final Map<String, String> sPrefixLegacyFileNameMap = Map.of(
+ PREFIX_XT, "netstats_xt.bin",
+ PREFIX_UID, "netstats_uid.bin",
+ PREFIX_UID_TAG, "netstats_uid.bin");
// These version constants are copied from NetworkStatsCollection/History, which is okay for
// OEMs to modify to adapt their own logic.
diff --git a/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java b/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java
index 4bc5b49..0427742 100644
--- a/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java
+++ b/core/java/android/net/vcn/persistablebundleutils/TunnelConnectionParamsUtils.java
@@ -53,7 +53,7 @@
if (in.keySet().size() != EXPECTED_BUNDLE_KEY_CNT) {
throw new IllegalArgumentException(
String.format(
- "Expect PersistableBundle to have %d element but found: %d",
+ "Expect PersistableBundle to have %d element but found: %s",
EXPECTED_BUNDLE_KEY_CNT, in.keySet()));
}
diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java
index 64c1211..3282d56 100644
--- a/core/java/android/nfc/NfcAdapter.java
+++ b/core/java/android/nfc/NfcAdapter.java
@@ -29,7 +29,6 @@
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.content.IntentFilter;
-import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.tech.MifareClassic;
@@ -525,66 +524,6 @@
}
/**
- * Helper to check if this device has FEATURE_NFC_BEAM, but without using
- * a context.
- * Equivalent to
- * context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC_BEAM)
- */
- private static boolean hasBeamFeature() {
- IPackageManager pm = ActivityThread.getPackageManager();
- if (pm == null) {
- Log.e(TAG, "Cannot get package manager, assuming no Android Beam feature");
- return false;
- }
- try {
- return pm.hasSystemFeature(PackageManager.FEATURE_NFC_BEAM, 0);
- } catch (RemoteException e) {
- Log.e(TAG, "Package manager query failed, assuming no Android Beam feature", e);
- return false;
- }
- }
-
- /**
- * Helper to check if this device has FEATURE_NFC, but without using
- * a context.
- * Equivalent to
- * context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)
- */
- private static boolean hasNfcFeature() {
- IPackageManager pm = ActivityThread.getPackageManager();
- if (pm == null) {
- Log.e(TAG, "Cannot get package manager, assuming no NFC feature");
- return false;
- }
- try {
- return pm.hasSystemFeature(PackageManager.FEATURE_NFC, 0);
- } catch (RemoteException e) {
- Log.e(TAG, "Package manager query failed, assuming no NFC feature", e);
- return false;
- }
- }
-
- /**
- * Helper to check if this device is NFC HCE capable, by checking for
- * FEATURE_NFC_HOST_CARD_EMULATION and/or FEATURE_NFC_HOST_CARD_EMULATION_NFCF,
- * but without using a context.
- */
- private static boolean hasNfcHceFeature() {
- IPackageManager pm = ActivityThread.getPackageManager();
- if (pm == null) {
- Log.e(TAG, "Cannot get package manager, assuming no NFC feature");
- return false;
- }
- try {
- return pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION, 0)
- || pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF, 0);
- } catch (RemoteException e) {
- Log.e(TAG, "Package manager query failed, assuming no NFC feature", e);
- return false;
- }
- }
-
- /**
* Return list of Secure Elements which support off host card emulation.
*
* @return List<String> containing secure elements on the device which supports
@@ -593,23 +532,21 @@
* @hide
*/
public @NonNull List<String> getSupportedOffHostSecureElements() {
+ if (mContext == null) {
+ throw new UnsupportedOperationException("You need a context on NfcAdapter to use the "
+ + " getSupportedOffHostSecureElements APIs");
+ }
List<String> offHostSE = new ArrayList<String>();
- IPackageManager pm = ActivityThread.getPackageManager();
+ PackageManager pm = mContext.getPackageManager();
if (pm == null) {
Log.e(TAG, "Cannot get package manager, assuming no off-host CE feature");
return offHostSE;
}
- try {
- if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_UICC, 0)) {
- offHostSE.add("SIM");
- }
- if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_ESE, 0)) {
- offHostSE.add("eSE");
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Package manager query failed, assuming no off-host CE feature", e);
- offHostSE.clear();
- return offHostSE;
+ if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_UICC)) {
+ offHostSE.add("SIM");
+ }
+ if (pm.hasSystemFeature(PackageManager.FEATURE_NFC_OFF_HOST_CARD_EMULATION_ESE)) {
+ offHostSE.add("eSE");
}
return offHostSE;
}
@@ -621,10 +558,19 @@
*/
@UnsupportedAppUsage
public static synchronized NfcAdapter getNfcAdapter(Context context) {
+ if (context == null) {
+ if (sNullContextNfcAdapter == null) {
+ sNullContextNfcAdapter = new NfcAdapter(null);
+ }
+ return sNullContextNfcAdapter;
+ }
if (!sIsInitialized) {
- sHasNfcFeature = hasNfcFeature();
- sHasBeamFeature = hasBeamFeature();
- boolean hasHceFeature = hasNfcHceFeature();
+ PackageManager pm = context.getPackageManager();
+ sHasNfcFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC);
+ sHasBeamFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC_BEAM);
+ boolean hasHceFeature =
+ pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)
+ || pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF);
/* is this device meant to have NFC */
if (!sHasNfcFeature && !hasHceFeature) {
Log.v(TAG, "this device does not have NFC support");
@@ -660,12 +606,6 @@
sIsInitialized = true;
}
- if (context == null) {
- if (sNullContextNfcAdapter == null) {
- sNullContextNfcAdapter = new NfcAdapter(null);
- }
- return sNullContextNfcAdapter;
- }
NfcAdapter adapter = sNfcAdapters.get(context);
if (adapter == null) {
adapter = new NfcAdapter(context);
@@ -676,8 +616,12 @@
/** get handle to NFC service interface */
private static INfcAdapter getServiceInterface() {
+ if (!sHasNfcFeature) {
+ /* NFC is not supported */
+ return null;
+ }
/* get a handle to NFC service */
- IBinder b = ServiceManager.getService("nfc");
+ IBinder b = ServiceManager.waitForService("nfc");
if (b == null) {
return null;
}
@@ -707,6 +651,15 @@
"context not associated with any application (using a mock context?)");
}
+ synchronized (NfcAdapter.class) {
+ if (!sIsInitialized) {
+ PackageManager pm = context.getPackageManager();
+ sHasNfcFeature = pm.hasSystemFeature(PackageManager.FEATURE_NFC);
+ }
+ if (!sHasNfcFeature) {
+ return null;
+ }
+ }
if (getServiceInterface() == null) {
// NFC is not available
return null;
diff --git a/core/java/android/nfc/cardemulation/CardEmulation.java b/core/java/android/nfc/cardemulation/CardEmulation.java
index 0b56d19..6a42091 100644
--- a/core/java/android/nfc/cardemulation/CardEmulation.java
+++ b/core/java/android/nfc/cardemulation/CardEmulation.java
@@ -22,11 +22,9 @@
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
import android.app.Activity;
-import android.app.ActivityThread;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
-import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.nfc.INfcCardEmulation;
import android.nfc.NfcAdapter;
@@ -158,18 +156,13 @@
throw new UnsupportedOperationException();
}
if (!sIsInitialized) {
- IPackageManager pm = ActivityThread.getPackageManager();
+ PackageManager pm = context.getPackageManager();
if (pm == null) {
Log.e(TAG, "Cannot get PackageManager");
throw new UnsupportedOperationException();
}
- try {
- if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION, 0)) {
- Log.e(TAG, "This device does not support card emulation");
- throw new UnsupportedOperationException();
- }
- } catch (RemoteException e) {
- Log.e(TAG, "PackageManager query failed.");
+ if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)) {
+ Log.e(TAG, "This device does not support card emulation");
throw new UnsupportedOperationException();
}
sIsInitialized = true;
diff --git a/core/java/android/nfc/cardemulation/NfcFCardEmulation.java b/core/java/android/nfc/cardemulation/NfcFCardEmulation.java
index 3c92455..48bbf5b6 100644
--- a/core/java/android/nfc/cardemulation/NfcFCardEmulation.java
+++ b/core/java/android/nfc/cardemulation/NfcFCardEmulation.java
@@ -17,10 +17,8 @@
package android.nfc.cardemulation;
import android.app.Activity;
-import android.app.ActivityThread;
import android.content.ComponentName;
import android.content.Context;
-import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.nfc.INfcFCardEmulation;
import android.nfc.NfcAdapter;
@@ -70,18 +68,13 @@
throw new UnsupportedOperationException();
}
if (!sIsInitialized) {
- IPackageManager pm = ActivityThread.getPackageManager();
+ PackageManager pm = context.getPackageManager();
if (pm == null) {
Log.e(TAG, "Cannot get PackageManager");
throw new UnsupportedOperationException();
}
- try {
- if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF, 0)) {
- Log.e(TAG, "This device does not support NFC-F card emulation");
- throw new UnsupportedOperationException();
- }
- } catch (RemoteException e) {
- Log.e(TAG, "PackageManager query failed.");
+ if (!pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION_NFCF)) {
+ Log.e(TAG, "This device does not support NFC-F card emulation");
throw new UnsupportedOperationException();
}
sIsInitialized = true;
diff --git a/core/java/android/os/BaseBundle.java b/core/java/android/os/BaseBundle.java
index 0418a4b..b599028 100644
--- a/core/java/android/os/BaseBundle.java
+++ b/core/java/android/os/BaseBundle.java
@@ -438,8 +438,11 @@
map.ensureCapacity(count);
}
try {
+ // recycleParcel being false implies that we do not own the parcel. In this case, do
+ // not use lazy values to be safe, as the parcel could be recycled outside of our
+ // control.
recycleParcel &= parcelledData.readArrayMap(map, count, !parcelledByNative,
- /* lazy */ true, mClassLoader);
+ /* lazy */ recycleParcel, mClassLoader);
} catch (BadParcelableException e) {
if (sShouldDefuse) {
Log.w(TAG, "Failed to parse Bundle, but defusing quietly", e);
@@ -1845,7 +1848,6 @@
// bundle immediately; neither of which is obvious.
synchronized (this) {
initializeFromParcelLocked(parcel, /*recycleParcel=*/ false, isNativeBundle);
- unparcel(/* itemwise */ true);
}
return;
}
diff --git a/core/java/android/os/BinderProxy.java b/core/java/android/os/BinderProxy.java
index 6330661..1929a4d 100644
--- a/core/java/android/os/BinderProxy.java
+++ b/core/java/android/os/BinderProxy.java
@@ -536,8 +536,8 @@
mWarnOnBlocking = false;
warnOnBlocking = false;
- if (Build.IS_USERDEBUG) {
- // Log this as a WTF on userdebug builds.
+ if (Build.IS_USERDEBUG || Build.IS_ENG) {
+ // Log this as a WTF on userdebug and eng builds.
Log.wtf(Binder.TAG,
"Outgoing transactions from this process must be FLAG_ONEWAY",
new Throwable());
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index b3afaec..bb74e19 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -901,9 +901,21 @@
return isIsolated(myUid());
}
- /** {@hide} */
- @UnsupportedAppUsage
+ /**
+ * @deprecated Use {@link #isIsolatedUid(int)} instead.
+ * {@hide}
+ */
+ @Deprecated
+ @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.TIRAMISU,
+ publicAlternatives = "Use {@link #isIsolatedUid(int)} instead.")
public static final boolean isIsolated(int uid) {
+ return isIsolatedUid(uid);
+ }
+
+ /**
+ * Returns whether the process with the given {@code uid} is an isolated sandbox.
+ */
+ public static final boolean isIsolatedUid(int uid) {
uid = UserHandle.getAppId(uid);
return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID)
|| (uid >= FIRST_APP_ZYGOTE_ISOLATED_UID && uid <= LAST_APP_ZYGOTE_ISOLATED_UID);
diff --git a/core/java/android/os/ServiceManager.java b/core/java/android/os/ServiceManager.java
index ba5ed43..9ea4278 100644
--- a/core/java/android/os/ServiceManager.java
+++ b/core/java/android/os/ServiceManager.java
@@ -258,12 +258,14 @@
* waitForService should always be able to return the service.
* @hide
*/
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+ @NonNull
public static String[] getDeclaredInstances(@NonNull String iface) {
try {
return getIServiceManager().getDeclaredInstances(iface);
} catch (RemoteException e) {
Log.e(TAG, "error in getDeclaredInstances", e);
- return null;
+ throw e.rethrowFromSystemServer();
}
}
diff --git a/core/java/android/os/Trace.java b/core/java/android/os/Trace.java
index 4965057..726ef4d 100644
--- a/core/java/android/os/Trace.java
+++ b/core/java/android/os/Trace.java
@@ -100,6 +100,7 @@
/** @hide */
public static final long TRACE_TAG_VIBRATOR = 1L << 23;
/** @hide */
+ @SystemApi(client = MODULE_LIBRARIES)
public static final long TRACE_TAG_AIDL = 1L << 24;
/** @hide */
public static final long TRACE_TAG_NNAPI = 1L << 25;
diff --git a/core/java/android/security/keymaster/ExportResult.java b/core/java/android/security/keymaster/ExportResult.java
index 2c382ef..c78fb1a 100644
--- a/core/java/android/security/keymaster/ExportResult.java
+++ b/core/java/android/security/keymaster/ExportResult.java
@@ -61,4 +61,4 @@
out.writeInt(resultCode);
out.writeByteArray(exportData);
}
-};
+}
diff --git a/core/java/android/text/style/AccessibilityURLSpan.java b/core/java/android/text/style/AccessibilityURLSpan.java
index bd81623..e280bdf 100644
--- a/core/java/android/text/style/AccessibilityURLSpan.java
+++ b/core/java/android/text/style/AccessibilityURLSpan.java
@@ -26,6 +26,7 @@
* It is used to replace URLSpans in {@link AccessibilityNodeInfo#setText(CharSequence)}
* @hide
*/
+@SuppressWarnings("ParcelableCreator")
public class AccessibilityURLSpan extends URLSpan implements Parcelable {
final AccessibilityClickableSpan mAccessibilityClickableSpan;
diff --git a/core/java/android/util/AndroidException.java b/core/java/android/util/AndroidException.java
index 1345ddf..d1b9d9f 100644
--- a/core/java/android/util/AndroidException.java
+++ b/core/java/android/util/AndroidException.java
@@ -40,5 +40,5 @@
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
-};
+}
diff --git a/core/java/android/util/AndroidRuntimeException.java b/core/java/android/util/AndroidRuntimeException.java
index 2b824bf..72c34d8b 100644
--- a/core/java/android/util/AndroidRuntimeException.java
+++ b/core/java/android/util/AndroidRuntimeException.java
@@ -34,5 +34,4 @@
public AndroidRuntimeException(Exception cause) {
super(cause);
}
-};
-
+}
diff --git a/core/java/android/util/OWNERS b/core/java/android/util/OWNERS
index d4cf6e6..3772006 100644
--- a/core/java/android/util/OWNERS
+++ b/core/java/android/util/OWNERS
@@ -1,6 +1,6 @@
per-file Dump* = file:/core/java/com/android/internal/util/dump/OWNERS
per-file FeatureFlagUtils.java = sbasi@google.com
-per-file FeatureFlagUtils.java = tmfang@google.com
+per-file FeatureFlagUtils.java = edgarwang@google.com
per-file AttributeSet.java = file:/core/java/android/content/res/OWNERS
per-file TypedValue.java = file:/core/java/android/content/res/OWNERS
diff --git a/core/java/android/util/Range.java b/core/java/android/util/Range.java
index 9fd0ab9..41c171a 100644
--- a/core/java/android/util/Range.java
+++ b/core/java/android/util/Range.java
@@ -356,4 +356,4 @@
private final T mLower;
private final T mUpper;
-};
+}
diff --git a/core/java/android/util/TypedValue.java b/core/java/android/util/TypedValue.java
index 19de396..44318bb 100644
--- a/core/java/android/util/TypedValue.java
+++ b/core/java/android/util/TypedValue.java
@@ -696,5 +696,5 @@
sb.append("}");
return sb.toString();
}
-};
+}
diff --git a/core/java/android/view/CutoutSpecification.java b/core/java/android/view/CutoutSpecification.java
index f8aa934..3fc3b6a 100644
--- a/core/java/android/view/CutoutSpecification.java
+++ b/core/java/android/view/CutoutSpecification.java
@@ -394,7 +394,6 @@
Log.e(TAG, "According to SVG definition, it shouldn't happen");
return;
}
- spec.trim();
translateMatrix();
final Path newPath = PathParser.createPathFromPathData(spec);
diff --git a/core/java/android/view/RemoteAnimationDefinition.java b/core/java/android/view/RemoteAnimationDefinition.java
index ea97995..ff282ba 100644
--- a/core/java/android/view/RemoteAnimationDefinition.java
+++ b/core/java/android/view/RemoteAnimationDefinition.java
@@ -19,6 +19,7 @@
import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
import android.annotation.Nullable;
+import android.annotation.NonNull;
import android.app.WindowConfiguration.ActivityType;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.IBinder;
@@ -157,7 +158,7 @@
}
}
- public static final @android.annotation.NonNull Creator<RemoteAnimationDefinition> CREATOR =
+ public static final @NonNull Creator<RemoteAnimationDefinition> CREATOR =
new Creator<RemoteAnimationDefinition>() {
public RemoteAnimationDefinition createFromParcel(Parcel in) {
return new RemoteAnimationDefinition(in);
@@ -199,18 +200,17 @@
return 0;
}
- private static final @android.annotation.NonNull Creator<RemoteAnimationAdapterEntry> CREATOR
- = new Creator<RemoteAnimationAdapterEntry>() {
+ public static final @NonNull Parcelable.Creator<RemoteAnimationAdapterEntry> CREATOR =
+ new Parcelable.Creator<RemoteAnimationAdapterEntry>() {
+ @Override
+ public RemoteAnimationAdapterEntry createFromParcel(Parcel in) {
+ return new RemoteAnimationAdapterEntry(in);
+ }
- @Override
- public RemoteAnimationAdapterEntry createFromParcel(Parcel in) {
- return new RemoteAnimationAdapterEntry(in);
- }
-
- @Override
- public RemoteAnimationAdapterEntry[] newArray(int size) {
- return new RemoteAnimationAdapterEntry[size];
- }
- };
+ @Override
+ public RemoteAnimationAdapterEntry[] newArray(int size) {
+ return new RemoteAnimationAdapterEntry[size];
+ }
+ };
}
}
diff --git a/core/java/android/webkit/ConsoleMessage.java b/core/java/android/webkit/ConsoleMessage.java
index 5474557..89cb6b2 100644
--- a/core/java/android/webkit/ConsoleMessage.java
+++ b/core/java/android/webkit/ConsoleMessage.java
@@ -68,4 +68,4 @@
public int lineNumber() {
return mLineNumber;
}
-};
+}
diff --git a/core/java/android/webkit/ValueCallback.java b/core/java/android/webkit/ValueCallback.java
index 5c7d97f..3d5bb49 100644
--- a/core/java/android/webkit/ValueCallback.java
+++ b/core/java/android/webkit/ValueCallback.java
@@ -25,4 +25,4 @@
* @param value The value.
*/
public void onReceiveValue(T value);
-};
+}
diff --git a/core/java/android/window/TransitionFilter.java b/core/java/android/window/TransitionFilter.java
index db15145..e62d5c9 100644
--- a/core/java/android/window/TransitionFilter.java
+++ b/core/java/android/window/TransitionFilter.java
@@ -296,7 +296,7 @@
out.append((i == 0 ? "" : ",") + TransitionInfo.modeToString(mModes[i]));
}
}
- out.append("]").toString();
+ out.append("]");
out.append(" flags=" + TransitionInfo.flagsToString(mFlags));
out.append(" mustBeTask=" + mMustBeTask);
out.append(" order=" + containerOrderToString(mOrder));
diff --git a/core/java/com/android/internal/app/procstats/AssociationState.java b/core/java/com/android/internal/app/procstats/AssociationState.java
index 97f4b0f..a21a842 100644
--- a/core/java/com/android/internal/app/procstats/AssociationState.java
+++ b/core/java/com/android/internal/app/procstats/AssociationState.java
@@ -59,6 +59,7 @@
/**
* The state of the source process of an association.
*/
+ @SuppressWarnings("ParcelableCreator")
public static final class SourceState implements Parcelable {
private @NonNull final ProcessStats mProcessStats;
private @Nullable final AssociationState mAssociationState;
diff --git a/core/java/com/android/internal/expresslog/OWNERS b/core/java/com/android/internal/expresslog/OWNERS
new file mode 100644
index 0000000..ee865b1
--- /dev/null
+++ b/core/java/com/android/internal/expresslog/OWNERS
@@ -0,0 +1 @@
+include /services/core/java/com/android/server/stats/OWNERS
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index e290812..1e0b3cc 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -3656,6 +3656,7 @@
public abstract T instantiateObject();
}
+ @SuppressWarnings("ParcelableCreator")
public static class ControllerActivityCounterImpl extends ControllerActivityCounter
implements Parcelable {
private final Clock mClock;
diff --git a/core/java/com/android/internal/os/BinderCallsStats.java b/core/java/com/android/internal/os/BinderCallsStats.java
index 0a29fc52..eb62cb0 100644
--- a/core/java/com/android/internal/os/BinderCallsStats.java
+++ b/core/java/com/android/internal/os/BinderCallsStats.java
@@ -735,7 +735,7 @@
}
protected boolean shouldRecordDetailedData() {
- return mRandom.nextInt() % mPeriodicSamplingInterval == 0;
+ return mRandom.nextInt(mPeriodicSamplingInterval) == 0;
}
/**
diff --git a/core/java/com/android/internal/os/BinderLatencyObserver.java b/core/java/com/android/internal/os/BinderLatencyObserver.java
index e9d55db..1276fb9 100644
--- a/core/java/com/android/internal/os/BinderLatencyObserver.java
+++ b/core/java/com/android/internal/os/BinderLatencyObserver.java
@@ -236,7 +236,7 @@
}
protected boolean shouldKeepSample() {
- return mRandom.nextInt() % mPeriodicSamplingInterval == 0;
+ return mRandom.nextInt(mPeriodicSamplingInterval) == 0;
}
/** Updates the sampling interval. */
diff --git a/core/java/com/android/internal/os/LooperStats.java b/core/java/com/android/internal/os/LooperStats.java
index 2805dcc..0645eb7 100644
--- a/core/java/com/android/internal/os/LooperStats.java
+++ b/core/java/com/android/internal/os/LooperStats.java
@@ -290,7 +290,7 @@
}
protected boolean shouldCollectDetailedData() {
- return ThreadLocalRandom.current().nextInt() % mSamplingInterval == 0;
+ return ThreadLocalRandom.current().nextInt(mSamplingInterval) == 0;
}
private static class DispatchSession {
diff --git a/core/java/com/android/internal/os/RuntimeInit.java b/core/java/com/android/internal/os/RuntimeInit.java
index 28b98d6..8a9445d 100644
--- a/core/java/com/android/internal/os/RuntimeInit.java
+++ b/core/java/com/android/internal/os/RuntimeInit.java
@@ -16,10 +16,14 @@
package com.android.internal.os;
+import static com.android.internal.os.SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL;
+
+import android.annotation.TestApi;
import android.app.ActivityManager;
import android.app.ActivityThread;
import android.app.ApplicationErrorReport;
import android.app.IActivityManager;
+import android.app.compat.CompatChanges;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.type.DefaultMimeMapFactory;
import android.net.TrafficStats;
@@ -36,6 +40,7 @@
import dalvik.system.RuntimeHooks;
import dalvik.system.VMRuntime;
+import dalvik.system.ZipPathValidator;
import libcore.content.type.MimeMap;
@@ -260,10 +265,31 @@
*/
TrafficStats.attachSocketTagger();
+ /*
+ * Initialize the zip path validator callback depending on the targetSdk.
+ */
+ initZipPathValidatorCallback();
+
initialized = true;
}
/**
+ * If targetSDK >= U: set the safe zip path validator callback which disallows dangerous zip
+ * entry names.
+ * Otherwise: clear the callback to the default validation.
+ *
+ * @hide
+ */
+ @TestApi
+ public static void initZipPathValidatorCallback() {
+ if (CompatChanges.isChangeEnabled(VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL)) {
+ ZipPathValidator.setCallback(new SafeZipPathValidatorCallback());
+ } else {
+ ZipPathValidator.clearCallback();
+ }
+ }
+
+ /**
* Returns an HTTP user agent of the form
* "Dalvik/1.1.0 (Linux; U; Android Eclair Build/MAIN)".
*/
diff --git a/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java b/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java
new file mode 100644
index 0000000..a6ee108
--- /dev/null
+++ b/core/java/com/android/internal/os/SafeZipPathValidatorCallback.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.os;
+
+import android.annotation.NonNull;
+import android.compat.annotation.ChangeId;
+import android.compat.annotation.EnabledSince;
+import android.os.Build;
+
+import dalvik.system.ZipPathValidator;
+
+import java.io.File;
+import java.util.zip.ZipException;
+
+/**
+ * A child implementation of the {@link dalvik.system.ZipPathValidator.Callback} that removes the
+ * risk of zip path traversal vulnerabilities.
+ *
+ * @hide
+ */
+public class SafeZipPathValidatorCallback implements ZipPathValidator.Callback {
+ /**
+ * This change targets zip path traversal vulnerabilities by throwing
+ * {@link java.util.zip.ZipException} if zip path entries contain ".." or start with "/".
+ * <p>
+ * The exception will be thrown in {@link java.util.zip.ZipInputStream#getNextEntry} or
+ * {@link java.util.zip.ZipFile#ZipFile(String)}.
+ * <p>
+ * This validation is enabled for apps with targetSDK >= U.
+ */
+ @ChangeId
+ @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+ public static final long VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL = 242716250L;
+
+ @Override
+ public void onZipEntryAccess(@NonNull String path) throws ZipException {
+ if (path.startsWith("/")) {
+ throw new ZipException("Invalid zip entry path: " + path);
+ }
+ if (path.contains("..")) {
+ // If the string does contain "..", break it down into its actual name elements to
+ // ensure it actually contains ".." as a name, not just a name like "foo..bar" or even
+ // "foo..", which should be fine.
+ File file = new File(path);
+ while (file != null) {
+ if (file.getName().equals("..")) {
+ throw new ZipException("Invalid zip entry path: " + path);
+ }
+ file = file.getParentFile();
+ }
+ }
+ }
+}
diff --git a/core/java/com/android/internal/util/LatencyTracker.java b/core/java/com/android/internal/util/LatencyTracker.java
index ca40a40..ab42f87 100644
--- a/core/java/com/android/internal/util/LatencyTracker.java
+++ b/core/java/com/android/internal/util/LatencyTracker.java
@@ -413,7 +413,7 @@
boolean shouldSample;
int traceThreshold;
synchronized (mLock) {
- shouldSample = ThreadLocalRandom.current().nextInt() % mSamplingInterval == 0;
+ shouldSample = ThreadLocalRandom.current().nextInt(mSamplingInterval) == 0;
traceThreshold = mTraceThresholdPerAction[action];
}
diff --git a/core/java/com/android/internal/view/BaseSurfaceHolder.java b/core/java/com/android/internal/view/BaseSurfaceHolder.java
index 32ce0fe..1ae1307 100644
--- a/core/java/com/android/internal/view/BaseSurfaceHolder.java
+++ b/core/java/com/android/internal/view/BaseSurfaceHolder.java
@@ -241,4 +241,4 @@
mSurfaceFrame.right = width;
mSurfaceFrame.bottom = height;
}
-};
+}
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index 6b73648..949f363 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -19,6 +19,7 @@
#define LOG_NDEBUG 1
#include <android-base/macros.h>
+#include <android-base/parsebool.h>
#include <android-base/properties.h>
#include <android/graphics/jni_runtime.h>
#include <android_runtime/AndroidRuntime.h>
@@ -52,6 +53,8 @@
using namespace android;
using android::base::GetBoolProperty;
using android::base::GetProperty;
+using android::base::ParseBool;
+using android::base::ParseBoolResult;
extern int register_android_os_Binder(JNIEnv* env);
extern int register_android_os_Process(JNIEnv* env);
@@ -701,17 +704,24 @@
// Read if we are using the profile configuration, do this at the start since the last ART args
// take precedence.
- property_get("dalvik.vm.profilebootclasspath", propBuf, "");
- std::string profile_boot_class_path_flag = propBuf;
- // Empty means the property is unset and we should default to the phenotype property.
- // The possible values are {"true", "false", ""}
- if (profile_boot_class_path_flag.empty()) {
- profile_boot_class_path_flag = server_configurable_flags::GetServerConfigurableFlag(
- RUNTIME_NATIVE_BOOT_NAMESPACE,
- PROFILE_BOOT_CLASS_PATH,
- /*default_value=*/ "");
+ std::string profile_boot_class_path_flag =
+ server_configurable_flags::GetServerConfigurableFlag(RUNTIME_NATIVE_BOOT_NAMESPACE,
+ PROFILE_BOOT_CLASS_PATH,
+ /*default_value=*/"");
+ bool profile_boot_class_path;
+ switch (ParseBool(profile_boot_class_path_flag)) {
+ case ParseBoolResult::kError:
+ // Default to the system property.
+ profile_boot_class_path =
+ GetBoolProperty("dalvik.vm.profilebootclasspath", /*default_value=*/false);
+ break;
+ case ParseBoolResult::kTrue:
+ profile_boot_class_path = true;
+ break;
+ case ParseBoolResult::kFalse:
+ profile_boot_class_path = false;
+ break;
}
- const bool profile_boot_class_path = (profile_boot_class_path_flag == "true");
if (profile_boot_class_path) {
addOption("-Xcompiler-option");
addOption("--count-hotness-in-compiled-code");
diff --git a/core/jni/OWNERS b/core/jni/OWNERS
index a068008..9f39c32 100644
--- a/core/jni/OWNERS
+++ b/core/jni/OWNERS
@@ -99,3 +99,5 @@
# PM
per-file com_android_internal_content_* = file:/PACKAGE_MANAGER_OWNERS
+# Stats/expresslog
+per-file *expresslog* = file:/services/core/java/com/android/server/stats/OWNERS
diff --git a/core/res/OWNERS b/core/res/OWNERS
index 22f40a1..6d05e07 100644
--- a/core/res/OWNERS
+++ b/core/res/OWNERS
@@ -1,5 +1,4 @@
adamp@google.com
-alanv@google.com
asc@google.com
cinek@google.com
dsandler@android.com
@@ -20,9 +19,6 @@
ogunwale@google.com
patb@google.com
shanh@google.com
-svetoslavganov@android.com
-svetoslavganov@google.com
-toddke@google.com
tsuji@google.com
yamasani@google.com
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 343bc1c..f244ce4 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -3573,6 +3573,12 @@
experience while the device is non-interactive. -->
<bool name="config_emergencyGestureEnabled">true</bool>
+ <!-- Default value for Use Emergency SOS in Settings false = disabled, true = enabled -->
+ <bool name="config_defaultEmergencyGestureEnabled">true</bool>
+
+ <!-- Default value for Use Play countdown alarm in Settings false = disabled, true = enabled -->
+ <bool name="config_defaultEmergencyGestureSoundEnabled">false</bool>
+
<!-- Allow the gesture power + volume up to change the ringer mode while the device
is interactive. -->
<bool name="config_volumeHushGestureEnabled">true</bool>
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 7736c1a..596d89a 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -2968,6 +2968,8 @@
<java-symbol type="integer" name="config_cameraLiftTriggerSensorType" />
<java-symbol type="string" name="config_cameraLiftTriggerSensorStringType" />
<java-symbol type="bool" name="config_emergencyGestureEnabled" />
+ <java-symbol type="bool" name="config_defaultEmergencyGestureEnabled" />
+ <java-symbol type="bool" name="config_defaultEmergencyGestureSoundEnabled" />
<java-symbol type="bool" name="config_volumeHushGestureEnabled" />
<java-symbol type="drawable" name="platlogo_m" />
diff --git a/core/tests/GameManagerTests/OWNERS b/core/tests/GameManagerTests/OWNERS
new file mode 100644
index 0000000..0992440
--- /dev/null
+++ b/core/tests/GameManagerTests/OWNERS
@@ -0,0 +1 @@
+include /GAME_MANAGER_OWNERS
\ No newline at end of file
diff --git a/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java b/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java
index 1cf4302..372bca4 100644
--- a/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java
+++ b/core/tests/benchmarks/src/android/os/ParcelableBenchmark.java
@@ -88,6 +88,7 @@
}
}
+ @SuppressWarnings("ParcelableCreator")
@SuppressLint("ParcelCreator")
private static class PointArray implements Parcelable {
Rect mBounds = new Rect();
diff --git a/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java b/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java
new file mode 100644
index 0000000..282fdad
--- /dev/null
+++ b/core/tests/coretests/src/android/app/AutomaticZenRuleTest.java
@@ -0,0 +1,153 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.app;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.fail;
+
+import android.content.ComponentName;
+import android.net.Uri;
+import android.os.Parcel;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import com.google.common.base.Strings;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.lang.reflect.Field;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class AutomaticZenRuleTest {
+ private static final String CLASS = "android.app.AutomaticZenRule";
+
+ @Test
+ public void testLongFields_inConstructor() {
+ String longString = Strings.repeat("A", 65536);
+ Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530));
+
+ // test both variants where there's an owner, and where there's a configuration activity
+ AutomaticZenRule rule1 = new AutomaticZenRule(
+ longString, // name
+ new ComponentName("pkg", longString), // owner
+ null, // configuration activity
+ longUri, // conditionId
+ null, // zen policy
+ 0, // interruption filter
+ true); // enabled
+
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule1.getName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule1.getConditionId().toString().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule1.getOwner().getClassName().length());
+
+ AutomaticZenRule rule2 = new AutomaticZenRule(
+ longString, // name
+ null, // owner
+ new ComponentName(longString, "SomeClassName"), // configuration activity
+ longUri, // conditionId
+ null, // zen policy
+ 0, // interruption filter
+ false); // enabled
+
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule2.getName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule2.getConditionId().toString().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule2.getConfigurationActivity().getPackageName().length());
+ }
+
+ @Test
+ public void testLongFields_inSetters() {
+ String longString = Strings.repeat("A", 65536);
+ Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530));
+
+ AutomaticZenRule rule = new AutomaticZenRule(
+ "sensible name",
+ new ComponentName("pkg", "ShortClass"),
+ null,
+ Uri.parse("uri://short"),
+ null, 0, true);
+
+ rule.setName(longString);
+ rule.setConditionId(longUri);
+ rule.setConfigurationActivity(new ComponentName(longString, longString));
+
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, rule.getName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule.getConditionId().toString().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule.getConfigurationActivity().getPackageName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ rule.getConfigurationActivity().getClassName().length());
+ }
+
+ @Test
+ public void testLongInputsFromParcel() {
+ // Create a rule with long fields, set directly via reflection so that we can confirm that
+ // a rule with too-long fields that comes in via a parcel has its fields truncated directly.
+ AutomaticZenRule rule = new AutomaticZenRule(
+ "placeholder",
+ new ComponentName("place", "holder"),
+ null,
+ Uri.parse("uri://placeholder"),
+ null, 0, true);
+
+ try {
+ String longString = Strings.repeat("A", 65536);
+ Uri longUri = Uri.parse("uri://" + Strings.repeat("A", 65530));
+ Field name = Class.forName(CLASS).getDeclaredField("name");
+ name.setAccessible(true);
+ name.set(rule, longString);
+ Field conditionId = Class.forName(CLASS).getDeclaredField("conditionId");
+ conditionId.setAccessible(true);
+ conditionId.set(rule, longUri);
+ Field owner = Class.forName(CLASS).getDeclaredField("owner");
+ owner.setAccessible(true);
+ owner.set(rule, new ComponentName(longString, longString));
+ Field configActivity = Class.forName(CLASS).getDeclaredField("configurationActivity");
+ configActivity.setAccessible(true);
+ configActivity.set(rule, new ComponentName(longString, longString));
+ } catch (NoSuchFieldException e) {
+ fail(e.toString());
+ } catch (ClassNotFoundException e) {
+ fail(e.toString());
+ } catch (IllegalAccessException e) {
+ fail(e.toString());
+ }
+
+ Parcel parcel = Parcel.obtain();
+ rule.writeToParcel(parcel, 0);
+ parcel.setDataPosition(0);
+
+ AutomaticZenRule fromParcel = new AutomaticZenRule(parcel);
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH, fromParcel.getName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ fromParcel.getConditionId().toString().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ fromParcel.getConfigurationActivity().getPackageName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ fromParcel.getConfigurationActivity().getClassName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ fromParcel.getOwner().getPackageName().length());
+ assertEquals(AutomaticZenRule.MAX_STRING_LENGTH,
+ fromParcel.getOwner().getClassName().length());
+ }
+}
diff --git a/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java b/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java
index d505492..86e95832 100644
--- a/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java
+++ b/core/tests/coretests/src/android/content/pm/PackageManagerPropertyTests.java
@@ -20,6 +20,7 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import android.content.pm.PackageManager.Property;
@@ -162,40 +163,30 @@
@Test
public void testProperty_invalidName() throws Exception {
- try {
+ assertThrows(NullPointerException.class, () -> {
final Property p = new Property(null, 1, "android", null);
- fail("expected assertion error");
- } catch (AssertionError expected) {
- }
+ });
}
@Test
public void testProperty_invalidType() throws Exception {
- try {
+ assertThrows(IllegalArgumentException.class, () -> {
final Property p = new Property("invalidTypeProperty", 0, "android", null);
- fail("expected assertion error");
- } catch (AssertionError expected) {
- }
+ });
- try {
+ assertThrows(IllegalArgumentException.class, () -> {
final Property p = new Property("invalidTypeProperty", 6, "android", null);
- fail("expected assertion error");
- } catch (AssertionError expected) {
- }
+ });
- try {
+ assertThrows(IllegalArgumentException.class, () -> {
final Property p = new Property("invalidTypeProperty", -1, "android", null);
- fail("expected assertion error");
- } catch (AssertionError expected) {
- }
+ });
}
@Test
public void testProperty_noPackageName() throws Exception {
- try {
+ assertThrows(NullPointerException.class, () -> {
final Property p = new Property(null, 1, null, null);
- fail("expected assertion error");
- } catch (AssertionError expected) {
- }
+ });
}
}
diff --git a/core/tests/coretests/src/android/os/BundleTest.java b/core/tests/coretests/src/android/os/BundleTest.java
index a3bda8b..0fa5ec3 100644
--- a/core/tests/coretests/src/android/os/BundleTest.java
+++ b/core/tests/coretests/src/android/os/BundleTest.java
@@ -409,6 +409,69 @@
}
@Test
+ public void readFromParcel_withLazyValues_copiesUnderlyingParcel() {
+ Bundle bundle = new Bundle();
+ Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
+ bundle.putParcelable("key", parcelable);
+ bundle.putString("string", "value");
+ Parcel parcelledBundle = getParcelledBundle(bundle);
+
+ Bundle testBundle = new Bundle();
+ testBundle.setClassLoader(getClass().getClassLoader());
+ testBundle.readFromParcel(parcelledBundle);
+ // Recycle the parcel as it should have been copied
+ parcelledBundle.recycle();
+ assertThat(testBundle.getString("string")).isEqualTo("value");
+ assertThat(testBundle.<Parcelable>getParcelable("key")).isEqualTo(parcelable);
+ }
+
+ @Test
+ public void readFromParcelWithRwHelper_whenThrowingAndNotDefusing_throws() {
+ Bundle bundle = new Bundle();
+ Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
+ bundle.putParcelable("key", parcelable);
+ bundle.putString("string", "value");
+ Parcel parcelledBundle = getParcelledBundle(bundle);
+ parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());
+
+ Bundle testBundle = new Bundle();
+ assertThrows(BadParcelableException.class,
+ () -> testBundle.readFromParcel(parcelledBundle));
+ }
+
+ @Test
+ public void readFromParcelWithRwHelper_whenThrowingAndDefusing_returnsNull() {
+ Bundle bundle = new Bundle();
+ Parcelable parcelable = new CustomParcelable(13, "Tiramisu");
+ bundle.putParcelable("key", parcelable);
+ bundle.putString("string", "value");
+ Parcel parcelledBundle = getParcelledBundle(bundle);
+ parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());
+
+ Bundle.setShouldDefuse(true);
+ Bundle testBundle = new Bundle();
+ testBundle.readFromParcel(parcelledBundle);
+ // Recycle the parcel as it should not be referenced
+ parcelledBundle.recycle();
+ assertThat(testBundle.getString("string")).isNull();
+ assertThat(testBundle.<Parcelable>getParcelable("key")).isNull();
+ }
+
+ @Test
+ public void readFromParcelWithRwHelper_withoutLazyObject_returnsValue() {
+ Bundle bundle = new Bundle();
+ bundle.putString("string", "value");
+ Parcel parcelledBundle = getParcelledBundle(bundle);
+ parcelledBundle.setReadWriteHelper(new Parcel.ReadWriteHelper());
+
+ Bundle testBundle = new Bundle();
+ testBundle.readFromParcel(parcelledBundle);
+ // Recycle the parcel as it should not be referenced
+ parcelledBundle.recycle();
+ assertThat(testBundle.getString("string")).isEqualTo("value");
+ }
+
+ @Test
public void partialDeserialization_whenNotDefusing_throws() throws Exception {
Bundle.setShouldDefuse(false);
Bundle bundle = getMalformedBundle();
diff --git a/core/tests/coretests/src/android/text/format/DateFormatTest.java b/core/tests/coretests/src/android/text/format/DateFormatTest.java
index 212cc44..8459330 100644
--- a/core/tests/coretests/src/android/text/format/DateFormatTest.java
+++ b/core/tests/coretests/src/android/text/format/DateFormatTest.java
@@ -156,8 +156,8 @@
@DisableCompatChanges({DateFormat.DISALLOW_DUPLICATE_FIELD_IN_SKELETON})
public void testGetBestDateTimePattern_enableDuplicateField() {
// en-US uses 12-hour format by default.
- assertEquals("h:mm a", DateFormat.getBestDateTimePattern(Locale.US, "jmma"));
- assertEquals("h:mm a", DateFormat.getBestDateTimePattern(Locale.US, "ahmma"));
+ assertEquals("h:mm\u202fa", DateFormat.getBestDateTimePattern(Locale.US, "jmma"));
+ assertEquals("h:mm\u202fa", DateFormat.getBestDateTimePattern(Locale.US, "ahmma"));
}
private static void assertIllegalArgumentException(Locale l, String skeleton) {
diff --git a/core/tests/coretests/src/android/text/format/DateIntervalFormatTest.java b/core/tests/coretests/src/android/text/format/DateIntervalFormatTest.java
index 9c06395..de7244d 100644
--- a/core/tests/coretests/src/android/text/format/DateIntervalFormatTest.java
+++ b/core/tests/coretests/src/android/text/format/DateIntervalFormatTest.java
@@ -93,7 +93,8 @@
assertEquals("January 19",
formatDateRange(en_US, tz, timeWithCurrentYear, timeWithCurrentYear + HOUR,
FORMAT_SHOW_DATE));
- assertEquals("3:30 AM", formatDateRange(en_US, tz, fixedTime, fixedTime, FORMAT_SHOW_TIME));
+ assertEquals("3:30\u202fAM", formatDateRange(en_US, tz, fixedTime, fixedTime,
+ FORMAT_SHOW_TIME));
assertEquals("January 19, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + HOUR, FORMAT_SHOW_YEAR));
assertEquals("January 19",
@@ -101,27 +102,27 @@
assertEquals("January",
formatDateRange(en_US, tz, timeWithCurrentYear, timeWithCurrentYear + HOUR,
FORMAT_NO_MONTH_DAY));
- assertEquals("3:30 AM",
+ assertEquals("3:30\u202fAM",
formatDateRange(en_US, tz, fixedTime, fixedTime, FORMAT_12HOUR | FORMAT_SHOW_TIME));
assertEquals("03:30",
formatDateRange(en_US, tz, fixedTime, fixedTime, FORMAT_24HOUR | FORMAT_SHOW_TIME));
- assertEquals("3:30 AM", formatDateRange(en_US, tz, fixedTime, fixedTime,
+ assertEquals("3:30\u202fAM", formatDateRange(en_US, tz, fixedTime, fixedTime,
FORMAT_12HOUR /*| FORMAT_CAP_AMPM*/ | FORMAT_SHOW_TIME));
- assertEquals("12:00 PM",
+ assertEquals("12:00\u202fPM",
formatDateRange(en_US, tz, fixedTime + noonDuration, fixedTime + noonDuration,
FORMAT_12HOUR | FORMAT_SHOW_TIME));
- assertEquals("12:00 PM",
+ assertEquals("12:00\u202fPM",
formatDateRange(en_US, tz, fixedTime + noonDuration, fixedTime + noonDuration,
FORMAT_12HOUR | FORMAT_SHOW_TIME /*| FORMAT_CAP_NOON*/));
- assertEquals("12:00 PM",
+ assertEquals("12:00\u202fPM",
formatDateRange(en_US, tz, fixedTime + noonDuration, fixedTime + noonDuration,
FORMAT_12HOUR /*| FORMAT_NO_NOON*/ | FORMAT_SHOW_TIME));
- assertEquals("12:00 AM", formatDateRange(en_US, tz, fixedTime - midnightDuration,
+ assertEquals("12:00\u202fAM", formatDateRange(en_US, tz, fixedTime - midnightDuration,
fixedTime - midnightDuration,
FORMAT_12HOUR | FORMAT_SHOW_TIME /*| FORMAT_NO_MIDNIGHT*/));
- assertEquals("3:30 AM",
+ assertEquals("3:30\u202fAM",
formatDateRange(en_US, tz, fixedTime, fixedTime, FORMAT_SHOW_TIME | FORMAT_UTC));
- assertEquals("3 AM", formatDateRange(en_US, tz, onTheHour, onTheHour,
+ assertEquals("3\u202fAM", formatDateRange(en_US, tz, onTheHour, onTheHour,
FORMAT_SHOW_TIME | FORMAT_ABBREV_TIME));
assertEquals("Mon", formatDateRange(en_US, tz, fixedTime, fixedTime + HOUR,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_WEEKDAY));
@@ -134,13 +135,13 @@
assertEquals("1/19/2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * HOUR,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("1/19/2009 – 1/22/2009",
+ assertEquals("1/19/2009\u2009\u2013\u20091/22/2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("1/19/2009 – 4/22/2009",
+ assertEquals("1/19/2009\u2009\u2013\u20094/22/2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("1/19/2009 – 2/9/2012",
+ assertEquals("1/19/2009\u2009\u2013\u20092/9/2012",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
@@ -151,7 +152,7 @@
assertEquals("19.01. – 22.04.2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19.01.2009 – 09.02.2012",
+ assertEquals("19.01.2009\u2009\u2013\u200909.02.2012",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
@@ -169,48 +170,48 @@
assertEquals("19/1/2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + HOUR,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/1/2009",
+ assertEquals("19/1/2009\u2009\u2013\u200922/1/2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 22/4/2009",
+ assertEquals("19/1/2009\u2009\u2013\u200922/4/2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
- assertEquals("19/1/2009 – 9/2/2012",
+ assertEquals("19/1/2009\u2009\u2013\u20099/2/2012",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE));
// These are some random other test cases I came up with.
- assertEquals("January 19 – 22, 2009",
+ assertEquals("January 19\u2009\u2013\u200922, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, 0));
- assertEquals("Jan 19 – 22, 2009", formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY,
- FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("Mon, Jan 19 – Thu, Jan 22, 2009",
+ assertEquals("Jan 19\u2009\u2013\u200922, 2009", formatDateRange(en_US, tz, fixedTime,
+ fixedTime + 3 * DAY, FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
+ assertEquals("Mon, Jan 19\u2009\u2013\u2009Thu, Jan 22, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("Monday, January 19 – Thursday, January 22, 2009",
+ assertEquals("Monday, January 19\u2009\u2013\u2009Thursday, January 22, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
- assertEquals("January 19 – April 22, 2009",
+ assertEquals("January 19\u2009\u2013\u2009April 22, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("Jan 19 – Apr 22, 2009",
+ assertEquals("Jan 19\u2009\u2013\u2009Apr 22, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("Mon, Jan 19 – Wed, Apr 22, 2009",
+ assertEquals("Mon, Jan 19\u2009\u2013\u2009Wed, Apr 22, 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("January – April 2009",
+ assertEquals("January\u2009\u2013\u2009April 2009",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
- assertEquals("Jan 19, 2009 – Feb 9, 2012",
+ assertEquals("Jan 19, 2009\u2009\u2013\u2009Feb 9, 2012",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("Jan 2009 – Feb 2012",
+ assertEquals("Jan 2009\u2009\u2013\u2009Feb 2012",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("January 19, 2009 – February 9, 2012",
+ assertEquals("January 19, 2009\u2009\u2013\u2009February 9, 2012",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("Monday, January 19, 2009 – Thursday, February 9, 2012",
+ assertEquals("Monday, January 19, 2009\u2009\u2013\u2009Thursday, February 9, 2012",
formatDateRange(en_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
// The same tests but for de_DE.
@@ -225,26 +226,26 @@
assertEquals("Montag, 19. – Donnerstag, 22. Januar 2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
- assertEquals("19. Januar – 22. April 2009",
+ assertEquals("19. Januar\u2009\u2013\u200922. April 2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("19. Jan. – 22. Apr. 2009",
+ assertEquals("19. Jan.\u2009\u2013\u200922. Apr. 2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("Mo., 19. Jan. – Mi., 22. Apr. 2009",
+ assertEquals("Mo., 19. Jan.\u2009\u2013\u2009Mi., 22. Apr. 2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
assertEquals("Januar–April 2009",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
- assertEquals("19. Jan. 2009 – 9. Feb. 2012",
+ assertEquals("19. Jan. 2009\u2009\u2013\u20099. Feb. 2012",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("Jan. 2009 – Feb. 2012",
+ assertEquals("Jan. 2009\u2009\u2013\u2009Feb. 2012",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("19. Januar 2009 – 9. Februar 2012",
+ assertEquals("19. Januar 2009\u2009\u2013\u20099. Februar 2012",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("Montag, 19. Januar 2009 – Donnerstag, 9. Februar 2012",
+ assertEquals("Montag, 19. Januar 2009\u2009\u2013\u2009Donnerstag, 9. Februar 2012",
formatDateRange(de_DE, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
// The same tests but for es_US.
@@ -254,32 +255,32 @@
assertEquals("19–22 de ene de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun, 19 de ene – jue, 22 de ene de 2009",
+ assertEquals("lun, 19 de ene\u2009\u2013\u2009jue, 22 de ene de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("lunes, 19 de enero – jueves, 22 de enero de 2009",
+ assertEquals("lunes, 19 de enero\u2009\u2013\u2009jueves, 22 de enero de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
- assertEquals("19 de enero – 22 de abril de 2009",
+ assertEquals("19 de enero\u2009\u2013\u200922 de abril de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("19 de ene – 22 de abr 2009",
+ assertEquals("19 de ene\u2009\u2013\u200922 de abr 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun, 19 de ene – mié, 22 de abr de 2009",
+ assertEquals("lun, 19 de ene\u2009\u2013\u2009mié, 22 de abr de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
assertEquals("enero–abril de 2009",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
- assertEquals("19 de ene de 2009 – 9 de feb de 2012",
+ assertEquals("19 de ene de 2009\u2009\u2013\u20099 de feb de 2012",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("ene de 2009 – feb de 2012",
+ assertEquals("ene de 2009\u2009\u2013\u2009feb de 2012",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("19 de enero de 2009 – 9 de febrero de 2012",
+ assertEquals("19 de enero de 2009\u2009\u2013\u20099 de febrero de 2012",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("lunes, 19 de enero de 2009 – jueves, 9 de febrero de 2012",
+ assertEquals("lunes, 19 de enero de 2009\u2009\u2013\u2009jueves, 9 de febrero de 2012",
formatDateRange(es_US, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
// The same tests but for es_ES.
@@ -288,32 +289,32 @@
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, 0));
assertEquals("19–22 ene 2009", formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun, 19 ene – jue, 22 ene 2009",
+ assertEquals("lun, 19 ene\u2009\u2013\u2009jue, 22 ene 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
- assertEquals("lunes, 19 de enero – jueves, 22 de enero de 2009",
+ assertEquals("lunes, 19 de enero\u2009\u2013\u2009jueves, 22 de enero de 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * DAY, FORMAT_SHOW_WEEKDAY));
- assertEquals("19 de enero – 22 de abril de 2009",
+ assertEquals("19 de enero\u2009\u2013\u200922 de abril de 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, 0));
- assertEquals("19 ene – 22 abr 2009",
+ assertEquals("19 ene\u2009\u2013\u200922 abr 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("lun, 19 ene – mié, 22 abr 2009",
+ assertEquals("lun, 19 ene\u2009\u2013\u2009mié, 22 abr 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH,
FORMAT_SHOW_WEEKDAY | FORMAT_ABBREV_ALL));
assertEquals("enero–abril de 2009",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * MONTH, FORMAT_NO_MONTH_DAY));
- assertEquals("19 ene 2009 – 9 feb 2012",
+ assertEquals("19 ene 2009\u2009\u2013\u20099 feb 2012",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL));
- assertEquals("ene 2009 – feb 2012",
+ assertEquals("ene 2009\u2009\u2013\u2009feb 2012",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR,
FORMAT_NO_MONTH_DAY | FORMAT_ABBREV_ALL));
- assertEquals("19 de enero de 2009 – 9 de febrero de 2012",
+ assertEquals("19 de enero de 2009\u2009\u2013\u20099 de febrero de 2012",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, 0));
- assertEquals("lunes, 19 de enero de 2009 – jueves, 9 de febrero de 2012",
+ assertEquals("lunes, 19 de enero de 2009\u2009\u2013\u2009jueves, 9 de febrero de 2012",
formatDateRange(es_ES, tz, fixedTime, fixedTime + 3 * YEAR, FORMAT_SHOW_WEEKDAY));
}
@@ -330,7 +331,7 @@
c.set(2046, Calendar.OCTOBER, 4, 3, 30);
long oct_4_2046 = c.getTimeInMillis();
int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL;
- assertEquals("Jan 19, 2042 – Oct 4, 2046",
+ assertEquals("Jan 19, 2042\u2009\u2013\u2009Oct 4, 2046",
formatDateRange(l, tz, jan_19_2042, oct_4_2046, flags));
}
@@ -343,15 +344,15 @@
int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_ALL | FORMAT_SHOW_TIME | FORMAT_24HOUR;
// The Unix epoch is UTC, so 0 is 1970-01-01T00:00Z...
- assertEquals("Jan 1, 1970, 00:00 – Jan 2, 1970, 00:00",
+ assertEquals("Jan 1, 1970, 00:00\u2009\u2013\u2009Jan 2, 1970, 00:00",
formatDateRange(l, utc, 0, DAY + 1, flags));
// But MTV is hours behind, so 0 was still the afternoon of the previous day...
- assertEquals("Dec 31, 1969, 16:00 – Jan 1, 1970, 16:00",
+ assertEquals("Dec 31, 1969, 16:00\u2009\u2013\u2009Jan 1, 1970, 16:00",
formatDateRange(l, pacific, 0, DAY, flags));
}
// http://b/10318326 - we can drop the minutes in a 12-hour time if they're zero,
- // but not if we're using the 24-hour clock. That is: "4 PM" is reasonable, "16" is not.
+ // but not if we're using the 24-hour clock. That is: "4\u202fPM" is reasonable, "16" is not.
@Test
public void test10318326() throws Exception {
long midnight = 0;
@@ -367,23 +368,26 @@
// Full length on-the-hour times.
assertEquals("00:00", formatDateRange(l, utc, midnight, midnight, time24));
- assertEquals("12:00 AM", formatDateRange(l, utc, midnight, midnight, time12));
+ assertEquals("12:00\u202fAM", formatDateRange(l, utc, midnight, midnight, time12));
assertEquals("16:00", formatDateRange(l, utc, teaTime, teaTime, time24));
- assertEquals("4:00 PM", formatDateRange(l, utc, teaTime, teaTime, time12));
+ assertEquals("4:00\u202fPM", formatDateRange(l, utc, teaTime, teaTime, time12));
// Abbreviated on-the-hour times.
assertEquals("00:00", formatDateRange(l, utc, midnight, midnight, abbr24));
- assertEquals("12 AM", formatDateRange(l, utc, midnight, midnight, abbr12));
+ assertEquals("12\u202fAM", formatDateRange(l, utc, midnight, midnight, abbr12));
assertEquals("16:00", formatDateRange(l, utc, teaTime, teaTime, abbr24));
- assertEquals("4 PM", formatDateRange(l, utc, teaTime, teaTime, abbr12));
+ assertEquals("4\u202fPM", formatDateRange(l, utc, teaTime, teaTime, abbr12));
// Abbreviated on-the-hour ranges.
- assertEquals("00:00 – 16:00", formatDateRange(l, utc, midnight, teaTime, abbr24));
- assertEquals("12 AM – 4 PM", formatDateRange(l, utc, midnight, teaTime, abbr12));
+ assertEquals("00:00\u2009\u2013\u200916:00", formatDateRange(l, utc, midnight, teaTime,
+ abbr24));
+ assertEquals("12\u202fAM\u2009\u2013\u20094\u202fPM", formatDateRange(l, utc, midnight,
+ teaTime, abbr12));
// Abbreviated mixed ranges.
- assertEquals("00:00 – 16:01", formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr24));
- assertEquals("12:00 AM – 4:01 PM",
+ assertEquals("00:00\u2009\u2013\u200916:01", formatDateRange(l, utc, midnight,
+ teaTime + MINUTE, abbr24));
+ assertEquals("12:00\u202fAM\u2009\u2013\u20094:01\u202fPM",
formatDateRange(l, utc, midnight, teaTime + MINUTE, abbr12));
}
@@ -406,12 +410,12 @@
// Run one millisecond over, though, and you're into the next day.
long nextMorning = 1 * DAY + 1;
- assertEquals("Thursday, January 1 – Friday, January 2, 1970",
+ assertEquals("Thursday, January 1\u2009\u2013\u2009Friday, January 2, 1970",
formatDateRange(l, utc, midnight, nextMorning, flags));
// But the same reasoning applies for that day.
long nextMidnight = 2 * DAY;
- assertEquals("Thursday, January 1 – Friday, January 2, 1970",
+ assertEquals("Thursday, January 1\u2009\u2013\u2009Friday, January 2, 1970",
formatDateRange(l, utc, midnight, nextMidnight, flags));
}
@@ -424,9 +428,9 @@
int flags = FORMAT_SHOW_TIME | FORMAT_24HOUR | FORMAT_SHOW_DATE;
- assertEquals("January 1, 1970, 22:00 – 00:00",
+ assertEquals("January 1, 1970, 22:00\u2009\u2013\u200900:00",
formatDateRange(l, utc, 22 * HOUR, 24 * HOUR, flags));
- assertEquals("January 1, 1970 at 22:00 – January 2, 1970 at 00:30",
+ assertEquals("January 1, 1970 at 22:00\u2009\u2013\u2009January 2, 1970 at 00:30",
formatDateRange(l, utc, 22 * HOUR, 24 * HOUR + 30 * MINUTE, flags));
}
@@ -443,9 +447,9 @@
c.clear();
c.set(1980, Calendar.JANUARY, 1, 0, 0);
long jan_1_1980 = c.getTimeInMillis();
- assertEquals("January 1, 1980, 22:00 – 00:00",
+ assertEquals("January 1, 1980, 22:00\u2009\u2013\u200900:00",
formatDateRange(l, utc, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags));
- assertEquals("January 1, 1980 at 22:00 – January 2, 1980 at 00:30",
+ assertEquals("January 1, 1980 at 22:00\u2009\u2013\u2009January 2, 1980 at 00:30",
formatDateRange(l, utc, jan_1_1980 + 22 * HOUR,
jan_1_1980 + 24 * HOUR + 30 * MINUTE, flags));
}
@@ -463,12 +467,12 @@
c.clear();
c.set(1980, Calendar.JANUARY, 1, 0, 0);
long jan_1_1980 = c.getTimeInMillis();
- assertEquals("January 1, 1980, 22:00 – 00:00",
+ assertEquals("January 1, 1980, 22:00\u2009\u2013\u200900:00",
formatDateRange(l, pacific, jan_1_1980 + 22 * HOUR, jan_1_1980 + 24 * HOUR, flags));
c.set(1980, Calendar.JULY, 1, 0, 0);
long jul_1_1980 = c.getTimeInMillis();
- assertEquals("July 1, 1980, 22:00 – 00:00",
+ assertEquals("July 1, 1980, 22:00\u2009\u2013\u200900:00",
formatDateRange(l, pacific, jul_1_1980 + 22 * HOUR, jul_1_1980 + 24 * HOUR, flags));
}
@@ -531,11 +535,13 @@
formatDateRange(l, utc, oldYear, oldYear, FORMAT_SHOW_DATE | FORMAT_NO_YEAR));
// ...or the start and end years aren't the same...
- assertEquals(String.format("February 10, 1980 – February 10, %d", c.get(Calendar.YEAR)),
+ assertEquals(String.format("February 10, 1980\u2009\u2013\u2009February 10, %d",
+ c.get(Calendar.YEAR)),
formatDateRange(l, utc, oldYear, thisYear, FORMAT_SHOW_DATE));
// (And you can't avoid that --- icu4c steps in and overrides you.)
- assertEquals(String.format("February 10, 1980 – February 10, %d", c.get(Calendar.YEAR)),
+ assertEquals(String.format("February 10, 1980\u2009\u2013\u2009February 10, %d",
+ c.get(Calendar.YEAR)),
formatDateRange(l, utc, oldYear, thisYear, FORMAT_SHOW_DATE | FORMAT_NO_YEAR));
}
@@ -595,7 +601,7 @@
formatDateRange(new ULocale("fa"), utc, thisYear, thisYear, flags));
assertEquals("يونۍ د ۱۹۸۰ د فبروري ۱۰",
formatDateRange(new ULocale("ps"), utc, thisYear, thisYear, flags));
- assertEquals("วันอาทิตย์ที่ 10 กุมภาพันธ์ ค.ศ. 1980",
+ assertEquals("วันอาทิตย์ที่ 10 กุมภาพันธ์ 1980",
formatDateRange(new ULocale("th"), utc, thisYear, thisYear, flags));
}
@@ -607,9 +613,12 @@
int flags = FORMAT_SHOW_TIME | FORMAT_ABBREV_ALL | FORMAT_12HOUR;
- assertEquals("10 – 11 AM", formatDateRange(l, utc, 10 * HOUR, 11 * HOUR, flags));
- assertEquals("11 AM – 1 PM", formatDateRange(l, utc, 11 * HOUR, 13 * HOUR, flags));
- assertEquals("2 – 3 PM", formatDateRange(l, utc, 14 * HOUR, 15 * HOUR, flags));
+ assertEquals("10\u2009\u2013\u200911\u202fAM", formatDateRange(l, utc,
+ 10 * HOUR, 11 * HOUR, flags));
+ assertEquals("11\u202fAM\u2009\u2013\u20091\u202fPM", formatDateRange(l, utc,
+ 11 * HOUR, 13 * HOUR, flags));
+ assertEquals("2\u2009\u2013\u20093\u202fPM", formatDateRange(l, utc,
+ 14 * HOUR, 15 * HOUR, flags));
}
// http://b/20708022
@@ -618,8 +627,8 @@
final ULocale locale = new ULocale("en");
final TimeZone timeZone = TimeZone.getTimeZone("UTC");
- assertEquals("11:00 PM – 12:00 AM", formatDateRange(locale, timeZone,
- 1430434800000L, 1430438400000L, FORMAT_SHOW_TIME));
+ assertEquals("11:00\u202fPM\u2009\u2013\u200912:00\u202fAM", formatDateRange(locale,
+ timeZone, 1430434800000L, 1430438400000L, FORMAT_SHOW_TIME));
}
// http://b/68847519
@@ -629,23 +638,25 @@
ENGLISH, GMT_ZONE, from, to, FORMAT_SHOW_DATE | FORMAT_SHOW_TIME | FORMAT_24HOUR);
// If we're showing times and the end-point is midnight the following day, we want the
// behaviour of suppressing the date for the end...
- assertEquals("February 27, 2007, 04:00 – 00:00", fmt.apply(1172548800000L, 1172620800000L));
+ assertEquals("February 27, 2007, 04:00\u2009\u2013\u200900:00", fmt.apply(1172548800000L,
+ 1172620800000L));
// ...unless the start-point is also midnight, in which case we need dates to disambiguate.
- assertEquals("February 27, 2007 at 00:00 – February 28, 2007 at 00:00",
+ assertEquals("February 27, 2007 at 00:00\u2009\u2013\u2009February 28, 2007 at 00:00",
fmt.apply(1172534400000L, 1172620800000L));
// We want to show the date if the end-point is a millisecond after midnight the following
// day, or if it is exactly midnight the day after that.
- assertEquals("February 27, 2007 at 04:00 – February 28, 2007 at 00:00",
+ assertEquals("February 27, 2007 at 04:00\u2009\u2013\u2009February 28, 2007 at 00:00",
fmt.apply(1172548800000L, 1172620800001L));
- assertEquals("February 27, 2007 at 04:00 – March 1, 2007 at 00:00",
+ assertEquals("February 27, 2007 at 04:00\u2009\u2013\u2009March 1, 2007 at 00:00",
fmt.apply(1172548800000L, 1172707200000L));
// We want to show the date if the start-point is anything less than a minute after
// midnight,
// since that gets displayed as midnight...
- assertEquals("February 27, 2007 at 00:00 – February 28, 2007 at 00:00",
+ assertEquals("February 27, 2007 at 00:00\u2009\u2013\u2009February 28, 2007 at 00:00",
fmt.apply(1172534459999L, 1172620800000L));
// ...but not if it is exactly one minute after midnight.
- assertEquals("February 27, 2007, 00:01 – 00:00", fmt.apply(1172534460000L, 1172620800000L));
+ assertEquals("February 27, 2007, 00:01\u2009\u2013\u200900:00", fmt.apply(1172534460000L,
+ 1172620800000L));
}
// http://b/68847519
@@ -656,16 +667,20 @@
// If we're only showing dates and the end-point is midnight of any day, we want the
// behaviour of showing an end date one earlier. So if the end-point is March 2, 2007 00:00,
// show March 1, 2007 instead (whether the start-point is midnight or not).
- assertEquals("February 27 – March 1, 2007", fmt.apply(1172534400000L, 1172793600000L));
- assertEquals("February 27 – March 1, 2007", fmt.apply(1172548800000L, 1172793600000L));
+ assertEquals("February 27\u2009\u2013\u2009March 1, 2007",
+ fmt.apply(1172534400000L, 1172793600000L));
+ assertEquals("February 27\u2009\u2013\u2009March 1, 2007",
+ fmt.apply(1172548800000L, 1172793600000L));
// We want to show the true date if the end-point is a millisecond after midnight.
- assertEquals("February 27 – March 2, 2007", fmt.apply(1172534400000L, 1172793600001L));
+ assertEquals("February 27\u2009\u2013\u2009March 2, 2007",
+ fmt.apply(1172534400000L, 1172793600001L));
// 2006-02-27 00:00:00.000 GMT - 2007-03-02 00:00:00.000 GMT
- assertEquals("February 27, 2006 – March 1, 2007",
+ assertEquals("February 27, 2006\u2009\u2013\u2009March 1, 2007",
fmt.apply(1140998400000L, 1172793600000L));
// Spans a leap year's Feb 29th.
- assertEquals("February 27 – March 1, 2004", fmt.apply(1077840000000L, 1078185600000L));
+ assertEquals("February 27\u2009\u2013\u2009March 1, 2004",
+ fmt.apply(1077840000000L, 1078185600000L));
}
}
diff --git a/core/tests/coretests/src/android/text/format/DateUtilsTest.java b/core/tests/coretests/src/android/text/format/DateUtilsTest.java
index 381c051..39ed82ef 100644
--- a/core/tests/coretests/src/android/text/format/DateUtilsTest.java
+++ b/core/tests/coretests/src/android/text/format/DateUtilsTest.java
@@ -139,16 +139,16 @@
fixedTime, java.text.DateFormat.SHORT, java.text.DateFormat.FULL));
final long hourDuration = 2 * 60 * 60 * 1000;
- assertEquals("5:30:15 AM Greenwich Mean Time", DateUtils.formatSameDayTime(
+ assertEquals("5:30:15\u202fAM Greenwich Mean Time", DateUtils.formatSameDayTime(
fixedTime + hourDuration, fixedTime, java.text.DateFormat.FULL,
java.text.DateFormat.FULL));
- assertEquals("5:30:15 AM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
+ assertEquals("5:30:15\u202fAM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
fixedTime, java.text.DateFormat.FULL, java.text.DateFormat.DEFAULT));
- assertEquals("5:30:15 AM GMT", DateUtils.formatSameDayTime(fixedTime + hourDuration,
+ assertEquals("5:30:15\u202fAM GMT", DateUtils.formatSameDayTime(fixedTime + hourDuration,
fixedTime, java.text.DateFormat.FULL, java.text.DateFormat.LONG));
- assertEquals("5:30:15 AM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
+ assertEquals("5:30:15\u202fAM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
fixedTime, java.text.DateFormat.FULL, java.text.DateFormat.MEDIUM));
- assertEquals("5:30 AM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
+ assertEquals("5:30\u202fAM", DateUtils.formatSameDayTime(fixedTime + hourDuration,
fixedTime, java.text.DateFormat.FULL, java.text.DateFormat.SHORT));
}
diff --git a/core/tests/coretests/src/android/text/format/RelativeDateTimeFormatterTest.java b/core/tests/coretests/src/android/text/format/RelativeDateTimeFormatterTest.java
index b342516..2337802 100644
--- a/core/tests/coretests/src/android/text/format/RelativeDateTimeFormatterTest.java
+++ b/core/tests/coretests/src/android/text/format/RelativeDateTimeFormatterTest.java
@@ -468,37 +468,37 @@
cal.set(2015, Calendar.FEBRUARY, 5, 10, 50, 0);
final long base = cal.getTimeInMillis();
- assertEquals("5 seconds ago, 10:49 AM",
+ assertEquals("5 seconds ago, 10:49\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 5 * SECOND_IN_MILLIS, base, 0,
MINUTE_IN_MILLIS, 0));
- assertEquals("5 min. ago, 10:45 AM",
+ assertEquals("5 min. ago, 10:45\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 5 * MINUTE_IN_MILLIS, base, 0,
HOUR_IN_MILLIS, FORMAT_ABBREV_RELATIVE));
- assertEquals("0 hr. ago, 10:45 AM",
+ assertEquals("0 hr. ago, 10:45\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 5 * MINUTE_IN_MILLIS, base,
HOUR_IN_MILLIS, DAY_IN_MILLIS, FORMAT_ABBREV_RELATIVE));
- assertEquals("5 hours ago, 5:50 AM",
+ assertEquals("5 hours ago, 5:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 5 * HOUR_IN_MILLIS, base,
HOUR_IN_MILLIS, DAY_IN_MILLIS, 0));
- assertEquals("Yesterday, 7:50 PM",
+ assertEquals("Yesterday, 7:50\u202fPM",
getRelativeDateTimeString(en_US, tz, base - 15 * HOUR_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, FORMAT_ABBREV_RELATIVE));
- assertEquals("5 days ago, 10:50 AM",
+ assertEquals("5 days ago, 10:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 5 * DAY_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
- assertEquals("Jan 29, 10:50 AM",
+ assertEquals("Jan 29, 10:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 7 * DAY_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
- assertEquals("11/27/2014, 10:50 AM",
+ assertEquals("11/27/2014, 10:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 10 * WEEK_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
- assertEquals("11/27/2014, 10:50 AM",
+ assertEquals("11/27/2014, 10:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 10 * WEEK_IN_MILLIS, base, 0,
YEAR_IN_MILLIS, 0));
// User-supplied flags should be ignored when formatting the date clause.
final int FORMAT_SHOW_WEEKDAY = 0x00002;
- assertEquals("11/27/2014, 10:50 AM",
+ assertEquals("11/27/2014, 10:50\u202fAM",
getRelativeDateTimeString(en_US, tz, base - 10 * WEEK_IN_MILLIS, base, 0,
WEEK_IN_MILLIS,
FORMAT_ABBREV_ALL | FORMAT_SHOW_WEEKDAY));
@@ -514,14 +514,14 @@
// So 5 hours before 3:15 AM should be formatted as 'Yesterday, 9:15 PM'.
cal.set(2014, Calendar.MARCH, 9, 3, 15, 0);
long base = cal.getTimeInMillis();
- assertEquals("Yesterday, 9:15 PM",
+ assertEquals("Yesterday, 9:15\u202fPM",
getRelativeDateTimeString(en_US, tz, base - 5 * HOUR_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
// 1 hour after 2:00 AM should be formatted as 'In 1 hour, 4:00 AM'.
cal.set(2014, Calendar.MARCH, 9, 2, 0, 0);
base = cal.getTimeInMillis();
- assertEquals("In 1 hour, 4:00 AM",
+ assertEquals("In 1 hour, 4:00\u202fAM",
getRelativeDateTimeString(en_US, tz, base + 1 * HOUR_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
@@ -529,22 +529,22 @@
// 1:00 AM. 8 hours before 5:20 AM should be 'Yesterday, 10:20 PM'.
cal.set(2014, Calendar.NOVEMBER, 2, 5, 20, 0);
base = cal.getTimeInMillis();
- assertEquals("Yesterday, 10:20 PM",
+ assertEquals("Yesterday, 10:20\u202fPM",
getRelativeDateTimeString(en_US, tz, base - 8 * HOUR_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
cal.set(2014, Calendar.NOVEMBER, 2, 0, 45, 0);
base = cal.getTimeInMillis();
// 45 minutes after 0:45 AM should be 'In 45 minutes, 1:30 AM'.
- assertEquals("In 45 minutes, 1:30 AM",
+ assertEquals("In 45 minutes, 1:30\u202fAM",
getRelativeDateTimeString(en_US, tz, base + 45 * MINUTE_IN_MILLIS, base, 0,
WEEK_IN_MILLIS, 0));
// 45 minutes later, it should be 'In 45 minutes, 1:15 AM'.
- assertEquals("In 45 minutes, 1:15 AM",
+ assertEquals("In 45 minutes, 1:15\u202fAM",
getRelativeDateTimeString(en_US, tz, base + 90 * MINUTE_IN_MILLIS,
base + 45 * MINUTE_IN_MILLIS, 0, WEEK_IN_MILLIS, 0));
// Another 45 minutes later, it should be 'In 45 minutes, 2:00 AM'.
- assertEquals("In 45 minutes, 2:00 AM",
+ assertEquals("In 45 minutes, 2:00\u202fAM",
getRelativeDateTimeString(en_US, tz, base + 135 * MINUTE_IN_MILLIS,
base + 90 * MINUTE_IN_MILLIS, 0, WEEK_IN_MILLIS, 0));
}
@@ -593,7 +593,7 @@
Calendar yesterdayCalendar1 = Calendar.getInstance(tz, en_US);
yesterdayCalendar1.set(2011, Calendar.SEPTEMBER, 1, 10, 24, 0);
long yesterday1 = yesterdayCalendar1.getTimeInMillis();
- assertEquals("Yesterday, 10:24 AM",
+ assertEquals("Yesterday, 10:24\u202fAM",
getRelativeDateTimeString(en_US, tz, yesterday1, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -601,7 +601,7 @@
Calendar yesterdayCalendar2 = Calendar.getInstance(tz, en_US);
yesterdayCalendar2.set(2011, Calendar.SEPTEMBER, 1, 10, 22, 0);
long yesterday2 = yesterdayCalendar2.getTimeInMillis();
- assertEquals("Yesterday, 10:22 AM",
+ assertEquals("Yesterday, 10:22\u202fAM",
getRelativeDateTimeString(en_US, tz, yesterday2, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -609,7 +609,7 @@
Calendar twoDaysAgoCalendar1 = Calendar.getInstance(tz, en_US);
twoDaysAgoCalendar1.set(2011, Calendar.AUGUST, 31, 10, 24, 0);
long twoDaysAgo1 = twoDaysAgoCalendar1.getTimeInMillis();
- assertEquals("2 days ago, 10:24 AM",
+ assertEquals("2 days ago, 10:24\u202fAM",
getRelativeDateTimeString(en_US, tz, twoDaysAgo1, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -617,7 +617,7 @@
Calendar twoDaysAgoCalendar2 = Calendar.getInstance(tz, en_US);
twoDaysAgoCalendar2.set(2011, Calendar.AUGUST, 31, 10, 22, 0);
long twoDaysAgo2 = twoDaysAgoCalendar2.getTimeInMillis();
- assertEquals("2 days ago, 10:22 AM",
+ assertEquals("2 days ago, 10:22\u202fAM",
getRelativeDateTimeString(en_US, tz, twoDaysAgo2, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -625,7 +625,7 @@
Calendar tomorrowCalendar1 = Calendar.getInstance(tz, en_US);
tomorrowCalendar1.set(2011, Calendar.SEPTEMBER, 3, 10, 22, 0);
long tomorrow1 = tomorrowCalendar1.getTimeInMillis();
- assertEquals("Tomorrow, 10:22 AM",
+ assertEquals("Tomorrow, 10:22\u202fAM",
getRelativeDateTimeString(en_US, tz, tomorrow1, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -633,7 +633,7 @@
Calendar tomorrowCalendar2 = Calendar.getInstance(tz, en_US);
tomorrowCalendar2.set(2011, Calendar.SEPTEMBER, 3, 10, 24, 0);
long tomorrow2 = tomorrowCalendar2.getTimeInMillis();
- assertEquals("Tomorrow, 10:24 AM",
+ assertEquals("Tomorrow, 10:24\u202fAM",
getRelativeDateTimeString(en_US, tz, tomorrow2, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -641,7 +641,7 @@
Calendar twoDaysLaterCalendar1 = Calendar.getInstance(tz, en_US);
twoDaysLaterCalendar1.set(2011, Calendar.SEPTEMBER, 4, 10, 22, 0);
long twoDaysLater1 = twoDaysLaterCalendar1.getTimeInMillis();
- assertEquals("In 2 days, 10:22 AM",
+ assertEquals("In 2 days, 10:22\u202fAM",
getRelativeDateTimeString(en_US, tz, twoDaysLater1, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
@@ -649,7 +649,7 @@
Calendar twoDaysLaterCalendar2 = Calendar.getInstance(tz, en_US);
twoDaysLaterCalendar2.set(2011, Calendar.SEPTEMBER, 4, 10, 24, 0);
long twoDaysLater2 = twoDaysLaterCalendar2.getTimeInMillis();
- assertEquals("In 2 days, 10:24 AM",
+ assertEquals("In 2 days, 10:24\u202fAM",
getRelativeDateTimeString(en_US, tz, twoDaysLater2, now, MINUTE_IN_MILLIS,
WEEK_IN_MILLIS, 0));
}
@@ -664,11 +664,11 @@
cal.set(2012, Calendar.FEBRUARY, 5, 10, 50, 0);
long base = cal.getTimeInMillis();
- assertEquals("Feb 5, 5:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("Feb 5, 5:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 5 * HOUR_IN_MILLIS, base, 0, MINUTE_IN_MILLIS, 0));
- assertEquals("Jan 29, 10:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("Jan 29, 10:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 7 * DAY_IN_MILLIS, base, 0, WEEK_IN_MILLIS, 0));
- assertEquals("11/27/2011, 10:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("11/27/2011, 10:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 10 * WEEK_IN_MILLIS, base, 0, WEEK_IN_MILLIS, 0));
assertEquals("January 6", getRelativeTimeSpanString(en_US, tz,
@@ -687,11 +687,11 @@
// Feb 5, 2018 at 10:50 PST
cal.set(2018, Calendar.FEBRUARY, 5, 10, 50, 0);
base = cal.getTimeInMillis();
- assertEquals("Feb 5, 5:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("Feb 5, 5:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 5 * HOUR_IN_MILLIS, base, 0, MINUTE_IN_MILLIS, 0));
- assertEquals("Jan 29, 10:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("Jan 29, 10:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 7 * DAY_IN_MILLIS, base, 0, WEEK_IN_MILLIS, 0));
- assertEquals("11/27/2017, 10:50 AM", getRelativeDateTimeString(en_US, tz,
+ assertEquals("11/27/2017, 10:50\u202fAM", getRelativeDateTimeString(en_US, tz,
base - 10 * WEEK_IN_MILLIS, base, 0, WEEK_IN_MILLIS, 0));
assertEquals("January 6", getRelativeTimeSpanString(en_US, tz,
diff --git a/core/tests/coretests/src/android/widget/RemoteViewsTest.java b/core/tests/coretests/src/android/widget/RemoteViewsTest.java
index 00b3693..bbf9f3c 100644
--- a/core/tests/coretests/src/android/widget/RemoteViewsTest.java
+++ b/core/tests/coretests/src/android/widget/RemoteViewsTest.java
@@ -128,6 +128,7 @@
RemoteViews clone = child.clone();
}
+ @SuppressWarnings("ReturnValueIgnored")
@Test
public void clone_repeatedly() {
RemoteViews original = new RemoteViews(mPackage, R.layout.remote_views_test);
@@ -485,6 +486,7 @@
}
}
+ @SuppressWarnings("ReturnValueIgnored")
@Test
public void nestedAddViews() {
RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test);
@@ -509,6 +511,7 @@
parcelAndRecreate(views);
}
+ @SuppressWarnings("ReturnValueIgnored")
@Test
public void nestedLandscapeViews() {
RemoteViews views = new RemoteViews(mPackage, R.layout.remote_views_test);
diff --git a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
index 82b2bf4..8207c9e 100644
--- a/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/BinderCallsStatsTest.java
@@ -1054,10 +1054,23 @@
super(new Injector() {
public Random getRandomGenerator() {
return new Random() {
- int mCallCount = 0;
+ int mCallCount = -1;
public int nextInt() {
- return mCallCount++;
+ throw new IllegalStateException("Should not use nextInt()");
+ }
+
+ public int nextInt(int x) {
+ if (mCallCount == -1) {
+ // The tests are written such that they expect
+ // the first call to nextInt() to be on the first
+ // callEnded(). However, the BinderCallsStats
+ // constructor also calls nextInt(). Fake 0 being
+ // rolled twice.
+ mCallCount++;
+ return 0;
+ }
+ return (mCallCount++) % x;
}
};
}
diff --git a/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java b/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java
index 5af7376..7bd53b9 100644
--- a/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java
+++ b/core/tests/coretests/src/com/android/internal/os/BinderLatencyObserverTest.java
@@ -98,7 +98,7 @@
assertEquals(1, latencyHistograms.size());
LatencyDims dims = latencyHistograms.keySet().iterator().next();
assertEquals(binder.getClass(), dims.getBinderClass());
- assertEquals(1, dims.getTransactionCode());
+ assertEquals(2, dims.getTransactionCode()); // the first nextInt() is in the constructor
assertThat(latencyHistograms.get(dims)).asList().containsExactly(1, 0, 0, 0, 0).inOrder();
}
@@ -313,11 +313,11 @@
int mCallCount = 0;
public int nextInt() {
- return mCallCount++;
+ throw new IllegalStateException("Should not use nextInt()");
}
public int nextInt(int x) {
- return 1;
+ return (mCallCount++) % x;
}
};
}
diff --git a/core/tests/coretests/src/com/android/internal/os/SafeZipPathValidatorCallbackTest.java b/core/tests/coretests/src/com/android/internal/os/SafeZipPathValidatorCallbackTest.java
new file mode 100644
index 0000000..c540a15
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/os/SafeZipPathValidatorCallbackTest.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.os;
+
+import static org.junit.Assert.assertThrows;
+
+import android.compat.testing.PlatformCompatChangeRule;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import libcore.junit.util.compat.CoreCompatChangeRule.DisableCompatChanges;
+import libcore.junit.util.compat.CoreCompatChangeRule.EnableCompatChanges;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
+import java.util.zip.ZipFile;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+/**
+ * Test SafeZipPathCallback.
+ */
+@RunWith(AndroidJUnit4.class)
+public class SafeZipPathValidatorCallbackTest {
+ @Rule
+ public TestRule mCompatChangeRule = new PlatformCompatChangeRule();
+
+ @Before
+ public void setUp() {
+ RuntimeInit.initZipPathValidatorCallback();
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void testNewZipFile_whenZipFileHasDangerousEntriesAndChangeEnabled_throws()
+ throws Exception {
+ final String[] dangerousEntryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ };
+ for (String entryName : dangerousEntryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+
+ assertThrows(
+ "ZipException expected for entry: " + entryName,
+ ZipException.class,
+ () -> {
+ new ZipFile(tempFile);
+ });
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasDangerousEntriesAndChangeEnabled_throws()
+ throws Exception {
+ final String[] dangerousEntryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ };
+ for (String entryName : dangerousEntryNames) {
+ byte[] badZipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(badZipBytes))) {
+ assertThrows(
+ "ZipException expected for entry: " + entryName,
+ ZipException.class,
+ () -> {
+ zis.getNextEntry();
+ });
+ }
+ }
+ }
+
+ @Test
+ @EnableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void testNewZipFile_whenZipFileHasNormalEntriesAndChangeEnabled_doesNotThrow()
+ throws Exception {
+ final String[] normalEntryNames = {
+ "foo", "foo.bar", "foo..bar",
+ };
+ for (String entryName : normalEntryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+ try {
+ new ZipFile((tempFile));
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasNormalEntriesAndChangeEnabled_doesNotThrow()
+ throws Exception {
+ final String[] normalEntryNames = {
+ "foo", "foo.bar", "foo..bar",
+ };
+ for (String entryName : normalEntryNames) {
+ byte[] zipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try {
+ ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes));
+ zis.getNextEntry();
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testNewZipFile_whenZipFileHasNormalAndDangerousEntriesAndChangeDisabled_doesNotThrow()
+ throws Exception {
+ final String[] entryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ "foo",
+ "foo.bar",
+ "foo..bar",
+ };
+ for (String entryName : entryNames) {
+ final File tempFile = File.createTempFile("smdc", "zip");
+ try {
+ writeZipFileOutputStreamWithEmptyEntry(tempFile, entryName);
+ try {
+ new ZipFile((tempFile));
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ } finally {
+ tempFile.delete();
+ }
+ }
+ }
+
+ @Test
+ @DisableCompatChanges({SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL})
+ public void
+ testZipInputStreamGetNextEntry_whenZipFileHasNormalAndDangerousEntriesAndChangeDisabled_doesNotThrow()
+ throws Exception {
+ final String[] entryNames = {
+ "../foo.bar",
+ "foo/../bar.baz",
+ "foo/../../bar.baz",
+ "foo.bar/..",
+ "foo.bar/../",
+ "..",
+ "../",
+ "/foo",
+ "foo",
+ "foo.bar",
+ "foo..bar",
+ };
+ for (String entryName : entryNames) {
+ byte[] zipBytes = getZipBytesFromZipOutputStreamWithEmptyEntry(entryName);
+ try {
+ ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes));
+ zis.getNextEntry();
+ } catch (ZipException e) {
+ throw new AssertionError("ZipException not expected for entry: " + entryName);
+ }
+ }
+ }
+
+ private void writeZipFileOutputStreamWithEmptyEntry(File tempFile, String entryName)
+ throws IOException {
+ FileOutputStream tempFileStream = new FileOutputStream(tempFile);
+ writeZipOutputStreamWithEmptyEntry(tempFileStream, entryName);
+ tempFileStream.close();
+ }
+
+ private byte[] getZipBytesFromZipOutputStreamWithEmptyEntry(String entryName)
+ throws IOException {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ writeZipOutputStreamWithEmptyEntry(bos, entryName);
+ return bos.toByteArray();
+ }
+
+ private void writeZipOutputStreamWithEmptyEntry(OutputStream os, String entryName)
+ throws IOException {
+ ZipOutputStream zos = new ZipOutputStream(os);
+ ZipEntry entry = new ZipEntry(entryName);
+ zos.putNextEntry(entry);
+ zos.write(new byte[2]);
+ zos.closeEntry();
+ zos.close();
+ }
+}
diff --git a/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java b/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java
index 6c50bce..8b30828 100644
--- a/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java
+++ b/core/tests/coretests/src/com/android/internal/util/TokenBucketTest.java
@@ -16,6 +16,8 @@
package com.android.internal.util;
+import static org.junit.Assert.assertThrows;
+
import android.os.SystemClock;
import android.text.format.DateUtils;
@@ -170,10 +172,9 @@
}
void assertThrow(Fn fn) {
- try {
+ assertThrows(Throwable.class, () -> {
fn.call();
- fail("expected n exception to be thrown.");
- } catch (Throwable t) { }
+ });
}
interface Fn { void call(); }
diff --git a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
index 41b8956f..a226325 100644
--- a/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
+++ b/core/tests/hosttests/test-apps/MultiDexLegacyTestApp/src/com/android/multidexlegacytestapp/Test.java
@@ -31,6 +31,7 @@
assertEquals(3366, getActivity().getValue());
}
+ @SuppressWarnings("ReturnValueIgnored")
public void testAnnotation() throws Exception {
assertEquals(ReferencedByAnnotation.B,
((AnnotationWithEnum) TestApplication.annotation).value());
diff --git a/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java b/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java
index c53f4cc..1581abb 100644
--- a/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java
+++ b/core/tests/utiltests/src/com/android/internal/util/CallbackRegistryTest.java
@@ -20,6 +20,7 @@
import org.junit.Test;
import java.util.ArrayList;
+import java.util.Objects;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -39,11 +40,11 @@
Integer argValue;
private void addNotifyCount(Integer callback) {
- if (callback == callback1) {
+ if (Objects.equals(callback, callback1)) {
notify1++;
- } else if (callback == callback2) {
+ } else if (Objects.equals(callback, callback2)) {
notify2++;
- } else if (callback == callback3) {
+ } else if (Objects.equals(callback, callback3)) {
notify3++;
}
deepNotifyCount[callback]++;
@@ -114,7 +115,7 @@
public void onNotifyCallback(Integer callback, CallbackRegistryTest sender,
int arg1, Integer arg) {
addNotifyCount(callback);
- if (callback == callback1) {
+ if (Objects.equals(callback, callback1)) {
registry.remove(callback1);
registry.remove(callback2);
}
@@ -166,9 +167,9 @@
public void onNotifyCallback(Integer callback, CallbackRegistryTest sender,
int arg1, Integer arg) {
addNotifyCount(callback);
- if (callback == callback1) {
+ if (Objects.equals(callback, callback1)) {
registry.remove(callback2);
- } else if (callback == callback3) {
+ } else if (Objects.equals(callback, callback3)) {
registry.add(callback2);
}
}
diff --git a/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java b/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java
index 8706a68..42e3046 100644
--- a/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java
+++ b/errorprone/java/com/google/errorprone/bugpatterns/android/EfficientXmlChecker.java
@@ -168,6 +168,7 @@
*/
private static final Matcher<ExpressionTree> CONVERT_PRIMITIVE_TO_STRING =
new Matcher<ExpressionTree>() {
+ @SuppressWarnings("TreeToString") //TODO: Fix me
@Override
public boolean matches(ExpressionTree tree, VisitorState state) {
if (PRIMITIVE_TO_STRING.matches(tree, state)) {
@@ -205,6 +206,7 @@
*/
private static final Matcher<ExpressionTree> CONVERT_STRING_TO_PRIMITIVE =
new Matcher<ExpressionTree>() {
+ @SuppressWarnings("TreeToString") //TODO: Fix me
@Override
public boolean matches(ExpressionTree tree, VisitorState state) {
if (PRIMITIVE_PARSE.matches(tree, state)) {
diff --git a/graphics/java/android/graphics/drawable/RippleDrawable.java b/graphics/java/android/graphics/drawable/RippleDrawable.java
index 74cad1a..b170869 100644
--- a/graphics/java/android/graphics/drawable/RippleDrawable.java
+++ b/graphics/java/android/graphics/drawable/RippleDrawable.java
@@ -758,7 +758,7 @@
if (mBackground != null) {
mBackground.onHotspotBoundsChanged();
}
- float newRadius = Math.round(getComputedRadius());
+ float newRadius = getComputedRadius();
for (int i = 0; i < mRunningAnimations.size(); i++) {
RippleAnimationSession s = mRunningAnimations.get(i);
s.setRadius(newRadius);
diff --git a/graphics/java/android/graphics/drawable/VectorDrawable.java b/graphics/java/android/graphics/drawable/VectorDrawable.java
index 4065bd1..e25ee90 100644
--- a/graphics/java/android/graphics/drawable/VectorDrawable.java
+++ b/graphics/java/android/graphics/drawable/VectorDrawable.java
@@ -60,7 +60,7 @@
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Map;
import java.util.Stack;
/**
@@ -1171,18 +1171,14 @@
private static final int NATIVE_ALLOCATION_SIZE = 100;
- private static final HashMap<String, Integer> sPropertyIndexMap =
- new HashMap<String, Integer>() {
- {
- put("translateX", TRANSLATE_X_INDEX);
- put("translateY", TRANSLATE_Y_INDEX);
- put("scaleX", SCALE_X_INDEX);
- put("scaleY", SCALE_Y_INDEX);
- put("pivotX", PIVOT_X_INDEX);
- put("pivotY", PIVOT_Y_INDEX);
- put("rotation", ROTATION_INDEX);
- }
- };
+ private static final Map<String, Integer> sPropertyIndexMap = Map.of(
+ "translateX", TRANSLATE_X_INDEX,
+ "translateY", TRANSLATE_Y_INDEX,
+ "scaleX", SCALE_X_INDEX,
+ "scaleY", SCALE_Y_INDEX,
+ "pivotX", PIVOT_X_INDEX,
+ "pivotY", PIVOT_Y_INDEX,
+ "rotation", ROTATION_INDEX);
static int getPropertyIndex(String propertyName) {
if (sPropertyIndexMap.containsKey(propertyName)) {
@@ -1285,18 +1281,15 @@
}
};
- private static final HashMap<String, Property> sPropertyMap =
- new HashMap<String, Property>() {
- {
- put("translateX", TRANSLATE_X);
- put("translateY", TRANSLATE_Y);
- put("scaleX", SCALE_X);
- put("scaleY", SCALE_Y);
- put("pivotX", PIVOT_X);
- put("pivotY", PIVOT_Y);
- put("rotation", ROTATION);
- }
- };
+ private static final Map<String, Property> sPropertyMap = Map.of(
+ "translateX", TRANSLATE_X,
+ "translateY", TRANSLATE_Y,
+ "scaleX", SCALE_X,
+ "scaleY", SCALE_Y,
+ "pivotX", PIVOT_X,
+ "pivotY", PIVOT_Y,
+ "rotation", ROTATION);
+
// Temp array to store transform values obtained from native.
private float[] mTransform;
/////////////////////////////////////////////////////
@@ -1762,19 +1755,15 @@
private static final int NATIVE_ALLOCATION_SIZE = 264;
// Property map for animatable attributes.
- private final static HashMap<String, Integer> sPropertyIndexMap
- = new HashMap<String, Integer> () {
- {
- put("strokeWidth", STROKE_WIDTH_INDEX);
- put("strokeColor", STROKE_COLOR_INDEX);
- put("strokeAlpha", STROKE_ALPHA_INDEX);
- put("fillColor", FILL_COLOR_INDEX);
- put("fillAlpha", FILL_ALPHA_INDEX);
- put("trimPathStart", TRIM_PATH_START_INDEX);
- put("trimPathEnd", TRIM_PATH_END_INDEX);
- put("trimPathOffset", TRIM_PATH_OFFSET_INDEX);
- }
- };
+ private static final Map<String, Integer> sPropertyIndexMap = Map.of(
+ "strokeWidth", STROKE_WIDTH_INDEX,
+ "strokeColor", STROKE_COLOR_INDEX,
+ "strokeAlpha", STROKE_ALPHA_INDEX,
+ "fillColor", FILL_COLOR_INDEX,
+ "fillAlpha", FILL_ALPHA_INDEX,
+ "trimPathStart", TRIM_PATH_START_INDEX,
+ "trimPathEnd", TRIM_PATH_END_INDEX,
+ "trimPathOffset", TRIM_PATH_OFFSET_INDEX);
// Below are the Properties that wrap the setters to avoid reflection overhead in animations
private static final Property<VFullPath, Float> STROKE_WIDTH =
@@ -1881,19 +1870,15 @@
}
};
- private final static HashMap<String, Property> sPropertyMap
- = new HashMap<String, Property> () {
- {
- put("strokeWidth", STROKE_WIDTH);
- put("strokeColor", STROKE_COLOR);
- put("strokeAlpha", STROKE_ALPHA);
- put("fillColor", FILL_COLOR);
- put("fillAlpha", FILL_ALPHA);
- put("trimPathStart", TRIM_PATH_START);
- put("trimPathEnd", TRIM_PATH_END);
- put("trimPathOffset", TRIM_PATH_OFFSET);
- }
- };
+ private static final Map<String, Property> sPropertyMap = Map.of(
+ "strokeWidth", STROKE_WIDTH,
+ "strokeColor", STROKE_COLOR,
+ "strokeAlpha", STROKE_ALPHA,
+ "fillColor", FILL_COLOR,
+ "fillAlpha", FILL_ALPHA,
+ "trimPathStart", TRIM_PATH_START,
+ "trimPathEnd", TRIM_PATH_END,
+ "trimPathOffset", TRIM_PATH_OFFSET);
// Temp array to store property data obtained from native getter.
private byte[] mPropertyData;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
index 54d62ed..978ad8a 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/startingsurface/StartingSurfaceDrawer.java
@@ -429,7 +429,8 @@
}
@Override
- public @Nullable SplashScreenView get() {
+ @Nullable
+ public SplashScreenView get() {
synchronized (this) {
while (!mIsViewSet) {
try {
@@ -690,7 +691,7 @@
private final TaskSnapshotWindow mTaskSnapshotWindow;
private SplashScreenView mContentView;
private boolean mSetSplashScreen;
- private @StartingWindowType int mSuggestType;
+ @StartingWindowType private int mSuggestType;
private int mBGColor;
private final long mCreateTime;
private int mSystemBarAppearance;
@@ -731,7 +732,7 @@
// Reset the system bar color which set by splash screen, make it align to the app.
private void clearSystemBarColor() {
- if (mDecorView == null) {
+ if (mDecorView == null || !mDecorView.isAttachedToWindow()) {
return;
}
if (mDecorView.getLayoutParams() instanceof WindowManager.LayoutParams) {
diff --git a/libs/androidfw/LocaleDataTables.cpp b/libs/androidfw/LocaleDataTables.cpp
index b3fb145..b68143d 100644
--- a/libs/androidfw/LocaleDataTables.cpp
+++ b/libs/androidfw/LocaleDataTables.cpp
@@ -143,6 +143,7 @@
{0xACE00000u, 46u}, // ahl -> Latn
{0xB8E00000u, 1u}, // aho -> Ahom
{0x99200000u, 46u}, // ajg -> Latn
+ {0xCD200000u, 2u}, // ajt -> Arab
{0x616B0000u, 46u}, // ak -> Latn
{0xA9400000u, 101u}, // akk -> Xsux
{0x81600000u, 46u}, // ala -> Latn
@@ -1053,6 +1054,7 @@
{0xB70D0000u, 46u}, // nyn -> Latn
{0xA32D0000u, 46u}, // nzi -> Latn
{0x6F630000u, 46u}, // oc -> Latn
+ {0x6F634553u, 46u}, // oc-ES -> Latn
{0x88CE0000u, 46u}, // ogc -> Latn
{0x6F6A0000u, 11u}, // oj -> Cans
{0xC92E0000u, 11u}, // ojs -> Cans
@@ -1093,6 +1095,7 @@
{0xB4EF0000u, 71u}, // phn -> Phnx
{0xAD0F0000u, 46u}, // pil -> Latn
{0xBD0F0000u, 46u}, // pip -> Latn
+ {0xC90F0000u, 46u}, // pis -> Latn
{0x814F0000u, 9u}, // pka -> Brah
{0xB94F0000u, 46u}, // pko -> Latn
{0x706C0000u, 46u}, // pl -> Latn
@@ -1204,12 +1207,14 @@
{0xE1720000u, 46u}, // sly -> Latn
{0x736D0000u, 46u}, // sm -> Latn
{0x81920000u, 46u}, // sma -> Latn
+ {0x8D920000u, 46u}, // smd -> Latn
{0xA5920000u, 46u}, // smj -> Latn
{0xB5920000u, 46u}, // smn -> Latn
{0xBD920000u, 76u}, // smp -> Samr
{0xC1920000u, 46u}, // smq -> Latn
{0xC9920000u, 46u}, // sms -> Latn
{0x736E0000u, 46u}, // sn -> Latn
+ {0x85B20000u, 46u}, // snb -> Latn
{0x89B20000u, 46u}, // snc -> Latn
{0xA9B20000u, 46u}, // snk -> Latn
{0xBDB20000u, 46u}, // snp -> Latn
@@ -1314,6 +1319,7 @@
{0x746F0000u, 46u}, // to -> Latn
{0x95D30000u, 46u}, // tof -> Latn
{0x99D30000u, 46u}, // tog -> Latn
+ {0xA9D30000u, 46u}, // tok -> Latn
{0xC1D30000u, 46u}, // toq -> Latn
{0xA1F30000u, 46u}, // tpi -> Latn
{0xB1F30000u, 46u}, // tpm -> Latn
@@ -1527,6 +1533,7 @@
0x61665A414C61746ELLU, // af_Latn_ZA
0xC0C0434D4C61746ELLU, // agq_Latn_CM
0xB8E0494E41686F6DLLU, // aho_Ahom_IN
+ 0xCD20544E41726162LLU, // ajt_Arab_TN
0x616B47484C61746ELLU, // ak_Latn_GH
0xA940495158737578LLU, // akk_Xsux_IQ
0xB560584B4C61746ELLU, // aln_Latn_XK
@@ -1534,6 +1541,7 @@
0x616D455445746869LLU, // am_Ethi_ET
0xB9804E474C61746ELLU, // amo_Latn_NG
0x616E45534C61746ELLU, // an_Latn_ES
+ 0xB5A04E474C61746ELLU, // ann_Latn_NG
0xE5C049444C61746ELLU, // aoz_Latn_ID
0x8DE0544741726162LLU, // apd_Arab_TG
0x6172454741726162LLU, // ar_Arab_EG
@@ -2039,6 +2047,7 @@
0xB88F49525870656FLLU, // peo_Xpeo_IR
0xACAF44454C61746ELLU, // pfl_Latn_DE
0xB4EF4C4250686E78LLU, // phn_Phnx_LB
+ 0xC90F53424C61746ELLU, // pis_Latn_SB
0x814F494E42726168LLU, // pka_Brah_IN
0xB94F4B454C61746ELLU, // pko_Latn_KE
0x706C504C4C61746ELLU, // pl_Latn_PL
@@ -2119,11 +2128,13 @@
0xE17249444C61746ELLU, // sly_Latn_ID
0x736D57534C61746ELLU, // sm_Latn_WS
0x819253454C61746ELLU, // sma_Latn_SE
+ 0x8D92414F4C61746ELLU, // smd_Latn_AO
0xA59253454C61746ELLU, // smj_Latn_SE
0xB59246494C61746ELLU, // smn_Latn_FI
0xBD92494C53616D72LLU, // smp_Samr_IL
0xC99246494C61746ELLU, // sms_Latn_FI
0x736E5A574C61746ELLU, // sn_Latn_ZW
+ 0x85B24D594C61746ELLU, // snb_Latn_MY
0xA9B24D4C4C61746ELLU, // snk_Latn_ML
0x736F534F4C61746ELLU, // so_Latn_SO
0x99D2555A536F6764LLU, // sog_Sogd_UZ
diff --git a/libs/androidfw/ZipUtils.cpp b/libs/androidfw/ZipUtils.cpp
index 58fc5bb..a1385f2 100644
--- a/libs/androidfw/ZipUtils.cpp
+++ b/libs/androidfw/ZipUtils.cpp
@@ -35,7 +35,7 @@
using namespace android;
// TODO: This can go away once the only remaining usage in aapt goes away.
-class FileReader : public zip_archive::Reader {
+class FileReader final : public zip_archive::Reader {
public:
explicit FileReader(FILE* fp) : Reader(), mFp(fp), mCurrentOffset(0) {
}
@@ -66,7 +66,7 @@
mutable off64_t mCurrentOffset;
};
-class FdReader : public zip_archive::Reader {
+class FdReader final : public zip_archive::Reader {
public:
explicit FdReader(int fd) : mFd(fd) {
}
@@ -79,7 +79,7 @@
const int mFd;
};
-class BufferReader : public zip_archive::Reader {
+class BufferReader final : public zip_archive::Reader {
public:
BufferReader(incfs::map_ptr<void> input, size_t inputSize) : Reader(),
mInput(input.convert<uint8_t>()),
@@ -105,7 +105,7 @@
const size_t mInputSize;
};
-class BufferWriter : public zip_archive::Writer {
+class BufferWriter final : public zip_archive::Writer {
public:
BufferWriter(void* output, size_t outputSize) : Writer(),
mOutput(reinterpret_cast<uint8_t*>(output)), mOutputSize(outputSize), mBytesWritten(0) {
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index ad9aa6c..33f7935 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -674,6 +674,7 @@
srcs: [
"tests/unit/main.cpp",
"tests/unit/ABitmapTests.cpp",
+ "tests/unit/AutoBackendTextureReleaseTests.cpp",
"tests/unit/CacheManagerTests.cpp",
"tests/unit/CanvasContextTests.cpp",
"tests/unit/CanvasOpTests.cpp",
diff --git a/libs/hwui/AutoBackendTextureRelease.cpp b/libs/hwui/AutoBackendTextureRelease.cpp
index ef5eacb..b656b6a 100644
--- a/libs/hwui/AutoBackendTextureRelease.cpp
+++ b/libs/hwui/AutoBackendTextureRelease.cpp
@@ -32,9 +32,17 @@
bool createProtectedImage = 0 != (desc.usage & AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT);
GrBackendFormat backendFormat =
GrAHardwareBufferUtils::GetBackendFormat(context, buffer, desc.format, false);
+ LOG_ALWAYS_FATAL_IF(!backendFormat.isValid(),
+ __FILE__ " Invalid GrBackendFormat. GrBackendApi==%" PRIu32
+ ", AHardwareBuffer_Format==%" PRIu32 ".",
+ static_cast<int>(context->backend()), desc.format);
mBackendTexture = GrAHardwareBufferUtils::MakeBackendTexture(
context, buffer, desc.width, desc.height, &mDeleteProc, &mUpdateProc, &mImageCtx,
createProtectedImage, backendFormat, false);
+ LOG_ALWAYS_FATAL_IF(!mBackendTexture.isValid(),
+ __FILE__ " Invalid GrBackendTexture. Width==%" PRIu32 ", height==%" PRIu32
+ ", protected==%d",
+ desc.width, desc.height, createProtectedImage);
}
void AutoBackendTextureRelease::unref(bool releaseImage) {
@@ -74,13 +82,13 @@
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
SkColorType colorType = GrAHardwareBufferUtils::GetSkColorTypeFromBufferFormat(desc.format);
+ // The following ref will be counteracted by Skia calling releaseProc, either during
+ // MakeFromTexture if there is a failure, or later when SkImage is discarded. It must
+ // be called before MakeFromTexture, otherwise Skia may remove HWUI's ref on failure.
+ ref();
mImage = SkImage::MakeFromTexture(
context, mBackendTexture, kTopLeft_GrSurfaceOrigin, colorType, kPremul_SkAlphaType,
uirenderer::DataSpaceToColorSpace(dataspace), releaseProc, this);
- if (mImage.get()) {
- // The following ref will be counteracted by releaseProc, when SkImage is discarded.
- ref();
- }
}
void AutoBackendTextureRelease::newBufferContent(GrDirectContext* context) {
diff --git a/libs/hwui/AutoBackendTextureRelease.h b/libs/hwui/AutoBackendTextureRelease.h
index c9bb767..f0eb2a8 100644
--- a/libs/hwui/AutoBackendTextureRelease.h
+++ b/libs/hwui/AutoBackendTextureRelease.h
@@ -25,6 +25,9 @@
namespace android {
namespace uirenderer {
+// Friend TestUtils serves as a proxy for any test cases that require access to private members.
+class TestUtils;
+
/**
* AutoBackendTextureRelease manages EglImage/VkImage lifetime. It is a ref-counted object
* that keeps GPU resources alive until the last SkImage object using them is destroyed.
@@ -66,6 +69,9 @@
// mImage is the SkImage created from mBackendTexture.
sk_sp<SkImage> mImage;
+
+ // Friend TestUtils serves as a proxy for any test cases that require access to private members.
+ friend class TestUtils;
};
} /* namespace uirenderer */
diff --git a/libs/hwui/tests/common/TestUtils.h b/libs/hwui/tests/common/TestUtils.h
index 5092675..fcaa745 100644
--- a/libs/hwui/tests/common/TestUtils.h
+++ b/libs/hwui/tests/common/TestUtils.h
@@ -16,6 +16,7 @@
#pragma once
+#include <AutoBackendTextureRelease.h>
#include <DisplayList.h>
#include <Matrix.h>
#include <Properties.h>
@@ -283,6 +284,11 @@
static SkRect getClipBounds(const SkCanvas* canvas);
static SkRect getLocalClipBounds(const SkCanvas* canvas);
+ static int getUsageCount(const AutoBackendTextureRelease* textureRelease) {
+ EXPECT_NE(nullptr, textureRelease);
+ return textureRelease->mUsageCount;
+ }
+
struct CallCounts {
int sync = 0;
int contextDestroyed = 0;
diff --git a/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp b/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp
new file mode 100644
index 0000000..2ec78a4
--- /dev/null
+++ b/libs/hwui/tests/unit/AutoBackendTextureReleaseTests.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include "AutoBackendTextureRelease.h"
+#include "tests/common/TestUtils.h"
+
+using namespace android;
+using namespace android::uirenderer;
+
+AHardwareBuffer* allocHardwareBuffer() {
+ AHardwareBuffer* buffer;
+ AHardwareBuffer_Desc desc = {
+ .width = 16,
+ .height = 16,
+ .layers = 1,
+ .format = AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM,
+ .usage = AHARDWAREBUFFER_USAGE_CPU_READ_RARELY | AHARDWAREBUFFER_USAGE_CPU_WRITE_RARELY,
+ };
+ constexpr int kSucceeded = 0;
+ int status = AHardwareBuffer_allocate(&desc, &buffer);
+ EXPECT_EQ(kSucceeded, status);
+ return buffer;
+}
+
+// Expands to AutoBackendTextureRelease_makeImage_invalid_RenderThreadTest,
+// set as friend in AutoBackendTextureRelease.h
+RENDERTHREAD_TEST(AutoBackendTextureRelease, makeImage_invalid) {
+ AHardwareBuffer* buffer = allocHardwareBuffer();
+ AutoBackendTextureRelease* textureRelease =
+ new AutoBackendTextureRelease(renderThread.getGrContext(), buffer);
+
+ EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease));
+
+ // SkImage::MakeFromTexture should fail if given null GrDirectContext.
+ textureRelease->makeImage(buffer, HAL_DATASPACE_UNKNOWN, /*context = */ nullptr);
+
+ EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease));
+
+ textureRelease->unref(true);
+ AHardwareBuffer_release(buffer);
+}
+
+// Expands to AutoBackendTextureRelease_makeImage_valid_RenderThreadTest,
+// set as friend in AutoBackendTextureRelease.h
+RENDERTHREAD_TEST(AutoBackendTextureRelease, makeImage_valid) {
+ AHardwareBuffer* buffer = allocHardwareBuffer();
+ AutoBackendTextureRelease* textureRelease =
+ new AutoBackendTextureRelease(renderThread.getGrContext(), buffer);
+
+ EXPECT_EQ(1, TestUtils::getUsageCount(textureRelease));
+
+ textureRelease->makeImage(buffer, HAL_DATASPACE_UNKNOWN, renderThread.getGrContext());
+
+ EXPECT_EQ(2, TestUtils::getUsageCount(textureRelease));
+
+ textureRelease->unref(true);
+ AHardwareBuffer_release(buffer);
+}
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java
index 30fae1d..c3e605e 100644
--- a/media/java/android/media/AudioManager.java
+++ b/media/java/android/media/AudioManager.java
@@ -2325,10 +2325,9 @@
return AudioSystem.SUCCESS;
}
- private final Map<Integer, Object> mDevRoleForCapturePresetListeners = new HashMap<>(){{
- put(AudioSystem.DEVICE_ROLE_PREFERRED,
- new DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>());
- }};
+ private final Map<Integer, Object> mDevRoleForCapturePresetListeners = Map.of(
+ AudioSystem.DEVICE_ROLE_PREFERRED,
+ new DevRoleListeners<OnPreferredDevicesForCapturePresetChangedListener>());
private class DevRoleListenerInfo<T> {
final @NonNull Executor mExecutor;
@@ -6483,15 +6482,17 @@
// AudioPort implementation
//
- static final int AUDIOPORT_GENERATION_INIT = 0;
- static Integer sAudioPortGeneration = new Integer(AUDIOPORT_GENERATION_INIT);
- static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>();
- static ArrayList<AudioPort> sPreviousAudioPortsCached = new ArrayList<AudioPort>();
- static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>();
+ private static final int AUDIOPORT_GENERATION_INIT = 0;
+ private static Object sAudioPortGenerationLock = new Object();
+ @GuardedBy("sAudioPortGenerationLock")
+ private static int sAudioPortGeneration = AUDIOPORT_GENERATION_INIT;
+ private static ArrayList<AudioPort> sAudioPortsCached = new ArrayList<AudioPort>();
+ private static ArrayList<AudioPort> sPreviousAudioPortsCached = new ArrayList<AudioPort>();
+ private static ArrayList<AudioPatch> sAudioPatchesCached = new ArrayList<AudioPatch>();
static int resetAudioPortGeneration() {
int generation;
- synchronized (sAudioPortGeneration) {
+ synchronized (sAudioPortGenerationLock) {
generation = sAudioPortGeneration;
sAudioPortGeneration = AUDIOPORT_GENERATION_INIT;
}
@@ -6501,7 +6502,7 @@
static int updateAudioPortCache(ArrayList<AudioPort> ports, ArrayList<AudioPatch> patches,
ArrayList<AudioPort> previousPorts) {
sAudioPortEventHandler.init();
- synchronized (sAudioPortGeneration) {
+ synchronized (sAudioPortGenerationLock) {
if (sAudioPortGeneration == AUDIOPORT_GENERATION_INIT) {
int[] patchGeneration = new int[1];
diff --git a/media/java/android/media/AudioMetadata.java b/media/java/android/media/AudioMetadata.java
index ca175b4..0f962f9 100644
--- a/media/java/android/media/AudioMetadata.java
+++ b/media/java/android/media/AudioMetadata.java
@@ -30,6 +30,7 @@
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -446,14 +447,13 @@
// BaseMap is corresponding to audio_utils::metadata::Data
private static final int AUDIO_METADATA_OBJ_TYPE_BASEMAP = 6;
- private static final HashMap<Class, Integer> AUDIO_METADATA_OBJ_TYPES = new HashMap<>() {{
- put(Integer.class, AUDIO_METADATA_OBJ_TYPE_INT);
- put(Long.class, AUDIO_METADATA_OBJ_TYPE_LONG);
- put(Float.class, AUDIO_METADATA_OBJ_TYPE_FLOAT);
- put(Double.class, AUDIO_METADATA_OBJ_TYPE_DOUBLE);
- put(String.class, AUDIO_METADATA_OBJ_TYPE_STRING);
- put(BaseMap.class, AUDIO_METADATA_OBJ_TYPE_BASEMAP);
- }};
+ private static final Map<Class, Integer> AUDIO_METADATA_OBJ_TYPES = Map.of(
+ Integer.class, AUDIO_METADATA_OBJ_TYPE_INT,
+ Long.class, AUDIO_METADATA_OBJ_TYPE_LONG,
+ Float.class, AUDIO_METADATA_OBJ_TYPE_FLOAT,
+ Double.class, AUDIO_METADATA_OBJ_TYPE_DOUBLE,
+ String.class, AUDIO_METADATA_OBJ_TYPE_STRING,
+ BaseMap.class, AUDIO_METADATA_OBJ_TYPE_BASEMAP);
private static final Charset AUDIO_METADATA_CHARSET = StandardCharsets.UTF_8;
@@ -634,8 +634,8 @@
* Datum corresponds to Object
****************************************************************************************/
- private static final HashMap<Integer, DataPackage<?>> DATA_PACKAGES = new HashMap<>() {{
- put(AUDIO_METADATA_OBJ_TYPE_INT, new DataPackage<Integer>() {
+ private static final Map<Integer, DataPackage<?>> DATA_PACKAGES = Map.of(
+ AUDIO_METADATA_OBJ_TYPE_INT, new DataPackage<Integer>() {
@Override
@Nullable
public Integer unpack(ByteBuffer buffer) {
@@ -647,8 +647,8 @@
output.putInt(obj);
return true;
}
- });
- put(AUDIO_METADATA_OBJ_TYPE_LONG, new DataPackage<Long>() {
+ },
+ AUDIO_METADATA_OBJ_TYPE_LONG, new DataPackage<Long>() {
@Override
@Nullable
public Long unpack(ByteBuffer buffer) {
@@ -660,8 +660,8 @@
output.putLong(obj);
return true;
}
- });
- put(AUDIO_METADATA_OBJ_TYPE_FLOAT, new DataPackage<Float>() {
+ },
+ AUDIO_METADATA_OBJ_TYPE_FLOAT, new DataPackage<Float>() {
@Override
@Nullable
public Float unpack(ByteBuffer buffer) {
@@ -673,8 +673,8 @@
output.putFloat(obj);
return true;
}
- });
- put(AUDIO_METADATA_OBJ_TYPE_DOUBLE, new DataPackage<Double>() {
+ },
+ AUDIO_METADATA_OBJ_TYPE_DOUBLE, new DataPackage<Double>() {
@Override
@Nullable
public Double unpack(ByteBuffer buffer) {
@@ -686,8 +686,8 @@
output.putDouble(obj);
return true;
}
- });
- put(AUDIO_METADATA_OBJ_TYPE_STRING, new DataPackage<String>() {
+ },
+ AUDIO_METADATA_OBJ_TYPE_STRING, new DataPackage<String>() {
@Override
@Nullable
public String unpack(ByteBuffer buffer) {
@@ -713,9 +713,9 @@
output.put(valueArr);
return true;
}
- });
- put(AUDIO_METADATA_OBJ_TYPE_BASEMAP, new BaseMapPackage());
- }};
+ },
+ AUDIO_METADATA_OBJ_TYPE_BASEMAP, new BaseMapPackage());
+
// ObjectPackage is a special case that it is expected to unpack audio_utils::metadata::Datum,
// which contains data type and data size besides the payload for the data.
private static final ObjectPackage OBJECT_PACKAGE = new ObjectPackage();
diff --git a/media/java/android/media/AudioSystem.java b/media/java/android/media/AudioSystem.java
index 18135f2..b7282218 100644
--- a/media/java/android/media/AudioSystem.java
+++ b/media/java/android/media/AudioSystem.java
@@ -431,6 +431,18 @@
return "AUDIO_FORMAT_APTX_TWSP";
case /* AUDIO_FORMAT_LC3 */ 0x2B000000:
return "AUDIO_FORMAT_LC3";
+ case /* AUDIO_FORMAT_MPEGH */ 0x2C000000:
+ return "AUDIO_FORMAT_MPEGH";
+ case /* AUDIO_FORMAT_IEC60958 */ 0x2D000000:
+ return "AUDIO_FORMAT_IEC60958";
+ case /* AUDIO_FORMAT_DTS_UHD */ 0x2E000000:
+ return "AUDIO_FORMAT_DTS_UHD";
+ case /* AUDIO_FORMAT_DRA */ 0x2F000000:
+ return "AUDIO_FORMAT_DRA";
+ case /* AUDIO_FORMAT_APTX_ADAPTIVE_QLEA */ 0x30000000:
+ return "AUDIO_FORMAT_APTX_ADAPTIVE_QLEA";
+ case /* AUDIO_FORMAT_APTX_ADAPTIVE_R4 */ 0x31000000:
+ return "AUDIO_FORMAT_APTX_ADAPTIVE_R4";
/* Aliases */
case /* AUDIO_FORMAT_PCM_16_BIT */ 0x1:
@@ -503,10 +515,14 @@
return "AUDIO_FORMAT_MAT_2_0"; // (MAT | MAT_SUB_2_0)
case /* AUDIO_FORMAT_MAT_2_1 */ 0x24000003:
return "AUDIO_FORMAT_MAT_2_1"; // (MAT | MAT_SUB_2_1)
- case /* AUDIO_FORMAT_DTS_UHD */ 0x2E000000:
- return "AUDIO_FORMAT_DTS_UHD";
- case /* AUDIO_FORMAT_DRA */ 0x2F000000:
- return "AUDIO_FORMAT_DRA";
+ case /* AUDIO_FORMAT_MPEGH_SUB_BL_L3 */ 0x2C000013:
+ return "AUDIO_FORMAT_MPEGH_SUB_BL_L3";
+ case /* AUDIO_FORMAT_MPEGH_SUB_BL_L4 */ 0x2C000014:
+ return "AUDIO_FORMAT_MPEGH_SUB_BL_L4";
+ case /* AUDIO_FORMAT_MPEGH_SUB_LC_L3 */ 0x2C000023:
+ return "AUDIO_FORMAT_MPEGH_SUB_LC_L3";
+ case /* AUDIO_FORMAT_MPEGH_SUB_LC_L4 */ 0x2C000024:
+ return "AUDIO_FORMAT_MPEGH_SUB_LC_L4";
default:
return "AUDIO_FORMAT_(" + audioFormat + ")";
}
@@ -2400,4 +2416,3 @@
*/
final static int NATIVE_EVENT_ROUTING_CHANGE = 1000;
}
-
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index 85cd342..d51f1e1 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -48,8 +48,8 @@
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.NioUtils;
-import java.util.HashMap;
import java.util.LinkedList;
+import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
@@ -1867,26 +1867,24 @@
}
// General pair map
- private static final HashMap<String, Integer> CHANNEL_PAIR_MAP = new HashMap<>() {{
- put("front", AudioFormat.CHANNEL_OUT_FRONT_LEFT
- | AudioFormat.CHANNEL_OUT_FRONT_RIGHT);
- put("back", AudioFormat.CHANNEL_OUT_BACK_LEFT
- | AudioFormat.CHANNEL_OUT_BACK_RIGHT);
- put("front of center", AudioFormat.CHANNEL_OUT_FRONT_LEFT_OF_CENTER
- | AudioFormat.CHANNEL_OUT_FRONT_RIGHT_OF_CENTER);
- put("side", AudioFormat.CHANNEL_OUT_SIDE_LEFT
- | AudioFormat.CHANNEL_OUT_SIDE_RIGHT);
- put("top front", AudioFormat.CHANNEL_OUT_TOP_FRONT_LEFT
- | AudioFormat.CHANNEL_OUT_TOP_FRONT_RIGHT);
- put("top back", AudioFormat.CHANNEL_OUT_TOP_BACK_LEFT
- | AudioFormat.CHANNEL_OUT_TOP_BACK_RIGHT);
- put("top side", AudioFormat.CHANNEL_OUT_TOP_SIDE_LEFT
- | AudioFormat.CHANNEL_OUT_TOP_SIDE_RIGHT);
- put("bottom front", AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_LEFT
- | AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_RIGHT);
- put("front wide", AudioFormat.CHANNEL_OUT_FRONT_WIDE_LEFT
- | AudioFormat.CHANNEL_OUT_FRONT_WIDE_RIGHT);
- }};
+ private static final Map<String, Integer> CHANNEL_PAIR_MAP = Map.of(
+ "front", AudioFormat.CHANNEL_OUT_FRONT_LEFT
+ | AudioFormat.CHANNEL_OUT_FRONT_RIGHT,
+ "back", AudioFormat.CHANNEL_OUT_BACK_LEFT
+ | AudioFormat.CHANNEL_OUT_BACK_RIGHT,
+ "front of center", AudioFormat.CHANNEL_OUT_FRONT_LEFT_OF_CENTER
+ | AudioFormat.CHANNEL_OUT_FRONT_RIGHT_OF_CENTER,
+ "side", AudioFormat.CHANNEL_OUT_SIDE_LEFT | AudioFormat.CHANNEL_OUT_SIDE_RIGHT,
+ "top front", AudioFormat.CHANNEL_OUT_TOP_FRONT_LEFT
+ | AudioFormat.CHANNEL_OUT_TOP_FRONT_RIGHT,
+ "top back", AudioFormat.CHANNEL_OUT_TOP_BACK_LEFT
+ | AudioFormat.CHANNEL_OUT_TOP_BACK_RIGHT,
+ "top side", AudioFormat.CHANNEL_OUT_TOP_SIDE_LEFT
+ | AudioFormat.CHANNEL_OUT_TOP_SIDE_RIGHT,
+ "bottom front", AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_LEFT
+ | AudioFormat.CHANNEL_OUT_BOTTOM_FRONT_RIGHT,
+ "front wide", AudioFormat.CHANNEL_OUT_FRONT_WIDE_LEFT
+ | AudioFormat.CHANNEL_OUT_FRONT_WIDE_RIGHT);
/**
* Convenience method to check that the channel configuration (a.k.a channel mask) is supported
@@ -1924,7 +1922,7 @@
return false;
}
// Check all pairs to see that they are matched (front duplicated here).
- for (HashMap.Entry<String, Integer> e : CHANNEL_PAIR_MAP.entrySet()) {
+ for (Map.Entry<String, Integer> e : CHANNEL_PAIR_MAP.entrySet()) {
final int positionPair = e.getValue();
if ((channelConfig & positionPair) != 0
&& (channelConfig & positionPair) != positionPair) {
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index e18642c..62d14e1 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -70,6 +70,7 @@
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
@@ -4833,12 +4834,13 @@
for (int i = 1; i < entryValues.length; ++i) {
final Pair<Integer, Integer> guessDataFormat = guessDataFormat(entryValues[i]);
int first = -1, second = -1;
- if (guessDataFormat.first == dataFormat.first
- || guessDataFormat.second == dataFormat.first) {
+ if (Objects.equals(guessDataFormat.first, dataFormat.first)
+ || Objects.equals(guessDataFormat.second, dataFormat.first)) {
first = dataFormat.first;
}
- if (dataFormat.second != -1 && (guessDataFormat.first == dataFormat.second
- || guessDataFormat.second == dataFormat.second)) {
+ if (dataFormat.second != -1
+ && (Objects.equals(guessDataFormat.first, dataFormat.second)
+ || Objects.equals(guessDataFormat.second, dataFormat.second))) {
second = dataFormat.second;
}
if (first == -1 && second == -1) {
diff --git a/media/java/android/media/MediaHTTPService.java b/media/java/android/media/MediaHTTPService.java
index 3008067..2342a42 100644
--- a/media/java/android/media/MediaHTTPService.java
+++ b/media/java/android/media/MediaHTTPService.java
@@ -21,6 +21,8 @@
import android.os.IBinder;
import android.util.Log;
+import com.android.internal.annotations.GuardedBy;
+
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookieStore;
@@ -31,7 +33,9 @@
public class MediaHTTPService extends IMediaHTTPService.Stub {
private static final String TAG = "MediaHTTPService";
@Nullable private List<HttpCookie> mCookies;
- private Boolean mCookieStoreInitialized = new Boolean(false);
+ private final Object mCookieStoreInitializedLock = new Object();
+ @GuardedBy("mCookieStoreInitializedLock")
+ private boolean mCookieStoreInitialized = false;
public MediaHTTPService(@Nullable List<HttpCookie> cookies) {
mCookies = cookies;
@@ -40,7 +44,7 @@
public IMediaHTTPConnection makeHTTPConnection() {
- synchronized (mCookieStoreInitialized) {
+ synchronized (mCookieStoreInitializedLock) {
// Only need to do it once for all connections
if ( !mCookieStoreInitialized ) {
CookieHandler cookieHandler = CookieHandler.getDefault();
@@ -78,8 +82,8 @@
Log.v(TAG, "makeHTTPConnection(" + this + "): cookieHandler: " + cookieHandler +
" Cookies: " + mCookies);
- } // mCookieStoreInitialized
- } // synchronized
+ }
+ }
return new MediaHTTPConnection();
}
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 737bc34..a9cbffb 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -2473,6 +2473,8 @@
*
* @see android.media.MediaPlayer#getTrackInfo
*/
+ // The creator needs to be pulic, which requires removing the @UnsupportedAppUsage
+ @SuppressWarnings("ParcelableCreator")
static public class TrackInfo implements Parcelable {
/**
* Gets the track type.
diff --git a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
index e72026a..1aae8f4 100644
--- a/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
+++ b/media/java/android/media/tv/tuner/dvr/DvrRecorder.java
@@ -27,6 +27,7 @@
import android.os.Process;
import android.util.Log;
+import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.FrameworkStatsLog;
import java.util.concurrent.Executor;
@@ -47,7 +48,9 @@
private static int sInstantId = 0;
private int mSegmentId = 0;
private int mOverflow;
- private Boolean mIsStopped = true;
+ private final Object mIsStoppedLock = new Object();
+ @GuardedBy("mIsStoppedLock")
+ private boolean mIsStopped = true;
private final Object mListenerLock = new Object();
private native int nativeAttachFilter(Filter filter);
@@ -147,7 +150,7 @@
.write(FrameworkStatsLog.TV_TUNER_DVR_STATUS, mUserId,
FrameworkStatsLog.TV_TUNER_DVR_STATUS__TYPE__RECORD,
FrameworkStatsLog.TV_TUNER_DVR_STATUS__STATE__STARTED, mSegmentId, 0);
- synchronized (mIsStopped) {
+ synchronized (mIsStoppedLock) {
int result = nativeStartDvr();
if (result == Tuner.RESULT_SUCCESS) {
mIsStopped = false;
@@ -170,7 +173,7 @@
.write(FrameworkStatsLog.TV_TUNER_DVR_STATUS, mUserId,
FrameworkStatsLog.TV_TUNER_DVR_STATUS__TYPE__RECORD,
FrameworkStatsLog.TV_TUNER_DVR_STATUS__STATE__STOPPED, mSegmentId, mOverflow);
- synchronized (mIsStopped) {
+ synchronized (mIsStoppedLock) {
int result = nativeStopDvr();
if (result == Tuner.RESULT_SUCCESS) {
mIsStopped = true;
@@ -188,7 +191,7 @@
*/
@Result
public int flush() {
- synchronized (mIsStopped) {
+ synchronized (mIsStoppedLock) {
if (mIsStopped) {
return nativeFlushDvr();
}
diff --git a/media/java/android/mtp/MtpPropertyGroup.java b/media/java/android/mtp/MtpPropertyGroup.java
index aff2e1b4..89e5e0d 100644
--- a/media/java/android/mtp/MtpPropertyGroup.java
+++ b/media/java/android/mtp/MtpPropertyGroup.java
@@ -230,7 +230,7 @@
case MtpConstants.PROPERTY_PERSISTENT_UID:
// The persistent uid must be unique and never reused among all objects,
// and remain the same between sessions.
- long puid = (object.getPath().toString().hashCode() << 32)
+ long puid = (((long) object.getPath().toString().hashCode()) << 32)
+ object.getModifiedTime();
list.append(id, property.code, property.type, puid);
break;
diff --git a/media/mca/effect/java/android/media/effect/EffectFactory.java b/media/mca/effect/java/android/media/effect/EffectFactory.java
index f6fcba7..cbb2736 100644
--- a/media/mca/effect/java/android/media/effect/EffectFactory.java
+++ b/media/mca/effect/java/android/media/effect/EffectFactory.java
@@ -486,11 +486,9 @@
private Effect instantiateEffect(Class effectClass, String name) {
// Make sure this is an Effect subclass
- try {
- effectClass.asSubclass(Effect.class);
- } catch (ClassCastException e) {
+ if (!Effect.class.isAssignableFrom(effectClass)) {
throw new IllegalArgumentException("Attempting to allocate effect '" + effectClass
- + "' which is not a subclass of Effect!", e);
+ + "' which is not a subclass of Effect!");
}
// Look for the correct constructor
diff --git a/media/mca/filterfw/java/android/filterfw/core/Filter.java b/media/mca/filterfw/java/android/filterfw/core/Filter.java
index a608ef5..e82c046 100644
--- a/media/mca/filterfw/java/android/filterfw/core/Filter.java
+++ b/media/mca/filterfw/java/android/filterfw/core/Filter.java
@@ -90,9 +90,7 @@
return false;
}
// Then make sure it's a subclass of Filter.
- try {
- filterClass.asSubclass(Filter.class);
- } catch (ClassCastException e) {
+ if (!Filter.class.isAssignableFrom(filterClass)) {
return false;
}
return true;
diff --git a/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java b/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java
index 779df99..736e511 100644
--- a/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java
+++ b/media/mca/filterfw/java/android/filterfw/core/FilterFactory.java
@@ -112,9 +112,7 @@
public Filter createFilterByClass(Class filterClass, String filterName) {
// Make sure this is a Filter subclass
- try {
- filterClass.asSubclass(Filter.class);
- } catch (ClassCastException e) {
+ if (!Filter.class.isAssignableFrom(filterClass)) {
throw new IllegalArgumentException("Attempting to allocate class '" + filterClass
+ "' which is not a subclass of Filter!");
}
diff --git a/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java b/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java
index 8cf9a13..6ff1885 100644
--- a/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java
+++ b/media/mca/filterfw/java/android/filterfw/core/KeyValueMap.java
@@ -55,12 +55,12 @@
public int getInt(String key) {
Object result = get(key);
- return result != null ? (Integer)result : null;
+ return result != null ? (Integer) result : 0;
}
public float getFloat(String key) {
Object result = get(key);
- return result != null ? (Float)result : null;
+ return result != null ? (Float) result : 0;
}
@Override
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
index c5281657..8c05725 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
@@ -296,7 +296,7 @@
mMemWriter.write("End Memory :" + mEndMemory + "\n");
}
} catch (Exception e) {
- e.toString();
+ // TODO
}
}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java
index 39add7e..c814eba 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/CameraMetadataTest.java
@@ -264,8 +264,14 @@
builder.append("**");
}
- if (elem instanceof Number) {
- builder.append(String.format("%x", elem));
+ if (elem instanceof Byte) {
+ builder.append(String.format("%x", (Byte) elem));
+ } else if (elem instanceof Short) {
+ builder.append(String.format("%x", (Short) elem));
+ } else if (elem instanceof Integer) {
+ builder.append(String.format("%x", (Integer) elem));
+ } else if (elem instanceof Long) {
+ builder.append(String.format("%x", (Long) elem));
} else {
builder.append(elem);
}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java
index fd1c2d3..37dd4b5 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/MediaPlayerGetCurrentPositionStateUnitTest.java
@@ -18,7 +18,7 @@
import android.media.MediaPlayer;
import android.test.AndroidTestCase;
-import android.test.suitebuilder.annotation.LargeTest;;
+import android.test.suitebuilder.annotation.LargeTest;
/**
* Unit test class to test the set of valid and invalid states that
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
index a3aa010..77f37d0 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceActivity.java
@@ -193,6 +193,7 @@
initUI();
}
+ @SuppressWarnings("MissingSuperCall") // TODO: Fix me
@Override
protected void onNewIntent(Intent intent) {
// Handle another incoming request (while we are not done with the original - mRequest -
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java
index 93e6271..3029d10 100644
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/google/CloudPrintPlugin.java
@@ -55,18 +55,15 @@
private static final String PRIVET_SERVICE = "_privet._tcp";
/** The required mDNS service types */
- private static final Set<String> PRINTER_SERVICE_TYPE = new HashSet<String>() {{
- // Not checking _printer_._sub
- add(PRIVET_SERVICE);
- }};
+ private static final Set<String> PRINTER_SERVICE_TYPE = Set.of(
+ PRIVET_SERVICE); // Not checking _printer_._sub
/** All possible connection states */
- private static final Set<String> POSSIBLE_CONNECTION_STATES = new HashSet<String>() {{
- add("online");
- add("offline");
- add("connecting");
- add("not-configured");
- }};
+ private static final Set<String> POSSIBLE_CONNECTION_STATES = Set.of(
+ "online",
+ "offline",
+ "connecting",
+ "not-configured");
private static final byte SUPPORTED_TXTVERS = '1';
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java
index 34e7e3d..0c5de27 100644
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/mdnsFilter/MDNSFilterPlugin.java
@@ -37,9 +37,7 @@
public class MDNSFilterPlugin implements PrintServicePlugin {
/** The mDNS service types supported */
- private static final Set<String> PRINTER_SERVICE_TYPES = new HashSet<String>() {{
- add("_ipp._tcp");
- }};
+ private static final Set<String> PRINTER_SERVICE_TYPES = Set.of("_ipp._tcp");
/**
* The printer filter for {@link MDNSFilteredDiscovery} passing only mDNS results
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java
index d03bb1d..b9983c3 100644
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterMopria.java
@@ -23,7 +23,6 @@
import com.android.printservice.recommendation.util.MDNSFilteredDiscovery;
import com.android.printservice.recommendation.util.MDNSUtils;
-import java.util.HashSet;
import java.util.Set;
/**
@@ -32,10 +31,7 @@
class PrinterFilterMopria implements MDNSFilteredDiscovery.PrinterFilter {
private static final String TAG = "PrinterFilterMopria";
- static final Set<String> MOPRIA_MDNS_SERVICES = new HashSet<String>() {{
- add("_ipp._tcp");
- add("_ipps._tcp");
- }};
+ static final Set<String> MOPRIA_MDNS_SERVICES = Set.of("_ipp._tcp", "_ipps._tcp");
private static final String PDL__PDF = "application/pdf";
private static final String PDL__PCLM = "application/PCLm";
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java
index b9b9098..680dd84 100644
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/PrinterFilterSamsung.java
@@ -25,7 +25,6 @@
import com.android.printservice.recommendation.util.MDNSFilteredDiscovery;
import com.android.printservice.recommendation.util.MDNSUtils;
-import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -36,9 +35,7 @@
class PrinterFilterSamsung implements MDNSFilteredDiscovery.PrinterFilter {
private static final String TAG = "PrinterFilterSamsung";
- static final Set<String> SAMSUNG_MDNS_SERVICES = new HashSet<String>() {{
- add("_pdl-datastream._tcp");
- }};
+ static final Set<String> SAMSUNG_MDNS_SERVICES = Set.of("_pdl-datastream._tcp");
private static final String[] NOT_SUPPORTED_MODELS = new String[]{
"SCX-5x15",
@@ -57,9 +54,7 @@
private static final String ATTR_PRODUCT = "product";
private static final String ATTR_TY = "ty";
- private static Set<String> SAMUNG_VENDOR_SET = new HashSet<String>() {{
- add("samsung");
- }};
+ private static final Set<String> SAMUNG_VENDOR_SET = Set.of("samsung");
@Override
public boolean matchesCriteria(NsdServiceInfo nsdServiceInfo) {
diff --git a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java
index ae1bdce..cbd5833 100644
--- a/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java
+++ b/packages/PrintRecommendationService/src/com/android/printservice/recommendation/plugin/samsung/SamsungRecommendationPlugin.java
@@ -29,10 +29,11 @@
import java.util.Set;
public class SamsungRecommendationPlugin implements PrintServicePlugin {
- private static final Set<String> ALL_MDNS_SERVICES = new HashSet<String>() {{
- addAll(PrinterFilterMopria.MOPRIA_MDNS_SERVICES);
- addAll(PrinterFilterSamsung.SAMSUNG_MDNS_SERVICES);
- }};
+ private static final Set<String> ALL_MDNS_SERVICES = new HashSet<String>();
+ static {
+ ALL_MDNS_SERVICES.addAll(PrinterFilterMopria.MOPRIA_MDNS_SERVICES);
+ ALL_MDNS_SERVICES.addAll(PrinterFilterSamsung.SAMSUNG_MDNS_SERVICES);
+ }
private final @NonNull Context mContext;
private final @NonNull MDNSFilteredDiscovery mMDNSFilteredDiscovery;
diff --git a/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java b/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java
index 00b3736..b0aa8f1 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/widget/PrintContentView.java
@@ -402,7 +402,7 @@
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
- if ((isOptionsClosed() || isOptionsClosed()) && dy <= 0) {
+ if (isOptionsClosed() && dy <= 0) {
return;
}
diff --git a/packages/SettingsLib/OWNERS b/packages/SettingsLib/OWNERS
index 8eafbdf..24bb3a7 100644
--- a/packages/SettingsLib/OWNERS
+++ b/packages/SettingsLib/OWNERS
@@ -3,9 +3,9 @@
edgarwang@google.com
emilychuang@google.com
evanlaird@google.com
+hanxu@google.com
juliacr@google.com
leifhendrik@google.com
-tmfang@google.com
virgild@google.com
# Exempt resource files (because they are in a flat directory and too hard to manage via OWNERS)
diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java
index 6ce72bb..3af64e2 100644
--- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java
+++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/BluetoothDiscoverableTimeoutReceiver.java
@@ -82,4 +82,4 @@
Log.e(TAG, "localBluetoothAdapter is NULL!!");
}
}
-};
+}
diff --git a/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java b/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java
index 23195af..00f1c01 100644
--- a/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java
+++ b/packages/SystemUI/src/com/android/keyguard/AdminSecondaryLockScreenController.java
@@ -33,6 +33,7 @@
import android.view.ViewGroup;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
import com.android.keyguard.dagger.KeyguardBouncerScope;
import com.android.systemui.dagger.qualifiers.Main;
@@ -208,7 +209,7 @@
hide();
if (mKeyguardCallback != null) {
mKeyguardCallback.dismiss(/* securityVerified= */ true, userId,
- /* bypassSecondaryLockScreen= */true);
+ /* bypassSecondaryLockScreen= */true, SecurityMode.Invalid);
}
}
}
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
index eb418ff..b8fcb10 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardAbsKeyInputViewController.java
@@ -179,7 +179,7 @@
if (dismissKeyguard) {
mDismissing = true;
mLatencyTracker.onActionStart(LatencyTracker.ACTION_LOCKSCREEN_UNLOCK);
- getKeyguardSecurityCallback().dismiss(true, userId);
+ getKeyguardSecurityCallback().dismiss(true, userId, getSecurityMode());
}
} else {
if (isValidPassword) {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
index 12fa401..befd59b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardHostViewController.java
@@ -90,7 +90,7 @@
Log.i(TAG, "TrustAgent dismissed Keyguard.");
}
mSecurityCallback.dismiss(false /* authenticated */, userId,
- /* bypassSecondaryLockScreen */ false);
+ /* bypassSecondaryLockScreen */ false, SecurityMode.Invalid);
} else {
mViewMediatorCallback.playTrustedSound();
}
@@ -102,9 +102,9 @@
@Override
public boolean dismiss(boolean authenticated, int targetUserId,
- boolean bypassSecondaryLockScreen) {
+ boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) {
return mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish(
- authenticated, targetUserId, bypassSecondaryLockScreen);
+ authenticated, targetUserId, bypassSecondaryLockScreen, expectedSecurityMode);
}
@Override
@@ -212,7 +212,8 @@
* @return True if the keyguard is done.
*/
public boolean dismiss(int targetUserId) {
- return mSecurityCallback.dismiss(false, targetUserId, false);
+ return mSecurityCallback.dismiss(false, targetUserId, false,
+ getCurrentSecurityMode());
}
/**
@@ -355,10 +356,10 @@
}
public boolean handleBackKey() {
- if (mKeyguardSecurityContainerController.getCurrentSecurityMode()
- != SecurityMode.None) {
+ SecurityMode securityMode = mKeyguardSecurityContainerController.getCurrentSecurityMode();
+ if (securityMode != SecurityMode.None) {
mKeyguardSecurityContainerController.dismiss(
- false, KeyguardUpdateMonitor.getCurrentUser());
+ false, KeyguardUpdateMonitor.getCurrentUser(), securityMode);
return true;
}
return false;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
index 98ac640..87300c3 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardInputViewController.java
@@ -59,10 +59,11 @@
return false;
}
@Override
- public void dismiss(boolean securityVerified, int targetUserId) { }
+ public void dismiss(boolean securityVerified, int targetUserId,
+ SecurityMode expectedSecurityMode) { }
@Override
public void dismiss(boolean authenticated, int targetId,
- boolean bypassSecondaryLockScreen) { }
+ boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) { }
@Override
public void onUserInput() { }
@Override
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
index 39c3949..1a59b82 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardPatternViewController.java
@@ -171,7 +171,7 @@
if (dismissKeyguard) {
mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);
mLatencyTracker.onActionStart(LatencyTracker.ACTION_LOCKSCREEN_UNLOCK);
- getKeyguardSecurityCallback().dismiss(true, userId);
+ getKeyguardSecurityCallback().dismiss(true, userId, SecurityMode.Pattern);
}
} else {
mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java
index e384727..bc72f79 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityCallback.java
@@ -15,14 +15,17 @@
*/
package com.android.keyguard;
+import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
+
public interface KeyguardSecurityCallback {
/**
* Dismiss the given security screen.
* @param securityVerified true if the user correctly entered credentials for the given screen.
* @param targetUserId a user that needs to be the foreground user at the dismissal completion.
+ * @param expectedSecurityMode The security mode that is invoking this dismiss.
*/
- void dismiss(boolean securityVerified, int targetUserId);
+ void dismiss(boolean securityVerified, int targetUserId, SecurityMode expectedSecurityMode);
/**
* Dismiss the given security screen.
@@ -30,8 +33,10 @@
* @param targetUserId a user that needs to be the foreground user at the dismissal completion.
* @param bypassSecondaryLockScreen true if the user can bypass the secondary lock screen,
* if any, during this dismissal.
+ * @param expectedSecurityMode The security mode that is invoking this dismiss.
*/
- void dismiss(boolean securityVerified, int targetUserId, boolean bypassSecondaryLockScreen);
+ void dismiss(boolean securityVerified, int targetUserId, boolean bypassSecondaryLockScreen,
+ SecurityMode expectedSecurityMode);
/**
* Manually report user activity to keep the device awake.
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
index cce516d..12bb47b 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainer.java
@@ -233,7 +233,12 @@
// Used to notify the container when something interesting happens.
public interface SecurityCallback {
- boolean dismiss(boolean authenticated, int targetUserId, boolean bypassSecondaryLockScreen);
+ /**
+ * Potentially dismiss the current security screen, after validating that all device
+ * security has been unlocked. Otherwise show the next screen.
+ */
+ boolean dismiss(boolean authenticated, int targetUserId, boolean bypassSecondaryLockScreen,
+ SecurityMode expectedSecurityMode);
void userActivity();
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
index 19a2d9e..2b9553d 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSecurityContainerController.java
@@ -153,14 +153,17 @@
}
@Override
- public void dismiss(boolean authenticated, int targetId) {
- dismiss(authenticated, targetId, /* bypassSecondaryLockScreen */ false);
+ public void dismiss(boolean authenticated, int targetId,
+ SecurityMode expectedSecurityMode) {
+ dismiss(authenticated, targetId, /* bypassSecondaryLockScreen */ false,
+ expectedSecurityMode);
}
@Override
public void dismiss(boolean authenticated, int targetId,
- boolean bypassSecondaryLockScreen) {
- mSecurityCallback.dismiss(authenticated, targetId, bypassSecondaryLockScreen);
+ boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) {
+ mSecurityCallback.dismiss(authenticated, targetId, bypassSecondaryLockScreen,
+ expectedSecurityMode);
}
public boolean isVerifyUnlockOnly() {
@@ -350,8 +353,13 @@
return mCurrentSecurityMode;
}
- public void dismiss(boolean authenticated, int targetUserId) {
- mKeyguardSecurityCallback.dismiss(authenticated, targetUserId);
+ /**
+ * Potentially dismiss the current security screen, after validating that all device
+ * security has been unlocked. Otherwise show the next screen.
+ */
+ public void dismiss(boolean authenticated, int targetUserId,
+ SecurityMode expectedSecurityMode) {
+ mKeyguardSecurityCallback.dismiss(authenticated, targetUserId, expectedSecurityMode);
}
public void reset() {
@@ -410,12 +418,21 @@
* completion.
* @param bypassSecondaryLockScreen true if the user is allowed to bypass the secondary
* secondary lock screen requirement, if any.
+ * @param expectedSecurityMode SecurityMode that is invoking this request. SecurityMode.Invalid
+ * indicates that no check should be done
* @return true if keyguard is done
*/
public boolean showNextSecurityScreenOrFinish(boolean authenticated, int targetUserId,
- boolean bypassSecondaryLockScreen) {
+ boolean bypassSecondaryLockScreen, SecurityMode expectedSecurityMode) {
if (DEBUG) Log.d(TAG, "showNextSecurityScreenOrFinish(" + authenticated + ")");
+ if (expectedSecurityMode != SecurityMode.Invalid
+ && expectedSecurityMode != getCurrentSecurityMode()) {
+ Log.w(TAG, "Attempted to invoke showNextSecurityScreenOrFinish with securityMode "
+ + expectedSecurityMode + ", but current mode is " + getCurrentSecurityMode());
+ return false;
+ }
+
boolean finish = false;
boolean strongAuth = false;
int eventSubtype = -1;
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java
index e337123..821b2e1 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinViewController.java
@@ -170,7 +170,8 @@
mRemainingAttempts = -1;
mShowDefaultMessage = true;
getKeyguardSecurityCallback().dismiss(
- true, KeyguardUpdateMonitor.getCurrentUser());
+ true, KeyguardUpdateMonitor.getCurrentUser(),
+ SecurityMode.SimPin);
} else {
mShowDefaultMessage = false;
if (result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT) {
diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java
index 47aa43b..203f9b6 100644
--- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java
+++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukViewController.java
@@ -69,7 +69,8 @@
if (simState == TelephonyManager.SIM_STATE_READY) {
mRemainingAttempts = -1;
mShowDefaultMessage = true;
- getKeyguardSecurityCallback().dismiss(true, KeyguardUpdateMonitor.getCurrentUser());
+ getKeyguardSecurityCallback().dismiss(true, KeyguardUpdateMonitor.getCurrentUser(),
+ SecurityMode.SimPuk);
} else {
resetState();
}
@@ -278,7 +279,8 @@
mShowDefaultMessage = true;
getKeyguardSecurityCallback().dismiss(
- true, KeyguardUpdateMonitor.getCurrentUser());
+ true, KeyguardUpdateMonitor.getCurrentUser(),
+ SecurityMode.SimPuk);
} else {
mShowDefaultMessage = false;
if (result.getResult() == PinResult.PIN_RESULT_TYPE_INCORRECT) {
diff --git a/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java b/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java
index 18fb423..d9bcb50 100644
--- a/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java
+++ b/packages/SystemUI/src/com/android/systemui/fragments/ExtensionFragmentListener.java
@@ -50,13 +50,12 @@
@Override
public void accept(T extension) {
- try {
- Fragment.class.cast(extension);
+ if (Fragment.class.isInstance(extension)) {
mFragmentHostManager.getExtensionManager().setCurrentExtension(mId, mTag,
mOldClass, extension.getClass().getName(), mExtension.getContext());
mOldClass = extension.getClass().getName();
- } catch (ClassCastException e) {
- Log.e(TAG, extension.getClass().getName() + " must be a Fragment", e);
+ } else {
+ Log.e(TAG, extension.getClass().getName() + " must be a Fragment");
}
mExtension.clearItem(true);
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
index 0783eeec..90bcb0fe 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/KeyguardViewMediator.java
@@ -1641,7 +1641,7 @@
try {
callback.onKeyguardExitResult(true);
} catch (RemoteException e) {
- Slog.w(TAG, "Failed to call onKeyguardExitResult(false)", e);
+ Slog.w(TAG, "Failed to call onKeyguardExitResult(true)", e);
}
} else {
diff --git a/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java b/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java
index 00aa138..7f16a6b 100644
--- a/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/people/PeopleTileViewHelper.java
@@ -1093,7 +1093,7 @@
Pair<Integer, Integer> first = emojiIndices.get(i - 1);
// Check if second emoji starts right after first starts
- if (second.first == first.second) {
+ if (Objects.equals(second.first, first.second)) {
// Check if emojis in sequence are the same
if (Objects.equals(emojiTexts.get(i), emojiTexts.get(i - 1))) {
if (DEBUG) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
index 9fbd5c3..6123663 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/logging/NotificationLogger.java
@@ -56,6 +56,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.concurrent.Executor;
import javax.inject.Inject;
@@ -592,7 +593,7 @@
return;
}
if (loggedExpansionState != null
- && state.mIsExpanded == loggedExpansionState) {
+ && Objects.equals(state.mIsExpanded, loggedExpansionState)) {
return;
}
mLoggedExpansionState.put(key, state.mIsExpanded);
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java
index dffad6c..80385e6 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/AdminSecondaryLockScreenControllerTest.java
@@ -44,6 +44,7 @@
import androidx.test.filters.SmallTest;
+import com.android.keyguard.KeyguardSecurityModel.SecurityMode;
import com.android.systemui.SysuiTestCase;
import org.junit.After;
@@ -190,7 +191,7 @@
private void verifyViewDismissed(SurfaceView v) throws Exception {
verify(mKeyguardSecurityContainer).removeView(v);
- verify(mKeyguardCallback).dismiss(true, TARGET_USER_ID, true);
+ verify(mKeyguardCallback).dismiss(true, TARGET_USER_ID, true, SecurityMode.Invalid);
assertThat(mContext.isBound(mComponentName)).isFalse();
}
}
diff --git a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
index 4d33430..efc9921 100644
--- a/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
+++ b/packages/SystemUI/tests/src/com/android/keyguard/KeyguardSecurityContainerControllerTest.java
@@ -21,7 +21,10 @@
import static com.android.keyguard.KeyguardSecurityContainer.MODE_DEFAULT;
import static com.android.keyguard.KeyguardSecurityContainer.MODE_ONE_HANDED;
+import static com.google.common.truth.Truth.assertThat;
+
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
@@ -69,6 +72,7 @@
@TestableLooper.RunWithLooper()
public class KeyguardSecurityContainerControllerTest extends SysuiTestCase {
private static final int VIEW_WIDTH = 1600;
+ private static final int TARGET_USER_ID = 100;
@Rule
public MockitoRule mRule = MockitoJUnit.rule();
@@ -299,4 +303,42 @@
verify(mUserSwitcherController)
.removeUserSwitchCallback(any(UserSwitcherController.UserSwitchCallback.class));
}
+
+ @Test
+ public void showNextSecurityScreenOrFinish_setsSecurityScreenToPinAfterSimPinUnlock() {
+ // GIVEN the current security method is SimPin
+ when(mKeyguardUpdateMonitor.getUserHasTrust(anyInt())).thenReturn(false);
+ when(mKeyguardUpdateMonitor.getUserUnlockedWithBiometric(TARGET_USER_ID)).thenReturn(false);
+ mKeyguardSecurityContainerController.showSecurityScreen(SecurityMode.SimPin);
+
+ // WHEN a request is made from the SimPin screens to show the next security method
+ when(mKeyguardSecurityModel.getSecurityMode(TARGET_USER_ID)).thenReturn(SecurityMode.PIN);
+ mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish(
+ /* authenticated= */true,
+ TARGET_USER_ID,
+ /* bypassSecondaryLockScreen= */true,
+ SecurityMode.SimPin);
+
+ // THEN the next security method of PIN is set, and the keyguard is not marked as done
+ verify(mSecurityCallback, never()).finish(anyBoolean(), anyInt());
+ assertThat(mKeyguardSecurityContainerController.getCurrentSecurityMode())
+ .isEqualTo(SecurityMode.PIN);
+ }
+
+ @Test
+ public void showNextSecurityScreenOrFinish_ignoresCallWhenSecurityMethodHasChanged() {
+ //GIVEN current security mode has been set to PIN
+ mKeyguardSecurityContainerController.showSecurityScreen(SecurityMode.PIN);
+
+ //WHEN a request comes from SimPin to dismiss the security screens
+ boolean keyguardDone = mKeyguardSecurityContainerController.showNextSecurityScreenOrFinish(
+ /* authenticated= */true,
+ TARGET_USER_ID,
+ /* bypassSecondaryLockScreen= */true,
+ SecurityMode.SimPin);
+
+ //THEN no action has happened, which will not dismiss the security screens
+ assertThat(keyguardDone).isEqualTo(false);
+ verify(mKeyguardUpdateMonitor, never()).getUserHasTrust(anyInt());
+ }
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java
index 7d56339..8a6895e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/screenshot/ImageExporterTest.java
@@ -65,7 +65,7 @@
private static final byte[] EXIF_FILE_TAG = "Exif\u0000\u0000".getBytes(US_ASCII);
private static final ZonedDateTime CAPTURE_TIME =
- ZonedDateTime.of(LocalDateTime.of(2020, 12, 15, 13, 15), ZoneId.of("EST"));
+ ZonedDateTime.of(LocalDateTime.of(2020, 12, 15, 13, 15), ZoneId.of("America/New_York"));
@Test
public void testImageFilename() {
diff --git a/services/appwidget/java/com/android/server/appwidget/AppWidgetXmlUtil.java b/services/appwidget/java/com/android/server/appwidget/AppWidgetXmlUtil.java
index 6a5dcc8..2aca99c 100644
--- a/services/appwidget/java/com/android/server/appwidget/AppWidgetXmlUtil.java
+++ b/services/appwidget/java/com/android/server/appwidget/AppWidgetXmlUtil.java
@@ -111,7 +111,7 @@
info.minWidth = parser.getAttributeInt(null, ATTR_MIN_WIDTH, 0);
info.minHeight = parser.getAttributeInt(null, ATTR_MIN_HEIGHT, 0);
info.minResizeWidth = parser.getAttributeInt(null, ATTR_MIN_RESIZE_WIDTH, 0);
- info.minResizeWidth = parser.getAttributeInt(null, ATTR_MIN_RESIZE_HEIGHT, 0);
+ info.minResizeHeight = parser.getAttributeInt(null, ATTR_MIN_RESIZE_HEIGHT, 0);
info.maxResizeWidth = parser.getAttributeInt(null, ATTR_MAX_RESIZE_WIDTH, 0);
info.maxResizeHeight = parser.getAttributeInt(null, ATTR_MAX_RESIZE_HEIGHT, 0);
info.targetCellWidth = parser.getAttributeInt(null, ATTR_TARGET_CELL_WIDTH, 0);
diff --git a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
index 8525e36..592045c 100644
--- a/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
+++ b/services/autofill/java/com/android/server/autofill/RemoteAugmentedAutofillService.java
@@ -245,6 +245,7 @@
});
}
+ @SuppressWarnings("ReturnValueIgnored")
private void maybeRequestShowInlineSuggestions(int sessionId,
@Nullable InlineSuggestionsRequest request,
@Nullable List<Dataset> inlineSuggestionsData, @Nullable Bundle clientState,
diff --git a/services/backup/java/com/android/server/backup/OperationStorage.java b/services/backup/java/com/android/server/backup/OperationStorage.java
index 466f647..8f73436 100644
--- a/services/backup/java/com/android/server/backup/OperationStorage.java
+++ b/services/backup/java/com/android/server/backup/OperationStorage.java
@@ -153,4 +153,4 @@
* @return a set of operation tokens for operations in that state.
*/
Set<Integer> operationTokensForOpState(@OpState int state);
-};
+}
diff --git a/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java b/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java
index 6908c60..a94167e 100644
--- a/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java
+++ b/services/backup/java/com/android/server/backup/internal/LifecycleOperationStorage.java
@@ -353,4 +353,4 @@
op.callback.handleCancel(cancelAll);
}
}
-};
+}
diff --git a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
index ff1a495..36b82f8 100644
--- a/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
+++ b/services/contentcapture/java/com/android/server/contentcapture/ContentCaptureManagerService.java
@@ -657,7 +657,6 @@
int sessionId, int flags, @NonNull IResultReceiver result) {
Objects.requireNonNull(activityToken);
Objects.requireNonNull(shareableActivityToken);
- Objects.requireNonNull(sessionId);
final int userId = UserHandle.getCallingUserId();
final ActivityPresentationInfo activityPresentationInfo = getAmInternal()
@@ -676,7 +675,6 @@
@Override
public void finishSession(int sessionId) {
- Objects.requireNonNull(sessionId);
final int userId = UserHandle.getCallingUserId();
synchronized (mLock) {
diff --git a/services/core/java/com/android/server/DynamicSystemService.java b/services/core/java/com/android/server/DynamicSystemService.java
index ce0e69c..27215b2 100644
--- a/services/core/java/com/android/server/DynamicSystemService.java
+++ b/services/core/java/com/android/server/DynamicSystemService.java
@@ -77,6 +77,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean startInstallation(String dsuSlot) throws RemoteException {
+ super.startInstallation_enforcePermission();
+
IGsiService service = getGsiService();
mGsiService = service;
// priority from high to low: sysprop -> sdcard -> /data
@@ -124,6 +126,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public int createPartition(String name, long size, boolean readOnly) throws RemoteException {
+ super.createPartition_enforcePermission();
+
IGsiService service = getGsiService();
int status = service.createPartition(name, size, readOnly);
if (status != IGsiService.INSTALL_OK) {
@@ -135,6 +139,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean closePartition() throws RemoteException {
+ super.closePartition_enforcePermission();
+
IGsiService service = getGsiService();
if (service.closePartition() != 0) {
Slog.i(TAG, "Partition installation completes with error");
@@ -146,6 +152,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean finishInstallation() throws RemoteException {
+ super.finishInstallation_enforcePermission();
+
IGsiService service = getGsiService();
if (service.closeInstall() != 0) {
Slog.i(TAG, "Failed to finish installation");
@@ -157,12 +165,16 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public GsiProgress getInstallationProgress() throws RemoteException {
+ super.getInstallationProgress_enforcePermission();
+
return getGsiService().getInstallProgress();
}
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean abort() throws RemoteException {
+ super.abort_enforcePermission();
+
return getGsiService().cancelGsiInstall();
}
@@ -183,12 +195,16 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean isEnabled() throws RemoteException {
+ super.isEnabled_enforcePermission();
+
return getGsiService().isGsiEnabled();
}
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean remove() throws RemoteException {
+ super.remove_enforcePermission();
+
try {
GsiServiceCallback callback = new GsiServiceCallback();
synchronized (callback) {
@@ -205,6 +221,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean setEnable(boolean enable, boolean oneShot) throws RemoteException {
+ super.setEnable_enforcePermission();
+
IGsiService gsiService = getGsiService();
if (enable) {
try {
@@ -229,6 +247,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean setAshmem(ParcelFileDescriptor ashmem, long size) {
+ super.setAshmem_enforcePermission();
+
try {
return getGsiService().setGsiAshmem(ashmem, size);
} catch (RemoteException e) {
@@ -239,6 +259,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean submitFromAshmem(long size) {
+ super.submitFromAshmem_enforcePermission();
+
try {
return getGsiService().commitGsiChunkFromAshmem(size);
} catch (RemoteException e) {
@@ -249,6 +271,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public boolean getAvbPublicKey(AvbPublicKey dst) {
+ super.getAvbPublicKey_enforcePermission();
+
try {
return getGsiService().getAvbPublicKey(dst) == 0;
} catch (RemoteException e) {
@@ -259,6 +283,8 @@
@Override
@EnforcePermission(android.Manifest.permission.MANAGE_DYNAMIC_SYSTEM)
public long suggestScratchSize() throws RemoteException {
+ super.suggestScratchSize_enforcePermission();
+
return getGsiService().suggestScratchSize();
}
}
diff --git a/services/core/java/com/android/server/GestureLauncherService.java b/services/core/java/com/android/server/GestureLauncherService.java
index e529010..7d2e276 100644
--- a/services/core/java/com/android/server/GestureLauncherService.java
+++ b/services/core/java/com/android/server/GestureLauncherService.java
@@ -466,7 +466,8 @@
public static boolean isEmergencyGestureSettingEnabled(Context context, int userId) {
return isEmergencyGestureEnabled(context.getResources())
&& Settings.Secure.getIntForUser(context.getContentResolver(),
- Settings.Secure.EMERGENCY_GESTURE_ENABLED, 1, userId) != 0;
+ Settings.Secure.EMERGENCY_GESTURE_ENABLED,
+ isDefaultEmergencyGestureEnabled(context.getResources()) ? 1 : 0, userId) != 0;
}
/**
@@ -513,6 +514,11 @@
return resources.getBoolean(com.android.internal.R.bool.config_emergencyGestureEnabled);
}
+ private static boolean isDefaultEmergencyGestureEnabled(Resources resources) {
+ return resources.getBoolean(
+ com.android.internal.R.bool.config_defaultEmergencyGestureEnabled);
+ }
+
/**
* Whether GestureLauncherService should be enabled according to system properties.
*/
diff --git a/services/core/java/com/android/server/SerialService.java b/services/core/java/com/android/server/SerialService.java
index e915fa1..ff903a0 100644
--- a/services/core/java/com/android/server/SerialService.java
+++ b/services/core/java/com/android/server/SerialService.java
@@ -37,6 +37,8 @@
@EnforcePermission(android.Manifest.permission.SERIAL_PORT)
public String[] getSerialPorts() {
+ super.getSerialPorts_enforcePermission();
+
ArrayList<String> ports = new ArrayList<String>();
for (int i = 0; i < mSerialPorts.length; i++) {
String path = mSerialPorts[i];
@@ -51,6 +53,8 @@
@EnforcePermission(android.Manifest.permission.SERIAL_PORT)
public ParcelFileDescriptor openSerialPort(String path) {
+ super.openSerialPort_enforcePermission();
+
for (int i = 0; i < mSerialPorts.length; i++) {
if (mSerialPorts[i].equals(path)) {
return native_open(path);
diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java
index f7b05f2..ec8745a 100644
--- a/services/core/java/com/android/server/StorageManagerService.java
+++ b/services/core/java/com/android/server/StorageManagerService.java
@@ -19,12 +19,10 @@
import static android.Manifest.permission.ACCESS_MTP;
import static android.Manifest.permission.INSTALL_PACKAGES;
import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
-import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.OP_LEGACY_STORAGE;
import static android.app.AppOpsManager.OP_MANAGE_EXTERNAL_STORAGE;
import static android.app.AppOpsManager.OP_REQUEST_INSTALL_PACKAGES;
-import static android.app.AppOpsManager.OP_WRITE_EXTERNAL_STORAGE;
import static android.app.PendingIntent.FLAG_CANCEL_CURRENT;
import static android.app.PendingIntent.FLAG_IMMUTABLE;
import static android.app.PendingIntent.FLAG_ONE_SHOT;
@@ -4461,11 +4459,7 @@
}
}
- // Determine if caller is holding runtime permission
- final boolean hasWrite = StorageManager.checkPermissionAndCheckOp(mContext, false, 0,
- uid, packageName, WRITE_EXTERNAL_STORAGE, OP_WRITE_EXTERNAL_STORAGE);
-
- // We're only willing to give out installer access if they also hold
+ // We're only willing to give out installer access if they hold
// runtime permission; this is a firm CDD requirement
final boolean hasInstall = mIPackageManager.checkUidPermission(INSTALL_PACKAGES,
uid) == PERMISSION_GRANTED;
@@ -4481,7 +4475,7 @@
break;
}
}
- if ((hasInstall || hasInstallOp) && hasWrite) {
+ if (hasInstall || hasInstallOp) {
return StorageManager.MOUNT_MODE_EXTERNAL_INSTALLER;
}
return StorageManager.MOUNT_MODE_EXTERNAL_DEFAULT;
diff --git a/services/core/java/com/android/server/appop/AppOpsService.java b/services/core/java/com/android/server/appop/AppOpsService.java
index b56654f..2f7f2da 100644
--- a/services/core/java/com/android/server/appop/AppOpsService.java
+++ b/services/core/java/com/android/server/appop/AppOpsService.java
@@ -7551,7 +7551,6 @@
Objects.requireNonNull(stackTrace);
Preconditions.checkArgument(op >= 0);
Preconditions.checkArgument(op < AppOpsManager._NUM_OP);
- Objects.requireNonNull(version);
NoteOpTrace noteOpTrace = new NoteOpTrace(stackTrace, op, packageName, version);
diff --git a/services/core/java/com/android/server/broadcastradio/hal2/Utils.java b/services/core/java/com/android/server/broadcastradio/hal2/Utils.java
index 384c9ba..85d796e 100644
--- a/services/core/java/com/android/server/broadcastradio/hal2/Utils.java
+++ b/services/core/java/com/android/server/broadcastradio/hal2/Utils.java
@@ -25,7 +25,7 @@
AM_LW,
AM_MW,
AM_SW,
-};
+}
class Utils {
private static final String TAG = "BcRadio2Srv.utils";
diff --git a/services/core/java/com/android/server/connectivity/Vpn.java b/services/core/java/com/android/server/connectivity/Vpn.java
index 0741d46..bc9bc03 100644
--- a/services/core/java/com/android/server/connectivity/Vpn.java
+++ b/services/core/java/com/android/server/connectivity/Vpn.java
@@ -645,7 +645,8 @@
.addTransportType(NetworkCapabilities.TRANSPORT_VPN)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
- .setTransportInfo(new VpnTransportInfo(VpnManager.TYPE_VPN_NONE, null))
+ .setTransportInfo(new VpnTransportInfo(
+ VpnManager.TYPE_VPN_NONE, null /* sessionId */, false /* bypassable */))
.build();
loadAlwaysOnPackage();
@@ -709,7 +710,8 @@
private void resetNetworkCapabilities() {
mNetworkCapabilities = new NetworkCapabilities.Builder(mNetworkCapabilities)
.setUids(null)
- .setTransportInfo(new VpnTransportInfo(VpnManager.TYPE_VPN_NONE, null))
+ .setTransportInfo(new VpnTransportInfo(
+ VpnManager.TYPE_VPN_NONE, null /* sessionId */, false /* bypassable */))
.build();
}
@@ -1567,7 +1569,8 @@
capsBuilder.setUids(createUserAndRestrictedProfilesRanges(mUserId,
mConfig.allowedApplications, mConfig.disallowedApplications));
- capsBuilder.setTransportInfo(new VpnTransportInfo(getActiveVpnType(), mConfig.session));
+ capsBuilder.setTransportInfo(
+ new VpnTransportInfo(getActiveVpnType(), mConfig.session, mConfig.allowBypass));
// Only apps targeting Q and above can explicitly declare themselves as metered.
// These VPNs are assumed metered unless they state otherwise.
diff --git a/services/core/java/com/android/server/cpu/OWNERS b/services/core/java/com/android/server/cpu/OWNERS
new file mode 100644
index 0000000..2f42363
--- /dev/null
+++ b/services/core/java/com/android/server/cpu/OWNERS
@@ -0,0 +1,4 @@
+# Bug component: 608533
+
+include platform/packages/services/Car:/OWNERS
+lakshmana@google.com
diff --git a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
index 9bce471f..8a22ab9 100644
--- a/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
+++ b/services/core/java/com/android/server/hdmi/HdmiCecLocalDeviceTv.java
@@ -837,7 +837,7 @@
void enableAudioReturnChannel(boolean enabled) {
assertRunOnServiceThread();
HdmiDeviceInfo avr = getAvrDeviceInfo();
- if (avr != null) {
+ if (avr != null && avr.getPortId() != Constants.INVALID_PORT_ID) {
mService.enableAudioReturnChannel(avr.getPortId(), enabled);
}
}
@@ -1336,19 +1336,31 @@
}
@ServiceThreadOnly
+ private void forceDisableArcOnAllPins() {
+ List<HdmiPortInfo> ports = mService.getPortInfo();
+ for (HdmiPortInfo port : ports) {
+ if (isArcFeatureEnabled(port.getId())) {
+ mService.enableAudioReturnChannel(port.getId(), false);
+ }
+ }
+ }
+
+ @ServiceThreadOnly
private void disableArcIfExist() {
assertRunOnServiceThread();
HdmiDeviceInfo avr = getAvrDeviceInfo();
if (avr == null) {
return;
}
- disableArc();
// Seq #44.
removeAllRunningArcAction();
if (!hasAction(RequestArcTerminationAction.class) && isArcEstablished()) {
addAndStartAction(new RequestArcTerminationAction(this, avr.getLogicalAddress()));
}
+
+ // Disable ARC Pin earlier, prevent the case where AVR doesn't send <Terminate ARC> in time
+ forceDisableArcOnAllPins();
}
@ServiceThreadOnly
diff --git a/services/core/java/com/android/server/hdmi/HdmiUtils.java b/services/core/java/com/android/server/hdmi/HdmiUtils.java
index ba19cf0..308a0c8 100644
--- a/services/core/java/com/android/server/hdmi/HdmiUtils.java
+++ b/services/core/java/com/android/server/hdmi/HdmiUtils.java
@@ -20,6 +20,8 @@
import static com.android.server.hdmi.Constants.ADDR_BACKUP_2;
import static com.android.server.hdmi.Constants.ADDR_TV;
+import static java.util.Map.entry;
+
import android.annotation.Nullable;
import android.hardware.hdmi.HdmiControlManager;
import android.hardware.hdmi.HdmiDeviceInfo;
@@ -45,7 +47,6 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -57,38 +58,34 @@
private static final String TAG = "HdmiUtils";
- private static final Map<Integer, List<Integer>> ADDRESS_TO_TYPE =
- new HashMap<Integer, List<Integer>>() {
- {
- put(Constants.ADDR_TV, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TV));
- put(Constants.ADDR_RECORDER_1,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER));
- put(Constants.ADDR_RECORDER_2,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER));
- put(Constants.ADDR_TUNER_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER));
- put(Constants.ADDR_PLAYBACK_1,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK));
- put(Constants.ADDR_AUDIO_SYSTEM,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM));
- put(Constants.ADDR_TUNER_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER));
- put(Constants.ADDR_TUNER_3, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER));
- put(Constants.ADDR_PLAYBACK_2,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK));
- put(Constants.ADDR_RECORDER_3,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER));
- put(Constants.ADDR_TUNER_4, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER));
- put(Constants.ADDR_PLAYBACK_3,
- Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK));
- put(Constants.ADDR_BACKUP_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK,
- HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER,
- HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR));
- put(Constants.ADDR_BACKUP_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK,
- HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER,
- HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR));
- put(Constants.ADDR_SPECIFIC_USE, Lists.newArrayList(ADDR_TV));
- put(Constants.ADDR_UNREGISTERED, Collections.emptyList());
- }
- };
+ private static final Map<Integer, List<Integer>> ADDRESS_TO_TYPE = Map.ofEntries(
+ entry(Constants.ADDR_TV, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TV)),
+ entry(Constants.ADDR_RECORDER_1,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)),
+ entry(Constants.ADDR_RECORDER_2,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)),
+ entry(Constants.ADDR_TUNER_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)),
+ entry(Constants.ADDR_PLAYBACK_1,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)),
+ entry(Constants.ADDR_AUDIO_SYSTEM,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM)),
+ entry(Constants.ADDR_TUNER_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)),
+ entry(Constants.ADDR_TUNER_3, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)),
+ entry(Constants.ADDR_PLAYBACK_2,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)),
+ entry(Constants.ADDR_RECORDER_3,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_RECORDER)),
+ entry(Constants.ADDR_TUNER_4, Lists.newArrayList(HdmiDeviceInfo.DEVICE_TUNER)),
+ entry(Constants.ADDR_PLAYBACK_3,
+ Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK)),
+ entry(Constants.ADDR_BACKUP_1, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK,
+ HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER,
+ HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)),
+ entry(Constants.ADDR_BACKUP_2, Lists.newArrayList(HdmiDeviceInfo.DEVICE_PLAYBACK,
+ HdmiDeviceInfo.DEVICE_RECORDER, HdmiDeviceInfo.DEVICE_TUNER,
+ HdmiDeviceInfo.DEVICE_VIDEO_PROCESSOR)),
+ entry(Constants.ADDR_SPECIFIC_USE, Lists.newArrayList(ADDR_TV)),
+ entry(Constants.ADDR_UNREGISTERED, Collections.emptyList()));
private static final String[] DEFAULT_NAMES = {
"TV",
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 72612a0..a9d747c 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -1799,8 +1799,8 @@
*/
public boolean transferTouchFocus(@NonNull IBinder fromChannelToken,
@NonNull IBinder toChannelToken) {
- Objects.nonNull(fromChannelToken);
- Objects.nonNull(toChannelToken);
+ Objects.requireNonNull(fromChannelToken);
+ Objects.requireNonNull(toChannelToken);
return mNative.transferTouchFocus(fromChannelToken, toChannelToken,
false /* isDragDrop */);
}
diff --git a/services/core/java/com/android/server/locales/OWNERS b/services/core/java/com/android/server/locales/OWNERS
index 4d93bff..e1e946b 100644
--- a/services/core/java/com/android/server/locales/OWNERS
+++ b/services/core/java/com/android/server/locales/OWNERS
@@ -2,3 +2,6 @@
pratyushmore@google.com
goldmanj@google.com
ankitavyas@google.com
+allenwtsu@google.com
+calvinpan@google.com
+joshhou@google.com
diff --git a/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java b/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java
index c199bb3..2d3f176 100644
--- a/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java
+++ b/services/core/java/com/android/server/location/contexthub/ContextHubTransactionManager.java
@@ -519,9 +519,9 @@
@Override
public String toString() {
StringBuilder sb = new StringBuilder(100);
- TransactionRecord[] arr;
+ ContextHubServiceTransaction[] arr;
synchronized (this) {
- arr = mTransactionQueue.toArray(new TransactionRecord[0]);
+ arr = mTransactionQueue.toArray(new ContextHubServiceTransaction[0]);
}
for (int i = 0; i < arr.length; i++) {
sb.append(i + ": " + arr[i] + "\n");
diff --git a/services/core/java/com/android/server/location/gnss/GnssConfiguration.java b/services/core/java/com/android/server/location/gnss/GnssConfiguration.java
index 12f8776..25350d0 100644
--- a/services/core/java/com/android/server/location/gnss/GnssConfiguration.java
+++ b/services/core/java/com/android/server/location/gnss/GnssConfiguration.java
@@ -260,26 +260,24 @@
Log.e(TAG, "Unable to set " + CONFIG_ES_EXTENSION_SEC + ": " + mEsExtensionSec);
}
- Map<String, SetCarrierProperty> map = new HashMap<String, SetCarrierProperty>() {
- {
- put(CONFIG_SUPL_VER, GnssConfiguration::native_set_supl_version);
- put(CONFIG_SUPL_MODE, GnssConfiguration::native_set_supl_mode);
+ Map<String, SetCarrierProperty> map = new HashMap<String, SetCarrierProperty>();
- if (isConfigSuplEsSupported(gnssConfigurationIfaceVersion)) {
- put(CONFIG_SUPL_ES, GnssConfiguration::native_set_supl_es);
- }
+ map.put(CONFIG_SUPL_VER, GnssConfiguration::native_set_supl_version);
+ map.put(CONFIG_SUPL_MODE, GnssConfiguration::native_set_supl_mode);
- put(CONFIG_LPP_PROFILE, GnssConfiguration::native_set_lpp_profile);
- put(CONFIG_A_GLONASS_POS_PROTOCOL_SELECT,
- GnssConfiguration::native_set_gnss_pos_protocol_select);
- put(CONFIG_USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL,
- GnssConfiguration::native_set_emergency_supl_pdn);
+ if (isConfigSuplEsSupported(gnssConfigurationIfaceVersion)) {
+ map.put(CONFIG_SUPL_ES, GnssConfiguration::native_set_supl_es);
+ }
- if (isConfigGpsLockSupported(gnssConfigurationIfaceVersion)) {
- put(CONFIG_GPS_LOCK, GnssConfiguration::native_set_gps_lock);
- }
- }
- };
+ map.put(CONFIG_LPP_PROFILE, GnssConfiguration::native_set_lpp_profile);
+ map.put(CONFIG_A_GLONASS_POS_PROTOCOL_SELECT,
+ GnssConfiguration::native_set_gnss_pos_protocol_select);
+ map.put(CONFIG_USE_EMERGENCY_PDN_FOR_EMERGENCY_SUPL,
+ GnssConfiguration::native_set_emergency_supl_pdn);
+
+ if (isConfigGpsLockSupported(gnssConfigurationIfaceVersion)) {
+ map.put(CONFIG_GPS_LOCK, GnssConfiguration::native_set_gps_lock);
+ }
for (Entry<String, SetCarrierProperty> entry : map.entrySet()) {
String propertyName = entry.getKey();
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index 018a2fc..2cc0073 100755
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -4927,7 +4927,16 @@
}
enforcePolicyAccess(Binder.getCallingUid(), "addAutomaticZenRule");
- return mZenModeHelper.addAutomaticZenRule(pkg, automaticZenRule,
+ // If the caller is system, take the package name from the rule's owner rather than
+ // from the caller's package.
+ String rulePkg = pkg;
+ if (isCallingUidSystem()) {
+ if (automaticZenRule.getOwner() != null) {
+ rulePkg = automaticZenRule.getOwner().getPackageName();
+ }
+ }
+
+ return mZenModeHelper.addAutomaticZenRule(rulePkg, automaticZenRule,
"addAutomaticZenRule");
}
@@ -7850,7 +7859,8 @@
&& (record.getSuppressedVisualEffects() & SUPPRESSED_EFFECT_STATUS_BAR) != 0;
if (!record.isUpdate
&& record.getImportance() > IMPORTANCE_MIN
- && !suppressedByDnd) {
+ && !suppressedByDnd
+ && isNotificationForCurrentUser(record)) {
sendAccessibilityEvent(record);
sentAccessibilityEvent = true;
}
diff --git a/services/core/java/com/android/server/notification/PermissionHelper.java b/services/core/java/com/android/server/notification/PermissionHelper.java
index 09ed567..14e82f3 100644
--- a/services/core/java/com/android/server/notification/PermissionHelper.java
+++ b/services/core/java/com/android/server/notification/PermissionHelper.java
@@ -257,9 +257,11 @@
private boolean packageRequestsNotificationPermission(String packageName,
@UserIdInt int userId) {
try {
- String[] permissions = mPackageManager.getPackageInfo(packageName, GET_PERMISSIONS,
- userId).requestedPermissions;
- return ArrayUtils.contains(permissions, NOTIFICATION_PERMISSION);
+ PackageInfo pi = mPackageManager.getPackageInfo(packageName, GET_PERMISSIONS, userId);
+ if (pi != null) {
+ String[] permissions = pi.requestedPermissions;
+ return ArrayUtils.contains(permissions, NOTIFICATION_PERMISSION);
+ }
} catch (RemoteException e) {
Slog.e(TAG, "Could not reach system server", e);
}
diff --git a/services/core/java/com/android/server/notification/PreferencesHelper.java b/services/core/java/com/android/server/notification/PreferencesHelper.java
index 477b8da..634ee7e 100644
--- a/services/core/java/com/android/server/notification/PreferencesHelper.java
+++ b/services/core/java/com/android/server/notification/PreferencesHelper.java
@@ -852,7 +852,9 @@
Objects.requireNonNull(pkg);
Objects.requireNonNull(group);
Objects.requireNonNull(group.getId());
- Objects.requireNonNull(!TextUtils.isEmpty(group.getName()));
+ if (TextUtils.isEmpty(group.getName())) {
+ throw new IllegalArgumentException("group.getName() can't be empty");
+ }
boolean needsDndChange = false;
synchronized (mPackagePreferences) {
PackagePreferences r = getOrCreatePackagePreferencesLocked(pkg, uid);
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index 2b00ad7..85c47a0 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -314,7 +314,7 @@
public String addAutomaticZenRule(String pkg, AutomaticZenRule automaticZenRule,
String reason) {
- if (!isSystemRule(automaticZenRule)) {
+ if (!ZenModeConfig.SYSTEM_AUTHORITY.equals(pkg)) {
PackageItemInfo component = getServiceInfo(automaticZenRule.getOwner());
if (component == null) {
component = getActivityInfo(automaticZenRule.getConfigurationActivity());
@@ -570,11 +570,6 @@
}
}
- private boolean isSystemRule(AutomaticZenRule rule) {
- return rule.getOwner() != null
- && ZenModeConfig.SYSTEM_AUTHORITY.equals(rule.getOwner().getPackageName());
- }
-
private ServiceInfo getServiceInfo(ComponentName owner) {
Intent queryIntent = new Intent();
queryIntent.setComponent(owner);
diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
index 5a01ccb..e411880 100644
--- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java
+++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java
@@ -149,8 +149,6 @@
@GuardedBy("mLock") @Status private int mLastExecutionStatus = STATUS_OK;
- @GuardedBy("mLock") private long mLastExecutionStartTimeMs;
- @GuardedBy("mLock") private long mLastExecutionDurationIncludingSleepMs;
@GuardedBy("mLock") private long mLastExecutionStartUptimeMs;
@GuardedBy("mLock") private long mLastExecutionDurationMs;
@@ -229,10 +227,6 @@
writer.println(mFinishedPostBootUpdate);
writer.print("mLastExecutionStatus:");
writer.println(mLastExecutionStatus);
- writer.print("mLastExecutionStartTimeMs:");
- writer.println(mLastExecutionStartTimeMs);
- writer.print("mLastExecutionDurationIncludingSleepMs:");
- writer.println(mLastExecutionDurationIncludingSleepMs);
writer.print("mLastExecutionStartUptimeMs:");
writer.println(mLastExecutionStartUptimeMs);
writer.print("mLastExecutionDurationMs:");
@@ -539,8 +533,6 @@
private boolean runIdleOptimization(
PackageManagerService pm, List<String> pkgs, boolean isPostBootUpdate) {
synchronized (mLock) {
- mLastExecutionStartTimeMs = SystemClock.elapsedRealtime();
- mLastExecutionDurationIncludingSleepMs = -1;
mLastExecutionStartUptimeMs = SystemClock.uptimeMillis();
mLastExecutionDurationMs = -1;
}
@@ -549,8 +541,6 @@
logStatus(status);
synchronized (mLock) {
mLastExecutionStatus = status;
- mLastExecutionDurationIncludingSleepMs =
- SystemClock.elapsedRealtime() - mLastExecutionStartTimeMs;
mLastExecutionDurationMs = SystemClock.uptimeMillis() - mLastExecutionStartUptimeMs;
}
@@ -954,10 +944,9 @@
synchronized (mLock) {
status = mLastExecutionStatus;
durationMs = mLastExecutionDurationMs;
- durationIncludingSleepMs = mLastExecutionDurationIncludingSleepMs;
}
- mStatsLogger.write(status, params.getStopReason(), durationMs, durationIncludingSleepMs);
+ mStatsLogger.write(status, params.getStopReason(), durationMs);
}
/** Injector pattern for testing purpose */
diff --git a/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java b/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java
index 3b306a8..b310c62a 100644
--- a/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java
+++ b/services/core/java/com/android/server/pm/PerPackageReadTimeouts.java
@@ -16,7 +16,7 @@
package com.android.server.pm;
-import android.annotation.NonNull;;
+import android.annotation.NonNull;
import android.text.TextUtils;
import com.android.internal.util.HexDump;
diff --git a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
index 905bcf9..1407530 100644
--- a/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
+++ b/services/core/java/com/android/server/pm/dex/ArtStatsLogUtils.java
@@ -320,12 +320,15 @@
public static class BackgroundDexoptJobStatsLogger {
/** Writes background dexopt job stats to statsd. */
public void write(@BackgroundDexOptService.Status int status,
- @JobParameters.StopReason int cancellationReason, long durationMs,
- long durationIncludingSleepMs) {
- ArtStatsLog.write(ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED,
+ @JobParameters.StopReason int cancellationReason,
+ long durationMs) {
+ ArtStatsLog.write(
+ ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED,
STATUS_MAP.getOrDefault(status,
ArtStatsLog.BACKGROUND_DEXOPT_JOB_ENDED__STATUS__STATUS_UNKNOWN),
- cancellationReason, durationMs, durationIncludingSleepMs);
+ cancellationReason,
+ durationMs,
+ 0); // deprecated, used to be durationIncludingSleepMs
}
}
}
diff --git a/services/core/java/com/android/server/pm/dex/DexoptUtils.java b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
index beea86d..d519c52 100644
--- a/services/core/java/com/android/server/pm/dex/DexoptUtils.java
+++ b/services/core/java/com/android/server/pm/dex/DexoptUtils.java
@@ -295,6 +295,7 @@
* NOTE: Keep this in sync with the dexopt expectations! Right now that is either "PCL[path]"
* for a PathClassLoader or "DLC[path]" for a DelegateLastClassLoader.
*/
+ @SuppressWarnings("ReturnValueIgnored")
/*package*/ static String encodeClassLoader(String classpath, String classLoaderName) {
classpath.getClass(); // Throw NPE if classpath is null
String classLoaderDexoptEncoding = classLoaderName;
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index 073776f..98bbcb9 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -86,6 +86,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
/**
@@ -1924,7 +1925,7 @@
mPkgRequestingPerm, newRestrictionExcemptFlags, -1, mUser);
}
- if (newGranted != null && newGranted != mOriginalGranted) {
+ if (newGranted != null && !Objects.equals(newGranted, mOriginalGranted)) {
if (newGranted) {
NO_PM_CACHE.grantPermission(mPermission, mPkgRequestingPerm, mUser);
} else {
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
index d34682d..1e13333 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java
@@ -2664,7 +2664,6 @@
final Permission bp = mRegistry.getPermission(permName);
final boolean appSupportsRuntimePermissions =
pkg.getTargetSdkVersion() >= Build.VERSION_CODES.M;
- String legacyActivityRecognitionPermission = null;
if (DEBUG_INSTALL && bp != null) {
Log.i(TAG, "Package " + friendlyName
@@ -2688,47 +2687,12 @@
// Cache newImplicitPermissions before modifing permissionsState as for the
// shared uids the original and new state are the same object
if (!origState.hasPermissionState(permName)
- && (pkg.getImplicitPermissions().contains(permName)
- || (permName.equals(Manifest.permission.ACTIVITY_RECOGNITION)))) {
- if (pkg.getImplicitPermissions().contains(permName)) {
+ && (pkg.getImplicitPermissions().contains(permName))) {
// If permName is an implicit permission, try to auto-grant
newImplicitPermissions.add(permName);
-
if (DEBUG_PERMISSIONS) {
Slog.i(TAG, permName + " is newly added for " + friendlyName);
}
- } else {
- // Special case for Activity Recognition permission. Even if AR
- // permission is not an implicit permission we want to add it to the
- // list (try to auto-grant it) if the app was installed on a device
- // before AR permission was split, regardless of if the app now requests
- // the new AR permission or has updated its target SDK and AR is no
- // longer implicit to it. This is a compatibility workaround for apps
- // when AR permission was split in Q.
- // TODO(zhanghai): This calls into SystemConfig, which generally
- // shouldn't cause deadlock, but maybe we should keep a cache of the
- // split permission list and just eliminate the possibility.
- final List<PermissionManager.SplitPermissionInfo> permissionList =
- getSplitPermissionInfos();
- int numSplitPerms = permissionList.size();
- for (int splitPermNum = 0; splitPermNum < numSplitPerms;
- splitPermNum++) {
- PermissionManager.SplitPermissionInfo sp = permissionList.get(
- splitPermNum);
- String splitPermName = sp.getSplitPermission();
- if (sp.getNewPermissions().contains(permName)
- && origState.isPermissionGranted(splitPermName)) {
- legacyActivityRecognitionPermission = splitPermName;
- newImplicitPermissions.add(permName);
-
- if (DEBUG_PERMISSIONS) {
- Slog.i(TAG, permName + " is newly added for "
- + friendlyName);
- }
- break;
- }
- }
- }
}
// TODO(b/140256621): The package instant app method has been removed
@@ -2862,8 +2826,7 @@
// Hard restricted permissions cannot be held.
} else if (!permissionPolicyInitialized
|| (!hardRestricted || restrictionExempt)) {
- if ((origPermState != null && origPermState.isGranted())
- || legacyActivityRecognitionPermission != null) {
+ if ((origPermState != null && origPermState.isGranted())) {
if (!uidState.grantPermission(bp)) {
wasChanged = true;
}
diff --git a/services/core/java/com/android/server/policy/PhoneWindowManager.java b/services/core/java/com/android/server/policy/PhoneWindowManager.java
index 3af6e18..2cf6608 100644
--- a/services/core/java/com/android/server/policy/PhoneWindowManager.java
+++ b/services/core/java/com/android/server/policy/PhoneWindowManager.java
@@ -3474,7 +3474,12 @@
@Override
public void onKeyguardExitResult(boolean success) {
if (success) {
- startDockOrHome(displayId, true /*fromHomeKey*/, awakenFromDreams);
+ final long origId = Binder.clearCallingIdentity();
+ try {
+ startDockOrHome(displayId, true /*fromHomeKey*/, awakenFromDreams);
+ } finally {
+ Binder.restoreCallingIdentity(origId);
+ }
}
}
});
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
index e197319..eb8464e 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
@@ -1888,12 +1888,9 @@
}
}
- private static final HashMap<Integer, String> sWallpaperType = new HashMap<Integer, String>() {
- {
- put(FLAG_SYSTEM, RECORD_FILE);
- put(FLAG_LOCK, RECORD_LOCK_FILE);
- }
- };
+ private static final Map<Integer, String> sWallpaperType = Map.of(
+ FLAG_SYSTEM, RECORD_FILE,
+ FLAG_LOCK, RECORD_LOCK_FILE);
private void errorCheck(int userID) {
sWallpaperType.forEach((type, filename) -> {
diff --git a/services/core/java/com/android/server/wm/DisplayWindowSettings.java b/services/core/java/com/android/server/wm/DisplayWindowSettings.java
index 11bcd8c..a9d0e96 100644
--- a/services/core/java/com/android/server/wm/DisplayWindowSettings.java
+++ b/services/core/java/com/android/server/wm/DisplayWindowSettings.java
@@ -436,11 +436,12 @@
mRemoveContentMode = other.mRemoveContentMode;
changed = true;
}
- if (other.mShouldShowWithInsecureKeyguard != mShouldShowWithInsecureKeyguard) {
+ if (!Objects.equals(
+ other.mShouldShowWithInsecureKeyguard, mShouldShowWithInsecureKeyguard)) {
mShouldShowWithInsecureKeyguard = other.mShouldShowWithInsecureKeyguard;
changed = true;
}
- if (other.mShouldShowSystemDecors != mShouldShowSystemDecors) {
+ if (!Objects.equals(other.mShouldShowSystemDecors, mShouldShowSystemDecors)) {
mShouldShowSystemDecors = other.mShouldShowSystemDecors;
changed = true;
}
@@ -452,15 +453,15 @@
mFixedToUserRotation = other.mFixedToUserRotation;
changed = true;
}
- if (other.mIgnoreOrientationRequest != mIgnoreOrientationRequest) {
+ if (!Objects.equals(other.mIgnoreOrientationRequest, mIgnoreOrientationRequest)) {
mIgnoreOrientationRequest = other.mIgnoreOrientationRequest;
changed = true;
}
- if (other.mIgnoreDisplayCutout != mIgnoreDisplayCutout) {
+ if (!Objects.equals(other.mIgnoreDisplayCutout, mIgnoreDisplayCutout)) {
mIgnoreDisplayCutout = other.mIgnoreDisplayCutout;
changed = true;
}
- if (other.mDontMoveToTop != mDontMoveToTop) {
+ if (!Objects.equals(other.mDontMoveToTop, mDontMoveToTop)) {
mDontMoveToTop = other.mDontMoveToTop;
changed = true;
}
@@ -516,14 +517,13 @@
mRemoveContentMode = delta.mRemoveContentMode;
changed = true;
}
- if (delta.mShouldShowWithInsecureKeyguard != null
- && delta.mShouldShowWithInsecureKeyguard
- != mShouldShowWithInsecureKeyguard) {
+ if (delta.mShouldShowWithInsecureKeyguard != null && !Objects.equals(
+ delta.mShouldShowWithInsecureKeyguard, mShouldShowWithInsecureKeyguard)) {
mShouldShowWithInsecureKeyguard = delta.mShouldShowWithInsecureKeyguard;
changed = true;
}
- if (delta.mShouldShowSystemDecors != null
- && delta.mShouldShowSystemDecors != mShouldShowSystemDecors) {
+ if (delta.mShouldShowSystemDecors != null && !Objects.equals(
+ delta.mShouldShowSystemDecors, mShouldShowSystemDecors)) {
mShouldShowSystemDecors = delta.mShouldShowSystemDecors;
changed = true;
}
@@ -537,18 +537,18 @@
mFixedToUserRotation = delta.mFixedToUserRotation;
changed = true;
}
- if (delta.mIgnoreOrientationRequest != null
- && delta.mIgnoreOrientationRequest != mIgnoreOrientationRequest) {
+ if (delta.mIgnoreOrientationRequest != null && !Objects.equals(
+ delta.mIgnoreOrientationRequest, mIgnoreOrientationRequest)) {
mIgnoreOrientationRequest = delta.mIgnoreOrientationRequest;
changed = true;
}
- if (delta.mIgnoreDisplayCutout != null
- && delta.mIgnoreDisplayCutout != mIgnoreDisplayCutout) {
+ if (delta.mIgnoreDisplayCutout != null && !Objects.equals(
+ delta.mIgnoreDisplayCutout, mIgnoreDisplayCutout)) {
mIgnoreDisplayCutout = delta.mIgnoreDisplayCutout;
changed = true;
}
- if (delta.mDontMoveToTop != null
- && delta.mDontMoveToTop != mDontMoveToTop) {
+ if (delta.mDontMoveToTop != null && !Objects.equals(
+ delta.mDontMoveToTop, mDontMoveToTop)) {
mDontMoveToTop = delta.mDontMoveToTop;
changed = true;
}
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index e1ee045..5d53c20 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -5458,7 +5458,23 @@
parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
(destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
- parent.deliverNewIntentLocked(callingUid, destIntent, destGrants, srec.packageName);
+ boolean abort;
+ try {
+ abort = !mTaskSupervisor.checkStartAnyActivityPermission(destIntent,
+ parent.info, null /* resultWho */, -1 /* requestCode */, srec.getPid(),
+ callingUid, srec.info.packageName, null /* callingFeatureId */,
+ false /* ignoreTargetSecurity */, false /* launchingInTask */, srec.app,
+ null /* resultRecord */, null /* resultRootTask */);
+ } catch (SecurityException e) {
+ abort = true;
+ }
+ if (abort) {
+ android.util.EventLog.writeEvent(0x534e4554, "238605611", callingUid, "");
+ foundParentInTask = false;
+ } else {
+ parent.deliverNewIntentLocked(callingUid, destIntent, destGrants,
+ srec.packageName);
+ }
} else {
try {
ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
diff --git a/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java b/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java
index 6f2930c..1b70d1d 100644
--- a/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java
+++ b/services/core/java/com/android/server/wm/WindowManagerThreadPriorityBooster.java
@@ -21,7 +21,7 @@
import static android.os.Process.myTid;
import static android.os.Process.setThreadPriority;
-import static com.android.server.LockGuard.INDEX_WINDOW;;
+import static com.android.server.LockGuard.INDEX_WINDOW;
import com.android.internal.annotations.GuardedBy;
import com.android.server.AnimationThread;
diff --git a/services/core/jni/com_android_server_am_BatteryStatsService.cpp b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
index 16eaa77..3678ced 100644
--- a/services/core/jni/com_android_server_am_BatteryStatsService.cpp
+++ b/services/core/jni/com_android_server_am_BatteryStatsService.cpp
@@ -98,7 +98,7 @@
public:
binder::Status notifyWakeup(bool success,
const std::vector<std::string>& wakeupReasons) override {
- ALOGI("In wakeup_callback: %s", success ? "resumed from suspend" : "suspend aborted");
+ ALOGV("In wakeup_callback: %s", success ? "resumed from suspend" : "suspend aborted");
bool reasonsCaptured = false;
{
std::unique_lock<std::mutex> reasonsLock(mReasonsMutex, std::defer_lock);
diff --git a/services/people/java/com/android/server/people/PeopleService.java b/services/people/java/com/android/server/people/PeopleService.java
index eab3b77..292320e 100644
--- a/services/people/java/com/android/server/people/PeopleService.java
+++ b/services/people/java/com/android/server/people/PeopleService.java
@@ -53,6 +53,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.function.Consumer;
/**
@@ -372,7 +373,8 @@
@Override
public boolean equals(Object o) {
ListenerKey key = (ListenerKey) o;
- return key.getPackageName().equals(mPackageName) && key.getUserId() == mUserId
+ return key.getPackageName().equals(mPackageName)
+ && Objects.equals(key.getUserId(), mUserId)
&& key.getShortcutId().equals(mShortcutId);
}
diff --git a/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java b/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java
index ea746d1..faad961 100644
--- a/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java
+++ b/services/tests/servicestests/src/com/android/server/camera/CameraServiceProxyTest.java
@@ -30,7 +30,7 @@
import android.view.Display;
import android.view.Surface;
-import java.util.HashMap;
+import java.util.Map;
@RunWith(JUnit4.class)
public class CameraServiceProxyTest {
@@ -75,24 +75,22 @@
/*ignoreResizableAndSdkCheck*/true)).isEqualTo(
CameraMetadata.SCALER_ROTATE_AND_CROP_NONE);
// Check rotation and lens facing combinations
- HashMap<Integer, Integer> backFacingMap = new HashMap<Integer, Integer>() {{
- put(Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE);
- put(Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_90);
- put(Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_270);
- put(Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180);
- }};
+ Map<Integer, Integer> backFacingMap = Map.of(
+ Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE,
+ Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_90,
+ Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_270,
+ Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180);
taskInfo.isFixedOrientationPortrait = true;
backFacingMap.forEach((key, value) -> {
assertThat(CameraServiceProxy.getCropRotateScale(ctx, ctx.getPackageName(), taskInfo,
key, CameraCharacteristics.LENS_FACING_BACK,
/*ignoreResizableAndSdkCheck*/true)).isEqualTo(value);
});
- HashMap<Integer, Integer> frontFacingMap = new HashMap<Integer, Integer>() {{
- put(Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE);
- put(Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_270);
- put(Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_90);
- put(Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180);
- }};
+ Map<Integer, Integer> frontFacingMap = Map.of(
+ Surface.ROTATION_0, CameraMetadata.SCALER_ROTATE_AND_CROP_NONE,
+ Surface.ROTATION_90, CameraMetadata.SCALER_ROTATE_AND_CROP_270,
+ Surface.ROTATION_270, CameraMetadata.SCALER_ROTATE_AND_CROP_90,
+ Surface.ROTATION_180, CameraMetadata.SCALER_ROTATE_AND_CROP_180);
frontFacingMap.forEach((key, value) -> {
assertThat(CameraServiceProxy.getCropRotateScale(ctx, ctx.getPackageName(), taskInfo,
key, CameraCharacteristics.LENS_FACING_FRONT,
diff --git a/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java
index df672c9..2c4fe53 100644
--- a/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java
+++ b/services/tests/servicestests/src/com/android/server/display/AmbientBrightnessStatsTrackerTest.java
@@ -424,7 +424,7 @@
@Override
public LocalDate getLocalDate() {
- return LocalDate.from(mLocalDate);
+ return mLocalDate;
}
}
diff --git a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
index 8112ca8..aceae72 100644
--- a/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
+++ b/services/tests/servicestests/src/com/android/server/hdmi/HdmiCecLocalDeviceTvTest.java
@@ -842,4 +842,53 @@
verify(mAudioManager, never()).setStreamVolume(eq(AudioManager.STREAM_MUSIC), anyInt(),
anyInt());
}
+
+ @Test
+ public void tvSendRequestArcTerminationOnSleep() {
+ // Emulate Audio device on port 0x2000 (supports ARC)
+
+ mNativeWrapper.setPortConnectionStatus(2, true);
+ HdmiCecMessage hdmiCecMessage = HdmiCecMessageBuilder.buildReportPhysicalAddressCommand(
+ ADDR_AUDIO_SYSTEM, 0x2000, HdmiDeviceInfo.DEVICE_AUDIO_SYSTEM);
+ mNativeWrapper.onCecMessage(hdmiCecMessage);
+ mTestLooper.dispatchAll();
+
+ mHdmiCecLocalDeviceTv.startArcAction(true);
+ mTestLooper.dispatchAll();
+ HdmiCecMessage requestArcInitiation = HdmiCecMessageBuilder.buildRequestArcInitiation(
+ ADDR_TV,
+ ADDR_AUDIO_SYSTEM);
+ HdmiCecMessage requestArcTermination = HdmiCecMessageBuilder.buildRequestArcTermination(
+ ADDR_TV,
+ ADDR_AUDIO_SYSTEM);
+ HdmiCecMessage initiateArc = HdmiCecMessageBuilder.buildInitiateArc(
+ ADDR_AUDIO_SYSTEM,
+ ADDR_TV);
+ HdmiCecMessage reportArcInitiated = HdmiCecMessageBuilder.buildReportArcInitiated(
+ ADDR_TV,
+ ADDR_AUDIO_SYSTEM);
+
+ assertThat(mNativeWrapper.getResultMessages()).contains(requestArcInitiation);
+ assertThat(mNativeWrapper.getResultMessages()).doesNotContain(requestArcTermination);
+
+ mNativeWrapper.onCecMessage(initiateArc);
+ mTestLooper.dispatchAll();
+
+ // Finish querying SADs
+ assertThat(mNativeWrapper.getResultMessages()).contains(SAD_QUERY);
+ mNativeWrapper.clearResultMessages();
+ mTestLooper.moveTimeForward(HdmiConfig.TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).contains(SAD_QUERY);
+ mTestLooper.moveTimeForward(HdmiConfig.TIMEOUT_MS);
+ mTestLooper.dispatchAll();
+
+ // ARC should be established after RequestSadAction is finished
+ assertThat(mNativeWrapper.getResultMessages()).contains(reportArcInitiated);
+
+ mHdmiControlService.onStandby(HdmiControlService.STANDBY_SCREEN_OFF);
+ mTestLooper.dispatchAll();
+ assertThat(mNativeWrapper.getResultMessages()).contains(requestArcTermination);
+ }
+
}
diff --git a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
index 9092ec3..0884b78 100644
--- a/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/inputmethod/InputMethodSubtypeSwitchingControllerTest.java
@@ -367,6 +367,7 @@
assertFalse(item_en_us_allcaps.mIsSystemLocale);
}
+ @SuppressWarnings("SelfComparison")
@Test
public void testImeSubtypeListComparator() throws Exception {
final ComponentName imeX1 = new ComponentName("com.example.imeX", "Ime1");
diff --git a/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java b/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java
index 1e855a9..1eb4fa5 100644
--- a/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java
+++ b/services/tests/servicestests/src/com/android/server/locksettings/PasswordSlotManagerTestable.java
@@ -58,4 +58,4 @@
} catch (Exception e) {
}
}
-};
+}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
index 911fb6a..08c2c6e 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/BuzzBeepBlinkTest.java
@@ -1301,6 +1301,21 @@
}
@Test
+ public void testA11yCrossUserEventNotSent() throws Exception {
+ final Notification n = new Builder(getContext(), "test")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon).build();
+ int userId = mUser.getIdentifier() + 1;
+ StatusBarNotification sbn = new StatusBarNotification(mPkg, mPkg, 0, mTag, mUid,
+ mPid, n, UserHandle.of(userId), null, System.currentTimeMillis());
+ NotificationRecord r = new NotificationRecord(getContext(), sbn,
+ new NotificationChannel("test", "test", IMPORTANCE_HIGH));
+
+ mService.buzzBeepBlinkLocked(r);
+
+ verify(mAccessibilityService, never()).sendAccessibilityEvent(any(), anyInt());
+ }
+
+ @Test
public void testLightsScreenOn() {
mService.mScreenOn = true;
NotificationRecord r = getLightsNotification();
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 480ad11..535183d 100755
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -7509,6 +7509,43 @@
}
@Test
+ public void testAddAutomaticZenRule_systemCallTakesPackageFromOwner() throws Exception {
+ mService.isSystemUid = true;
+ ZenModeHelper mockZenModeHelper = mock(ZenModeHelper.class);
+ when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt()))
+ .thenReturn(true);
+ mService.setZenHelper(mockZenModeHelper);
+ ComponentName owner = new ComponentName("android", "ProviderName");
+ ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build();
+ boolean isEnabled = true;
+ AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
+ zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled);
+ mBinderService.addAutomaticZenRule(rule, "com.android.settings");
+
+ // verify that zen mode helper gets passed in a package name of "android"
+ verify(mockZenModeHelper).addAutomaticZenRule(eq("android"), eq(rule), anyString());
+ }
+
+ @Test
+ public void testAddAutomaticZenRule_nonSystemCallTakesPackageFromArg() throws Exception {
+ mService.isSystemUid = false;
+ ZenModeHelper mockZenModeHelper = mock(ZenModeHelper.class);
+ when(mConditionProviders.isPackageOrComponentAllowed(anyString(), anyInt()))
+ .thenReturn(true);
+ mService.setZenHelper(mockZenModeHelper);
+ ComponentName owner = new ComponentName("android", "ProviderName");
+ ZenPolicy zenPolicy = new ZenPolicy.Builder().allowAlarms(true).build();
+ boolean isEnabled = true;
+ AutomaticZenRule rule = new AutomaticZenRule("test", owner, owner, mock(Uri.class),
+ zenPolicy, NotificationManager.INTERRUPTION_FILTER_PRIORITY, isEnabled);
+ mBinderService.addAutomaticZenRule(rule, "another.package");
+
+ // verify that zen mode helper gets passed in the package name from the arg, not the owner
+ verify(mockZenModeHelper).addAutomaticZenRule(
+ eq("another.package"), eq(rule), anyString());
+ }
+
+ @Test
public void testAreNotificationsEnabledForPackage() throws Exception {
mBinderService.areNotificationsEnabledForPackage(mContext.getPackageName(),
mUid);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
index 598a22b..d46530c 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/PreferencesHelperTest.java
@@ -2727,7 +2727,7 @@
@Test
public void testCreateChannel_addToGroup() {
- NotificationChannelGroup group = new NotificationChannelGroup("group", "");
+ NotificationChannelGroup group = new NotificationChannelGroup("group", "group");
mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, group, true);
NotificationChannel nc = new NotificationChannel("id", "hello", IMPORTANCE_DEFAULT);
assertTrue(mHelper.createNotificationChannel(PKG_N_MR1, UID_N_MR1, nc, true, false));
@@ -3177,8 +3177,8 @@
@Test
public void testGetNotificationChannelGroupWithChannels() throws Exception {
- NotificationChannelGroup group = new NotificationChannelGroup("group", "");
- NotificationChannelGroup other = new NotificationChannelGroup("something else", "");
+ NotificationChannelGroup group = new NotificationChannelGroup("group", "group");
+ NotificationChannelGroup other = new NotificationChannelGroup("something else", "name");
mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, group, true);
mHelper.createNotificationChannelGroup(PKG_N_MR1, UID_N_MR1, other, true);
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
index 4550b56..2ccdcaa 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -1672,6 +1672,36 @@
}
@Test
+ public void testAddAutomaticZenRule_claimedSystemOwner() {
+ // Make sure anything that claims to have a "system" owner but not actually part of the
+ // system package still gets limited on number of rules
+ for (int i = 0; i < RULE_LIMIT_PER_PACKAGE; i++) {
+ ScheduleInfo si = new ScheduleInfo();
+ si.startHour = i;
+ AutomaticZenRule zenRule = new AutomaticZenRule("name" + i,
+ new ComponentName("android", "ScheduleConditionProvider" + i),
+ null, // configuration activity
+ ZenModeConfig.toScheduleConditionId(si),
+ new ZenPolicy.Builder().build(),
+ NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
+ String id = mZenModeHelperSpy.addAutomaticZenRule("pkgname", zenRule, "test");
+ assertNotNull(id);
+ }
+ try {
+ AutomaticZenRule zenRule = new AutomaticZenRule("name",
+ new ComponentName("android", "ScheduleConditionProviderFinal"),
+ null, // configuration activity
+ ZenModeConfig.toScheduleConditionId(new ScheduleInfo()),
+ new ZenPolicy.Builder().build(),
+ NotificationManager.INTERRUPTION_FILTER_PRIORITY, true);
+ String id = mZenModeHelperSpy.addAutomaticZenRule("pkgname", zenRule, "test");
+ fail("allowed too many rules to be created");
+ } catch (IllegalArgumentException e) {
+ // yay
+ }
+ }
+
+ @Test
public void testAddAutomaticZenRule_CA() {
AutomaticZenRule zenRule = new AutomaticZenRule("name",
null,
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java
index df63795..7a41b50 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCInputTerminal.java
@@ -46,4 +46,4 @@
// TODO Add reporting specific to this descriptor
super.report(canvas);
}
-};
+}
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java
index 4aa8ca2..32275a6 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCOutputTerminal.java
@@ -46,4 +46,4 @@
super.report(canvas);
// TODO Add reporting specific to this descriptor
}
-};
+}
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java
index 5ce842e..0692066 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCProcessingUnit.java
@@ -47,4 +47,4 @@
super.report(canvas);
// TODO Add reporting specific to this descriptor
}
-};
+}
diff --git a/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java b/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java
index 8e9b0d8..604dd66 100644
--- a/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java
+++ b/services/usb/java/com/android/server/usb/descriptors/UsbVCSelectorUnit.java
@@ -47,4 +47,4 @@
super.report(canvas);
// TODO Add reporting specific to this descriptor
}
-};
+}
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
index 42d446d..af626f5 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/HotwordDetectionConnection.java
@@ -1196,4 +1196,4 @@
private static final String OP_MESSAGE =
"Providing hotword detection result to VoiceInteractionService";
-};
+}
diff --git a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
index a061618..e02f2f0 100644
--- a/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
+++ b/services/voiceinteraction/java/com/android/server/voiceinteraction/VoiceInteractionSessionConnection.java
@@ -810,4 +810,4 @@
}
}
};
-};
+}
diff --git a/telecomm/OWNERS b/telecomm/OWNERS
index eb0c432..dcaf858 100644
--- a/telecomm/OWNERS
+++ b/telecomm/OWNERS
@@ -4,3 +4,7 @@
tgunn@google.com
xiaotonj@google.com
rgreenwalt@google.com
+chinmayd@google.com
+grantmenke@google.com
+pmadapurmath@google.com
+tjstuart@google.com
\ No newline at end of file
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index e0f5b20..983d82b 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -1269,7 +1269,7 @@
if (service != null) {
try {
return service.getPhoneAccountsSupportingScheme(uriScheme,
- mContext.getOpPackageName());
+ mContext.getOpPackageName()).getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsSupportingScheme", e);
}
@@ -1312,7 +1312,7 @@
if (service != null) {
try {
return service.getSelfManagedPhoneAccounts(mContext.getOpPackageName(),
- mContext.getAttributionTag());
+ mContext.getAttributionTag()).getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getSelfManagedPhoneAccounts()", e);
}
@@ -1340,7 +1340,7 @@
if (service != null) {
try {
return service.getOwnSelfManagedPhoneAccounts(mContext.getOpPackageName(),
- mContext.getAttributionTag());
+ mContext.getAttributionTag()).getList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1366,7 +1366,7 @@
if (service != null) {
try {
return service.getCallCapablePhoneAccounts(includeDisabledAccounts,
- mContext.getOpPackageName(), mContext.getAttributionTag());
+ mContext.getOpPackageName(), mContext.getAttributionTag()).getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getCallCapablePhoneAccounts("
+ includeDisabledAccounts + ")", e);
@@ -1390,7 +1390,7 @@
ITelecomService service = getTelecomService();
if (service != null) {
try {
- return service.getPhoneAccountsForPackage(mContext.getPackageName());
+ return service.getPhoneAccountsForPackage(mContext.getPackageName()).getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getPhoneAccountsForPackage", e);
}
@@ -1450,7 +1450,7 @@
ITelecomService service = getTelecomService();
if (service != null) {
try {
- return service.getAllPhoneAccounts();
+ return service.getAllPhoneAccounts().getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccounts", e);
}
@@ -1469,7 +1469,7 @@
ITelecomService service = getTelecomService();
if (service != null) {
try {
- return service.getAllPhoneAccountHandles();
+ return service.getAllPhoneAccountHandles().getList();
} catch (RemoteException e) {
Log.e(TAG, "Error calling ITelecomService#getAllPhoneAccountHandles", e);
}
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index 37403a8..74b5545 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -24,6 +24,7 @@
import android.os.Bundle;
import android.os.UserHandle;
import android.telecom.PhoneAccount;
+import android.content.pm.ParceledListSlice;
/**
* Interface used to interact with Telecom. Mostly this is used by TelephonyManager for passing
@@ -57,31 +58,31 @@
/**
* @see TelecomServiceImpl#getCallCapablePhoneAccounts
*/
- List<PhoneAccountHandle> getCallCapablePhoneAccounts(
+ ParceledListSlice<PhoneAccountHandle> getCallCapablePhoneAccounts(
boolean includeDisabledAccounts, String callingPackage, String callingFeatureId);
/**
* @see TelecomServiceImpl#getSelfManagedPhoneAccounts
*/
- List<PhoneAccountHandle> getSelfManagedPhoneAccounts(String callingPackage,
+ ParceledListSlice<PhoneAccountHandle> getSelfManagedPhoneAccounts(String callingPackage,
String callingFeatureId);
/**
* @see TelecomServiceImpl#getOwnSelfManagedPhoneAccounts
*/
- List<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts(String callingPackage,
+ ParceledListSlice<PhoneAccountHandle> getOwnSelfManagedPhoneAccounts(String callingPackage,
String callingFeatureId);
/**
* @see TelecomManager#getPhoneAccountsSupportingScheme
*/
- List<PhoneAccountHandle> getPhoneAccountsSupportingScheme(in String uriScheme,
+ ParceledListSlice<PhoneAccountHandle> getPhoneAccountsSupportingScheme(in String uriScheme,
String callingPackage);
/**
* @see TelecomManager#getPhoneAccountsForPackage
*/
- List<PhoneAccountHandle> getPhoneAccountsForPackage(in String packageName);
+ ParceledListSlice<PhoneAccountHandle> getPhoneAccountsForPackage(in String packageName);
/**
* @see TelecomManager#getPhoneAccount
@@ -96,12 +97,12 @@
/**
* @see TelecomManager#getAllPhoneAccounts
*/
- List<PhoneAccount> getAllPhoneAccounts();
+ ParceledListSlice<PhoneAccount> getAllPhoneAccounts();
/**
* @see TelecomManager#getAllPhoneAccountHandles
*/
- List<PhoneAccountHandle> getAllPhoneAccountHandles();
+ ParceledListSlice<PhoneAccountHandle> getAllPhoneAccountHandles();
/**
* @see TelecomServiceImpl#getSimCallManager
diff --git a/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java b/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java
index 8b01cb3..2787d83 100644
--- a/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java
+++ b/telephony/common/com/google/android/mms/pdu/EncodedStringValue.java
@@ -199,7 +199,6 @@
*/
@Override
public Object clone() throws CloneNotSupportedException {
- super.clone();
int len = mData.length;
byte[] dstBytes = new byte[len];
System.arraycopy(mData, 0, dstBytes, 0, len);
diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java
index bb0522c..bd993f2 100644
--- a/telephony/java/android/telephony/CarrierConfigManager.java
+++ b/telephony/java/android/telephony/CarrierConfigManager.java
@@ -8478,7 +8478,12 @@
*
* Used to trade privacy/security against potentially reduced carrier coverage for some
* carriers.
+ *
+ * @deprecated Future versions of Android will disallow carriers from hiding this toggle
+ * because disabling 2g is a security feature that users should always have access to at
+ * their discretion.
*/
+ @Deprecated
public static final String KEY_HIDE_ENABLE_2G = "hide_enable_2g_bool";
/**
diff --git a/telephony/java/android/telephony/DataFailCause.java b/telephony/java/android/telephony/DataFailCause.java
index 5f7cfd1..5186c72 100644
--- a/telephony/java/android/telephony/DataFailCause.java
+++ b/telephony/java/android/telephony/DataFailCause.java
@@ -1613,29 +1613,26 @@
// If we are not able to find the configuration from carrier config, use the default
// ones.
if (permanentFailureSet == null) {
- permanentFailureSet = new HashSet<Integer>() {
- {
- add(OPERATOR_BARRED);
- add(MISSING_UNKNOWN_APN);
- add(UNKNOWN_PDP_ADDRESS_TYPE);
- add(USER_AUTHENTICATION);
- add(ACTIVATION_REJECT_GGSN);
- add(SERVICE_OPTION_NOT_SUPPORTED);
- add(SERVICE_OPTION_NOT_SUBSCRIBED);
- add(NSAPI_IN_USE);
- add(ONLY_IPV4_ALLOWED);
- add(ONLY_IPV6_ALLOWED);
- add(PROTOCOL_ERRORS);
- add(RADIO_POWER_OFF);
- add(TETHERED_CALL_ACTIVE);
- add(RADIO_NOT_AVAILABLE);
- add(UNACCEPTABLE_NETWORK_PARAMETER);
- add(SIGNAL_LOST);
- add(DUPLICATE_CID);
- add(MATCH_ALL_RULE_NOT_ALLOWED);
- add(ALL_MATCHING_RULES_FAILED);
- }
- };
+ permanentFailureSet = new HashSet<Integer>();
+ permanentFailureSet.add(OPERATOR_BARRED);
+ permanentFailureSet.add(MISSING_UNKNOWN_APN);
+ permanentFailureSet.add(UNKNOWN_PDP_ADDRESS_TYPE);
+ permanentFailureSet.add(USER_AUTHENTICATION);
+ permanentFailureSet.add(ACTIVATION_REJECT_GGSN);
+ permanentFailureSet.add(SERVICE_OPTION_NOT_SUPPORTED);
+ permanentFailureSet.add(SERVICE_OPTION_NOT_SUBSCRIBED);
+ permanentFailureSet.add(NSAPI_IN_USE);
+ permanentFailureSet.add(ONLY_IPV4_ALLOWED);
+ permanentFailureSet.add(ONLY_IPV6_ALLOWED);
+ permanentFailureSet.add(PROTOCOL_ERRORS);
+ permanentFailureSet.add(RADIO_POWER_OFF);
+ permanentFailureSet.add(TETHERED_CALL_ACTIVE);
+ permanentFailureSet.add(RADIO_NOT_AVAILABLE);
+ permanentFailureSet.add(UNACCEPTABLE_NETWORK_PARAMETER);
+ permanentFailureSet.add(SIGNAL_LOST);
+ permanentFailureSet.add(DUPLICATE_CID);
+ permanentFailureSet.add(MATCH_ALL_RULE_NOT_ALLOWED);
+ permanentFailureSet.add(ALL_MATCHING_RULES_FAILED);
}
permanentFailureSet.add(NO_RETRY_FAILURE);
diff --git a/telephony/java/android/telephony/RadioAccessSpecifier.java b/telephony/java/android/telephony/RadioAccessSpecifier.java
index a403095..9511db6 100644
--- a/telephony/java/android/telephony/RadioAccessSpecifier.java
+++ b/telephony/java/android/telephony/RadioAccessSpecifier.java
@@ -161,9 +161,17 @@
}
@Override
- public int hashCode () {
+ public int hashCode() {
return ((mRadioAccessNetwork * 31)
+ (Arrays.hashCode(mBands) * 37)
+ (Arrays.hashCode(mChannels)) * 39);
}
+
+ @Override
+ public String toString() {
+ return "RadioAccessSpecifier[mRadioAccessNetwork="
+ + AccessNetworkConstants.AccessNetworkType.toString(mRadioAccessNetwork)
+ + ", mBands=" + Arrays.toString(mBands)
+ + ", mChannels=" + Arrays.toString(mChannels) + "]";
+ }
}
diff --git a/telephony/java/android/telephony/SmsMessage.java b/telephony/java/android/telephony/SmsMessage.java
index e0145e6..c2b65f8 100644
--- a/telephony/java/android/telephony/SmsMessage.java
+++ b/telephony/java/android/telephony/SmsMessage.java
@@ -1092,6 +1092,11 @@
if (!TextUtils.isEmpty(simOperator)) {
for (NoEmsSupportConfig currentConfig : mNoEmsSupportConfigList) {
+ if (currentConfig == null) {
+ Rlog.w("SmsMessage", "hasEmsSupport currentConfig is null");
+ continue;
+ }
+
if (simOperator.startsWith(currentConfig.mOperatorNumber) &&
(TextUtils.isEmpty(currentConfig.mGid1) ||
(!TextUtils.isEmpty(currentConfig.mGid1) &&
@@ -1155,18 +1160,21 @@
private static boolean mIsNoEmsSupportConfigListLoaded = false;
private static boolean isNoEmsSupportConfigListExisted() {
- if (!mIsNoEmsSupportConfigListLoaded) {
- Resources r = Resources.getSystem();
- if (r != null) {
- String[] listArray = r.getStringArray(
- com.android.internal.R.array.no_ems_support_sim_operators);
- if ((listArray != null) && (listArray.length > 0)) {
- mNoEmsSupportConfigList = new NoEmsSupportConfig[listArray.length];
- for (int i=0; i<listArray.length; i++) {
- mNoEmsSupportConfigList[i] = new NoEmsSupportConfig(listArray[i].split(";"));
+ synchronized (SmsMessage.class) {
+ if (!mIsNoEmsSupportConfigListLoaded) {
+ Resources r = Resources.getSystem();
+ if (r != null) {
+ String[] listArray = r.getStringArray(
+ com.android.internal.R.array.no_ems_support_sim_operators);
+ if ((listArray != null) && (listArray.length > 0)) {
+ mNoEmsSupportConfigList = new NoEmsSupportConfig[listArray.length];
+ for (int i = 0; i < listArray.length; i++) {
+ mNoEmsSupportConfigList[i] = new NoEmsSupportConfig(
+ listArray[i].split(";"));
+ }
}
+ mIsNoEmsSupportConfigListLoaded = true;
}
- mIsNoEmsSupportConfigListLoaded = true;
}
}
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index a081bc3..3b376fb 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -9409,12 +9409,13 @@
/**
* Set the allowed network types of the device and provide the reason triggering the allowed
* network change.
- * <p>Requires permission: android.Manifest.MODIFY_PHONE_STATE or
+ * <p>Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} or
* that the calling app has carrier privileges (see {@link #hasCarrierPrivileges}).
*
- * This can be called for following reasons
+ * This can be called for following reasons:
* <ol>
- * <li>Allowed network types control by USER {@link #ALLOWED_NETWORK_TYPES_REASON_USER}
+ * <li>Allowed network types control by USER
+ * {@link TelephonyManager#ALLOWED_NETWORK_TYPES_REASON_USER}
* <li>Allowed network types control by carrier {@link #ALLOWED_NETWORK_TYPES_REASON_CARRIER}
* </ol>
* This API will result in allowing an intersection of allowed network types for all reasons,
@@ -9424,7 +9425,13 @@
* @param allowedNetworkTypes The bitmask of allowed network type
* @throws IllegalStateException if the Telephony process is not currently available.
* @throws IllegalArgumentException if invalid AllowedNetworkTypesReason is passed.
- * @throws SecurityException if the caller does not have the required privileges
+ * @throws SecurityException if the caller does not have the required privileges or if the
+ * caller tries to use one of the following security-based reasons without
+ * {@link android.Manifest.permission#MODIFY_PHONE_STATE} permissions.
+ * <ol>
+ * <li>{@code TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_ENABLE_2G}</li>
+ * <li>{@code TelephonyManager.ALLOWED_NETWORK_TYPES_REASON_USER_RESTRICTIONS}</li>
+ * </ol>
*/
@RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
@RequiresFeature(
diff --git a/telephony/java/android/telephony/ims/ImsService.java b/telephony/java/android/telephony/ims/ImsService.java
index bccb6ef..4477f81 100644
--- a/telephony/java/android/telephony/ims/ImsService.java
+++ b/telephony/java/android/telephony/ims/ImsService.java
@@ -50,7 +50,6 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
@@ -164,10 +163,9 @@
* Used for logging purposes, see {@link #getCapabilitiesString(long)}
* @hide
*/
- private static final Map<Long, String> CAPABILITIES_LOG_MAP = new HashMap<Long, String>() {{
- put(CAPABILITY_EMERGENCY_OVER_MMTEL, "EMERGENCY_OVER_MMTEL");
- put(CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION");
- }};
+ private static final Map<Long, String> CAPABILITIES_LOG_MAP = Map.of(
+ CAPABILITY_EMERGENCY_OVER_MMTEL, "EMERGENCY_OVER_MMTEL",
+ CAPABILITY_SIP_DELEGATE_CREATION, "SIP_DELEGATE_CREATION");
/**
* The intent that must be defined as an intent-filter in the AndroidManifest of the ImsService.
diff --git a/telephony/java/android/telephony/ims/RegistrationManager.java b/telephony/java/android/telephony/ims/RegistrationManager.java
index 090d413..9996b86 100644
--- a/telephony/java/android/telephony/ims/RegistrationManager.java
+++ b/telephony/java/android/telephony/ims/RegistrationManager.java
@@ -78,24 +78,22 @@
/**@hide*/
// Translate ImsRegistrationImplBase API to new AccessNetworkConstant because WLAN
// and WWAN are more accurate constants.
- Map<Integer, Integer> IMS_REG_TO_ACCESS_TYPE_MAP =
- new HashMap<Integer, Integer>() {{
- // Map NONE to -1 to make sure that we handle the REGISTRATION_TECH_NONE
- // case, since it is defined.
- put(ImsRegistrationImplBase.REGISTRATION_TECH_NONE,
- AccessNetworkConstants.TRANSPORT_TYPE_INVALID);
- put(ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
- AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
- put(ImsRegistrationImplBase.REGISTRATION_TECH_NR,
- AccessNetworkConstants.TRANSPORT_TYPE_WWAN);
- put(ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN,
- AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
- /* As the cross sim will be using ePDG tunnel over internet, it behaves
- like IWLAN in most cases. Hence setting the access type as IWLAN
- */
- put(ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM,
- AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
- }};
+ Map<Integer, Integer> IMS_REG_TO_ACCESS_TYPE_MAP = Map.of(
+ // Map NONE to -1 to make sure that we handle the REGISTRATION_TECH_NONE
+ // case, since it is defined.
+ ImsRegistrationImplBase.REGISTRATION_TECH_NONE,
+ AccessNetworkConstants.TRANSPORT_TYPE_INVALID,
+ ImsRegistrationImplBase.REGISTRATION_TECH_LTE,
+ AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
+ ImsRegistrationImplBase.REGISTRATION_TECH_NR,
+ AccessNetworkConstants.TRANSPORT_TYPE_WWAN,
+ ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN,
+ /* As the cross sim will be using ePDG tunnel over internet, it behaves
+ like IWLAN in most cases. Hence setting the access type as IWLAN
+ */
+ ImsRegistrationImplBase.REGISTRATION_TECH_CROSS_SIM,
+ AccessNetworkConstants.TRANSPORT_TYPE_WLAN);
/** @hide */
@NonNull
diff --git a/telephony/java/android/telephony/ims/feature/ImsFeature.java b/telephony/java/android/telephony/ims/feature/ImsFeature.java
index a42327b..174675f 100644
--- a/telephony/java/android/telephony/ims/feature/ImsFeature.java
+++ b/telephony/java/android/telephony/ims/feature/ImsFeature.java
@@ -34,7 +34,6 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import java.util.HashMap;
import java.util.Map;
/**
@@ -85,11 +84,10 @@
* Used for logging purposes.
* @hide
*/
- public static final Map<Integer, String> FEATURE_LOG_MAP = new HashMap<Integer, String>() {{
- put(FEATURE_EMERGENCY_MMTEL, "EMERGENCY_MMTEL");
- put(FEATURE_MMTEL, "MMTEL");
- put(FEATURE_RCS, "RCS");
- }};
+ public static final Map<Integer, String> FEATURE_LOG_MAP = Map.of(
+ FEATURE_EMERGENCY_MMTEL, "EMERGENCY_MMTEL",
+ FEATURE_MMTEL, "MMTEL",
+ FEATURE_RCS, "RCS");
/**
* Integer values defining IMS features that are supported in ImsFeature.
@@ -145,11 +143,10 @@
* Used for logging purposes.
* @hide
*/
- public static final Map<Integer, String> STATE_LOG_MAP = new HashMap<Integer, String>() {{
- put(STATE_UNAVAILABLE, "UNAVAILABLE");
- put(STATE_INITIALIZING, "INITIALIZING");
- put(STATE_READY, "READY");
- }};
+ public static final Map<Integer, String> STATE_LOG_MAP = Map.of(
+ STATE_UNAVAILABLE, "UNAVAILABLE",
+ STATE_INITIALIZING, "INITIALIZING",
+ STATE_READY, "READY");
/**
* Integer values defining the result codes that should be returned from
diff --git a/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java b/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java
index 0f4e122..4bcf5a4 100644
--- a/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java
+++ b/tests/CanvasCompare/src/com/android/test/hwuicompare/DisplayModifier.java
@@ -16,14 +16,16 @@
package com.android.test.hwuicompare;
-import java.util.LinkedHashMap;
-import java.util.Map.Entry;
+import static java.util.Map.entry;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.Log;
+import java.util.Map;
+import java.util.Map.Entry;
+
public abstract class DisplayModifier {
// automated tests ignore any combination of operations that don't together return TOTAL_MASK
@@ -76,41 +78,36 @@
};
@SuppressWarnings("serial")
- private static final LinkedHashMap<String, LinkedHashMap<String, DisplayModifier>> gMaps = new LinkedHashMap<String, LinkedHashMap<String, DisplayModifier>>() {
- {
- put("aa", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("true", new DisplayModifier() {
+ private static final Map<String, Map<String, DisplayModifier>> gMaps = Map.of(
+ "aa", Map.of(
+ "true", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setAntiAlias(true);
}
- });
- put("false", new DisplayModifier() {
+ },
+ "false", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setAntiAlias(false);
}
- });
- }
- });
- put("style", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("fill", new DisplayModifier() {
+ }),
+ "style", Map.of(
+ "fill", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStyle(Paint.Style.FILL);
}
- });
- put("stroke", new DisplayModifier() {
+ },
+ "stroke", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStyle(Paint.Style.STROKE);
}
@Override
protected int mask() { return SWEEP_STROKE_WIDTH_BIT; }
- });
- put("fillAndStroke", new DisplayModifier() {
+ },
+ "fillAndStroke", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStyle(Paint.Style.FILL_AND_STROKE);
@@ -118,131 +115,118 @@
@Override
protected int mask() { return SWEEP_STROKE_WIDTH_BIT; }
- });
- }
- });
- put("strokeWidth", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("hair", new DisplayModifier() {
+ }),
+ "strokeWidth", Map.of(
+ "hair", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeWidth(0);
}
@Override
protected int mask() { return SWEEP_STROKE_WIDTH_BIT; }
- });
- put("0.3", new DisplayModifier() {
+ },
+ "0.3", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeWidth(0.3f);
}
- });
- put("1", new DisplayModifier() {
+ },
+ "1", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeWidth(1);
}
- });
- put("5", new DisplayModifier() {
+ },
+ "5", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeWidth(5);
}
- });
- put("30", new DisplayModifier() {
+ },
+ "30", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeWidth(30);
}
- });
- }
- });
- put("strokeCap", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("butt", new DisplayModifier() {
+ }),
+ "strokeCap", Map.of(
+ "butt", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeCap(Paint.Cap.BUTT);
}
@Override
protected int mask() { return SWEEP_STROKE_CAP_BIT; }
- });
- put("round", new DisplayModifier() {
+ },
+ "round", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeCap(Paint.Cap.ROUND);
}
- });
- put("square", new DisplayModifier() {
+ },
+ "square", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeCap(Paint.Cap.SQUARE);
}
- });
- }
- });
- put("strokeJoin", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("bevel", new DisplayModifier() {
+ }),
+ "strokeJoin", Map.of(
+ "bevel", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeJoin(Paint.Join.BEVEL);
}
@Override
protected int mask() { return SWEEP_STROKE_JOIN_BIT; }
- });
- put("round", new DisplayModifier() {
+ },
+ "round", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeJoin(Paint.Join.ROUND);
}
- });
- put("miter", new DisplayModifier() {
+ },
+ "miter", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setStrokeJoin(Paint.Join.MITER);
}
- });
+ }),
// TODO: add miter0, miter1 etc to test miter distances
- }
- });
-
- put("transform", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("noTransform", new DisplayModifier() {
+ "transform", Map.of(
+ "noTransform", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {}
@Override
protected int mask() { return SWEEP_TRANSFORM_BIT; };
- });
- put("rotate5", new DisplayModifier() {
+ },
+ "rotate5", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.rotate(5);
}
- });
- put("rotate45", new DisplayModifier() {
+ },
+ "rotate45", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.rotate(45);
}
- });
- put("rotate90", new DisplayModifier() {
+ },
+ "rotate90", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.rotate(90);
canvas.translate(0, -200);
}
- });
- put("scale2x2", new DisplayModifier() {
+ },
+ "scale2x2", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.scale(2, 2);
}
@Override
protected int mask() { return SWEEP_TRANSFORM_BIT; };
- });
- put("rot20scl1x4", new DisplayModifier() {
+ },
+ "rot20scl1x4", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.rotate(20);
@@ -250,180 +234,167 @@
}
@Override
protected int mask() { return SWEEP_TRANSFORM_BIT; };
- });
- }
- });
-
- put("shader", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("noShader", new DisplayModifier() {
+ }),
+ "shader", Map.ofEntries(
+ entry("noShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {}
@Override
protected int mask() { return SWEEP_SHADER_BIT; };
- });
- put("repeatShader", new DisplayModifier() {
+ }),
+ entry("repeatShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mRepeatShader);
}
@Override
protected int mask() { return SWEEP_SHADER_BIT; };
- });
- put("translatedShader", new DisplayModifier() {
+ }),
+ entry("translatedShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mTranslatedShader);
}
- });
- put("scaledShader", new DisplayModifier() {
+ }),
+ entry("scaledShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mScaledShader);
}
- });
- put("horGradient", new DisplayModifier() {
+ }),
+ entry("horGradient", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mHorGradient);
}
- });
- put("diagGradient", new DisplayModifier() {
+ }),
+ entry("diagGradient", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mDiagGradient);
}
@Override
protected int mask() { return SWEEP_SHADER_BIT; };
- });
- put("vertGradient", new DisplayModifier() {
+ }),
+ entry("vertGradient", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mVertGradient);
}
- });
- put("radGradient", new DisplayModifier() {
+ }),
+ entry("radGradient", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mRadGradient);
}
- });
- put("sweepGradient", new DisplayModifier() {
+ }),
+ entry("sweepGradient", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mSweepGradient);
}
- });
- put("composeShader", new DisplayModifier() {
+ }),
+ entry("composeShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mComposeShader);
}
- });
- put("bad composeShader", new DisplayModifier() {
+ }),
+ entry("bad composeShader", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mBadComposeShader);
}
- });
- put("bad composeShader 2", new DisplayModifier() {
+ }),
+ entry("bad composeShader 2", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setShader(ResourceModifiers.instance().mAnotherBadComposeShader);
}
- });
- }
- });
-
- // FINAL MAP: DOES ACTUAL DRAWING
- put("drawing", new LinkedHashMap<String, DisplayModifier>() {
- {
- put("roundRect", new DisplayModifier() {
+ })),
+ "drawing", Map.ofEntries(
+ entry("roundRect", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawRoundRect(gRect, 20, 20, paint);
}
- });
- put("rect", new DisplayModifier() {
+ }),
+ entry("rect", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawRect(gRect, paint);
}
@Override
protected int mask() { return SWEEP_SHADER_BIT | SWEEP_STROKE_CAP_BIT; };
- });
- put("circle", new DisplayModifier() {
+ }),
+ entry("circle", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawCircle(100, 100, 75, paint);
}
- });
- put("oval", new DisplayModifier() {
+ }),
+ entry("oval", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawOval(gRect, paint);
}
- });
- put("lines", new DisplayModifier() {
+ }),
+ entry("lines", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawLines(gLinePts, paint);
}
@Override
protected int mask() { return SWEEP_STROKE_CAP_BIT; };
- });
- put("plusPoints", new DisplayModifier() {
+ }),
+ entry("plusPoints", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawPoints(gPts, paint);
}
- });
- put("text", new DisplayModifier() {
+ }),
+ entry("text", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setTextSize(36);
canvas.drawText("TEXTTEST", 0, 50, paint);
}
- });
- put("shadowtext", new DisplayModifier() {
+ }),
+ entry("shadowtext", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
paint.setTextSize(36);
paint.setShadowLayer(3.0f, 0.0f, 3.0f, 0xffff00ff);
canvas.drawText("TEXTTEST", 0, 50, paint);
}
- });
- put("bitmapMesh", new DisplayModifier() {
+ }),
+ entry("bitmapMesh", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawBitmapMesh(ResourceModifiers.instance().mBitmap, 3, 3,
ResourceModifiers.instance().mBitmapVertices, 0, null, 0, null);
}
- });
- put("arc", new DisplayModifier() {
+ }),
+ entry("arc", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawArc(gRect, 260, 285, false, paint);
}
@Override
protected int mask() { return SWEEP_STROKE_CAP_BIT; };
- });
- put("arcFromCenter", new DisplayModifier() {
+ }),
+ entry("arcFromCenter", new DisplayModifier() {
@Override
public void modifyDrawing(Paint paint, Canvas canvas) {
canvas.drawArc(gRect, 260, 285, true, paint);
}
@Override
protected int mask() { return SWEEP_STROKE_JOIN_BIT; };
- });
- }
- });
+ })));
// WARNING: DON'T PUT MORE MAPS BELOW THIS
- }
- };
- private static LinkedHashMap<String, DisplayModifier> getMapAtIndex(int index) {
- for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) {
+ private static Map<String, DisplayModifier> getMapAtIndex(int index) {
+ for (Map<String, DisplayModifier> map : gMaps.values()) {
if (index == 0) {
return map;
}
@@ -439,7 +410,7 @@
private static boolean stepInternal(boolean forward) {
int modifierMapIndex = gMaps.size() - 1;
while (modifierMapIndex >= 0) {
- LinkedHashMap<String, DisplayModifier> map = getMapAtIndex(modifierMapIndex);
+ Map<String, DisplayModifier> map = getMapAtIndex(modifierMapIndex);
mIndices[modifierMapIndex] += (forward ? 1 : -1);
if (mIndices[modifierMapIndex] >= 0 && mIndices[modifierMapIndex] < map.size()) {
@@ -471,7 +442,7 @@
private static boolean checkModificationStateMask() {
int operatorMask = 0x0;
int mapIndex = 0;
- for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) {
+ for (Map<String, DisplayModifier> map : gMaps.values()) {
int displayModifierIndex = mIndices[mapIndex];
for (Entry<String, DisplayModifier> modifierEntry : map.entrySet()) {
if (displayModifierIndex == 0) {
@@ -488,7 +459,7 @@
public static void apply(Paint paint, Canvas canvas) {
int mapIndex = 0;
- for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) {
+ for (Map<String, DisplayModifier> map : gMaps.values()) {
int displayModifierIndex = mIndices[mapIndex];
for (Entry<String, DisplayModifier> modifierEntry : map.entrySet()) {
if (displayModifierIndex == 0) {
@@ -510,7 +481,7 @@
String[][] keys = new String[gMaps.size()][];
int i = 0;
- for (LinkedHashMap<String, DisplayModifier> map : gMaps.values()) {
+ for (Map<String, DisplayModifier> map : gMaps.values()) {
keys[i] = new String[map.size()];
int j = 0;
for (String key : map.keySet()) {
diff --git a/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java b/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java
index 2ad0da9..8b9c020 100644
--- a/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java
+++ b/tests/HierarchyViewerTest/src/com/android/test/hierarchyviewer/ViewDumpParser.java
@@ -58,7 +58,7 @@
Object hash = getProperty(props, "__hash__");
if (name instanceof String && hash instanceof Integer) {
- return String.format(Locale.US, "%s@%x", name, hash);
+ return String.format(Locale.US, "%s@%x", name, (Integer) hash);
} else {
return null;
}
diff --git a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
index 4de51fb..43dc9de 100644
--- a/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
+++ b/tests/JankBench/app/src/main/java/com/android/benchmark/app/HomeActivity.java
@@ -140,9 +140,9 @@
handleNextBenchmark();
}
+ @SuppressWarnings("MissingSuperCall") // TODO: Fix me
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
-
}
private void handleNextBenchmark() {
diff --git a/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java b/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java
index c16efbd..d015a56 100644
--- a/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java
+++ b/tests/JankBench/app/src/main/java/com/android/benchmark/app/RunLocalBenchmarksActivity.java
@@ -367,6 +367,7 @@
}
}
+ @SuppressWarnings("MissingSuperCall") // TODO: Fix me
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
diff --git a/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java
index 8afe841..17fa210 100644
--- a/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java
+++ b/tests/MirrorSurfaceTest/src/com/google/android/test/mirrorsurface/MirrorSurfaceActivity.java
@@ -295,8 +295,8 @@
private void updateMirror(Rect displayFrame, float scale) {
if (displayFrame.isEmpty()) {
Rect bounds = mWindowBounds;
- int defaultCropW = Math.round(bounds.width() / 2);
- int defaultCropH = Math.round(bounds.height() / 2);
+ int defaultCropW = bounds.width() / 2;
+ int defaultCropH = bounds.height() / 2;
displayFrame.set(0, 0, defaultCropW, defaultCropH);
}
diff --git a/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java b/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java
index 241206d..65b7549 100644
--- a/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java
+++ b/tests/RenderThreadTest/src/com/example/renderthread/MainActivity.java
@@ -24,18 +24,14 @@
static final String KEY_NAME = "name";
static final String KEY_CLASS = "clazz";
- static Map<String,?> make(String name) {
- Map<String,Object> ret = new HashMap<String,Object>();
- ret.put(KEY_NAME, name);
- return ret;
- }
-
- @SuppressWarnings("serial")
- static final ArrayList<Map<String,?>> SAMPLES = new ArrayList<Map<String,?>>() {{
+ static final ArrayList<Map<String, ?>> SAMPLES = new ArrayList<>();
+ static {
for (int i = 1; i < 25; i++) {
- add(make("List Item: " + i));
+ Map<String, Object> sample = new HashMap<String, Object>();
+ sample.put(KEY_NAME, "List Item: " + i);
+ SAMPLES.add(sample);
}
- }};
+ }
Handler mHandler = new Handler();
diff --git a/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java b/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java
index c11b0f3..f85fb0f 100644
--- a/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java
+++ b/tests/SmokeTestApps/src/com/android/smoketest/triggers/CrashyApp.java
@@ -30,6 +30,7 @@
setContentView(tv);
}
+ @SuppressWarnings("ReturnValueIgnored")
@Override
public void onResume() {
((String) null).length();
diff --git a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
index 3da8b46..133c176 100644
--- a/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
+++ b/tests/utils/testutils/java/com/android/internal/util/test/BroadcastInterceptingContext.java
@@ -147,12 +147,39 @@
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
- return registerReceiver(receiver, filter, null, null);
+ return registerReceiver(receiver, filter, null, null, 0);
+ }
+
+ /**
+ * Registers the specified {@code receiver} to listen for broadcasts that match the {@code
+ * filter} in the current process.
+ *
+ * <p>Since this method only listens for broadcasts in the current process, the provided {@code
+ * flags} are ignored; this method is primarily intended to allow receivers that register with
+ * flags to register in the current process during tests.
+ */
+ @Override
+ public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, int flags) {
+ return registerReceiver(receiver, filter, null, null, flags);
}
@Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
String broadcastPermission, Handler scheduler) {
+ return registerReceiver(receiver, filter, broadcastPermission, scheduler, 0);
+ }
+
+ /**
+ * Registers the specified {@code receiver} to listen for broadcasts that match the {@code
+ * filter} to run in the context of the specified {@code scheduler} in the current process.
+ *
+ * <p>Since this method only listens for broadcasts in the current process, the provided {@code
+ * flags} are ignored; this method is primarily intended to allow receivers that register with
+ * flags to register in the current process during tests.
+ */
+ @Override
+ public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
+ String broadcastPermission, Handler scheduler, int flags) {
synchronized (mInterceptors) {
mInterceptors.add(new BroadcastInterceptor(receiver, filter, scheduler));
}
diff --git a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
index f924b2e..ad06830 100644
--- a/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
+++ b/tests/vcn/java/com/android/server/VcnManagementServiceTest.java
@@ -637,8 +637,7 @@
final BroadcastReceiver receiver = getPackageChangeReceiver();
verify(mMockContext).registerReceiver(any(), argThat(filter -> {
- return filter.hasAction(Intent.ACTION_PACKAGE_REMOVED)
- && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED);
+ return filter.hasAction(Intent.ACTION_PACKAGE_REMOVED);
}), any(), any());
receiver.onReceive(mMockContext, new Intent(Intent.ACTION_PACKAGE_REMOVED));
diff --git a/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java b/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java
index a750696..5012622 100644
--- a/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java
+++ b/wifi/tests/src/android/net/wifi/nl80211/WifiNl80211ManagerTest.java
@@ -117,13 +117,12 @@
private static final byte[] TEST_PSK =
new byte[]{'T', 'e', 's', 't'};
- private static final Set<Integer> SCAN_FREQ_SET =
- new HashSet<Integer>() {{
- add(2410);
- add(2450);
- add(5050);
- add(5200);
- }};
+ private static final Set<Integer> SCAN_FREQ_SET = Set.of(
+ 2410,
+ 2450,
+ 5050,
+ 5200);
+
private static final String TEST_QUOTED_SSID_1 = "\"testSsid1\"";
private static final String TEST_QUOTED_SSID_2 = "\"testSsid2\"";
private static final int[] TEST_FREQUENCIES_1 = {};
@@ -131,13 +130,11 @@
private static final MacAddress TEST_RAW_MAC_BYTES = MacAddress.fromBytes(
new byte[]{0x00, 0x01, 0x02, 0x03, 0x04, 0x05});
- private static final List<byte[]> SCAN_HIDDEN_NETWORK_SSID_LIST =
- new ArrayList<byte[]>() {{
- add(LocalNativeUtil.byteArrayFromArrayList(
- LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1)));
- add(LocalNativeUtil.byteArrayFromArrayList(
- LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2)));
- }};
+ private static final List<byte[]> SCAN_HIDDEN_NETWORK_SSID_LIST = List.of(
+ LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_1)),
+ LocalNativeUtil.byteArrayFromArrayList(
+ LocalNativeUtil.decodeSsid(TEST_QUOTED_SSID_2)));
private static final PnoSettings TEST_PNO_SETTINGS = new PnoSettings();
static {