Merge Android R (rvc-dev-plus-aosp-without-vendor@6692709)

Bug: 166295507
Merged-In: I43f896443fd0b36d3538b242bdaa859181eb8eee
Change-Id: Ifb8126ec6c2ae6e79afc1a0cc620dc2f062df96d
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index f28afae..90ab5b8 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -43,6 +43,7 @@
     <application android:label="@string/calendar_storage"
                  android:allowBackup="false"
                  android:icon="@drawable/app_icon"
+                 android:forceQueryable="true"
                  android:usesCleartextTraffic="false">
 
         <provider android:name="CalendarProvider2" android:authorities="com.android.calendar"
diff --git a/TEST_MAPPING b/TEST_MAPPING
new file mode 100644
index 0000000..abe9d6d
--- /dev/null
+++ b/TEST_MAPPING
@@ -0,0 +1,15 @@
+{
+    "presubmit": [
+        {
+            "name": "CalendarProviderTests"
+        },
+        {
+            "name": "CtsProviderTestCases",
+            "options": [
+                {
+                    "include-filter": "android.provider.cts.calendar."
+                }
+            ]
+        }
+    ]
+}
diff --git a/src/com/android/providers/calendar/CalendarAlarmManager.java b/src/com/android/providers/calendar/CalendarAlarmManager.java
index e64cac2..1c39be6 100644
--- a/src/com/android/providers/calendar/CalendarAlarmManager.java
+++ b/src/com/android/providers/calendar/CalendarAlarmManager.java
@@ -249,7 +249,7 @@
      * @param cp2 TODO
      */
     private void scheduleNextAlarmLocked(SQLiteDatabase db, CalendarProvider2 cp2) {
-        CalendarSanityChecker.getInstance(mContext).updateLastCheckTime();
+        cp2.mSanityChecker.updateLastCheckTime();
 
         Time time = new Time();
 
@@ -479,22 +479,27 @@
     }
 
     public void set(int type, long triggerAtTime, PendingIntent operation) {
+        if (mAlarmManager == null) return;
         mAlarmManager.set(type, triggerAtTime, operation);
     }
 
     public void setAndAllowWhileIdle(int type, long triggerAtTime, PendingIntent operation) {
+        if (mAlarmManager == null) return;
         mAlarmManager.setAndAllowWhileIdle(type, triggerAtTime, operation);
     }
 
     public void setExact(int type, long triggerAtTime, PendingIntent operation) {
+        if (mAlarmManager == null) return;
         mAlarmManager.setExact(type, triggerAtTime, operation);
     }
 
     public void setExactAndAllowWhileIdle(int type, long triggerAtTime, PendingIntent operation) {
+        if (mAlarmManager == null) return;
         mAlarmManager.setExactAndAllowWhileIdle(type, triggerAtTime, operation);
     }
 
     public void cancel(PendingIntent operation) {
+        if (mAlarmManager == null) return;
         mAlarmManager.cancel(operation);
     }
 
@@ -503,6 +508,7 @@
      * mAlarmScheduled is specific to that method, currently.
      */
     public void scheduleAlarm(long alarmTime) {
+        if (mAlarmManager == null) return;
         // Debug log for investigating dozing related bugs, remove it once we confirm it is stable.
         if (Build.IS_DEBUGGABLE) {
             Log.d(TAG, "schedule reminder alarm fired at " + alarmTime);
@@ -511,6 +517,7 @@
     }
 
     public void rescheduleMissedAlarms(ContentResolver cr) {
+        if (mAlarmManager == null) return;
         CalendarContract.CalendarAlerts.rescheduleMissedAlarms(cr, mContext, mAlarmManager);
     }
 }
diff --git a/src/com/android/providers/calendar/CalendarProvider2.java b/src/com/android/providers/calendar/CalendarProvider2.java
index 4a6bd22..e439f3a 100644
--- a/src/com/android/providers/calendar/CalendarProvider2.java
+++ b/src/com/android/providers/calendar/CalendarProvider2.java
@@ -189,6 +189,7 @@
      */
     MetaData mMetaData;
     CalendarCache mCalendarCache;
+    CalendarSanityChecker mSanityChecker;
 
     private CalendarDatabaseHelper mDbHelper;
     private CalendarInstancesHelper mInstancesHelper;
@@ -529,6 +530,7 @@
 
         mMetaData = new MetaData(mDbHelper);
         mInstancesHelper = new CalendarInstancesHelper(mDbHelper, mMetaData);
+        mSanityChecker = new CalendarSanityChecker(mContext);
 
         // Register for Intent broadcasts
         IntentFilter filter = new IntentFilter();
@@ -851,7 +853,7 @@
     @Override
     public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
             String sortOrder) {
-        CalendarSanityChecker.getInstance(mContext).checkLastCheckTime();
+        mSanityChecker.checkLastCheckTime();
 
         // Note don't use mCallingUid here. That's only used by mutation functions.
         final int callingUid = Binder.getCallingUid();
@@ -2325,7 +2327,7 @@
         if (Log.isLoggable(TAG, Log.VERBOSE)) {
             Log.v(TAG, "insertInTransaction: " + uri);
         }
-        CalendarSanityChecker.getInstance(mContext).checkLastCheckTime();
+        mSanityChecker.checkLastCheckTime();
 
         validateUriParameters(uri.getQueryParameterNames());
         final int match = sUriMatcher.match(uri);
@@ -3315,7 +3317,7 @@
         if (Log.isLoggable(TAG, Log.VERBOSE)) {
             Log.v(TAG, "deleteInTransaction: " + uri);
         }
-        CalendarSanityChecker.getInstance(mContext).checkLastCheckTime();
+        mSanityChecker.checkLastCheckTime();
 
         validateUriParameters(uri.getQueryParameterNames());
         final int match = sUriMatcher.match(uri);
@@ -4194,7 +4196,7 @@
         if (Log.isLoggable(TAG, Log.VERBOSE)) {
             Log.v(TAG, "updateInTransaction: " + uri);
         }
-        CalendarSanityChecker.getInstance(mContext).checkLastCheckTime();
+        mSanityChecker.checkLastCheckTime();
 
         validateUriParameters(uri.getQueryParameterNames());
         final int match = sUriMatcher.match(uri);
diff --git a/src/com/android/providers/calendar/CalendarSanityChecker.java b/src/com/android/providers/calendar/CalendarSanityChecker.java
index 19cb5b1..ce7b62a 100644
--- a/src/com/android/providers/calendar/CalendarSanityChecker.java
+++ b/src/com/android/providers/calendar/CalendarSanityChecker.java
@@ -16,14 +16,10 @@
 
 package com.android.providers.calendar;
 
-import android.annotation.Nullable;
-import android.content.ContentProvider;
 import android.content.Context;
-import android.content.IContentProvider;
 import android.content.SharedPreferences;
 import android.os.SystemClock;
 import android.os.UserManager;
-import android.provider.CalendarContract;
 import android.provider.Settings;
 import android.provider.Settings.Global;
 import android.text.format.DateUtils;
@@ -64,7 +60,6 @@
     private static final String LAST_CHECK_BOOT_COUNT_PREF_KEY = "last_check_boot_count";
     private static final String LAST_WTF_REALTIME_PREF_KEY = "last_wtf_realtime";
 
-    private static CalendarSanityChecker sInstance;
     private final Context mContext;
 
     private final Object mLock = new Object();
@@ -73,7 +68,7 @@
     @VisibleForTesting
     final SharedPreferences mPrefs;
 
-    protected CalendarSanityChecker(Context context) {
+    public CalendarSanityChecker(Context context) {
         mContext = context;
         mPrefs = mContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
     }
@@ -90,7 +85,7 @@
 
     @VisibleForTesting
     protected long getUserUnlockTime() {
-        final UserManager um = mContext.getSystemService(UserManager.class);
+        final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
         final long startTime = um.getUserStartRealtime();
         final long unlockTime = um.getUserUnlockRealtime();
         if (DEBUG) {
@@ -99,13 +94,6 @@
         return unlockTime;
     }
 
-    public static synchronized CalendarSanityChecker getInstance(Context context) {
-        if (sInstance == null) {
-            sInstance = new CalendarSanityChecker(context);
-        }
-        return sInstance;
-    }
-
     /**
      * Called by {@link CalendarAlarmManager#scheduleNextAlarmLocked}
      */
diff --git a/tests/Android.bp b/tests/Android.bp
index 1528d4a..4f57e37 100644
--- a/tests/Android.bp
+++ b/tests/Android.bp
@@ -5,6 +5,7 @@
     platform_apis: true,
     test_suites: ["device-tests"],
     static_libs: [
+        "androidx.test.rules",
         "calendar-common",
         "junit",
     ],
diff --git a/tests/AndroidManifest.xml b/tests/AndroidManifest.xml
index 0ce5105..6aa45d4 100644
--- a/tests/AndroidManifest.xml
+++ b/tests/AndroidManifest.xml
@@ -25,18 +25,8 @@
     <uses-permission android:name="android.permission.READ_CALENDAR" />
     <uses-permission android:name="android.permission.WRITE_CALENDAR" />
 
-    <!--
-    The test declared in this instrumentation will be run along with tests declared by
-    all other applications via the command: "adb shell itr".
-    The "itr" command will find all tests declared by all applications. If you want to run just these
-    tests on their own then use the command:
-    "adb shell am instrument -w com.android.providers.calendar.tests/android.test.InstrumentationTestRunner"
-
-    To test db upgrade:
-    adb shell am instrument -w -e class com.android.providers.calendar.CalendarDatabaseHelperTest#testSchemasEqualForAllTables com.android.providers.calendar.tests/android.test.InstrumentationTestRunner
-    -->
-    <instrumentation android:name="android.test.InstrumentationTestRunner"
+    <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner"
                      android:targetPackage="com.android.providers.calendar"
-                     android:label="calendar provider tests"/>
+                     android:label="CalendarProvider tests"/>
 
 </manifest>
diff --git a/tests/AndroidTest.xml b/tests/AndroidTest.xml
index 0b63420..e7d5d1a 100644
--- a/tests/AndroidTest.xml
+++ b/tests/AndroidTest.xml
@@ -20,9 +20,9 @@
 
     <option name="test-suite-tag" value="apct" />
     <option name="test-tag" value="CalendarProviderTests" />
-    <test class="com.android.tradefed.testtype.InstrumentationTest" >
+    <test class="com.android.tradefed.testtype.AndroidJUnitTest" >
         <option name="package" value="com.android.providers.calendar.tests" />
-        <option name="runner" value="android.test.InstrumentationTestRunner" />
+        <option name="runner" value="androidx.test.runner.AndroidJUnitRunner" />
         <option name="hidden-api-checks" value="false"/>
     </test>
 </configuration>
diff --git a/tests/src/com/android/providers/calendar/CalendarDatabaseHelperTest.java b/tests/src/com/android/providers/calendar/CalendarDatabaseHelperTest.java
index 79c84e8..a2925d4 100644
--- a/tests/src/com/android/providers/calendar/CalendarDatabaseHelperTest.java
+++ b/tests/src/com/android/providers/calendar/CalendarDatabaseHelperTest.java
@@ -13,24 +13,34 @@
  * See the License for the specific language governing permissions and
  * limitations under the License
  */
+
 package com.android.providers.calendar;
 
-
-import com.android.common.content.SyncStateContentProviderHelper;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 
 import android.database.Cursor;
 import android.database.DatabaseUtils;
 import android.database.sqlite.SQLiteDatabase;
 import android.test.mock.MockContext;
-import android.test.suitebuilder.annotation.MediumTest;
 import android.text.TextUtils;
 import android.util.Log;
 
+import androidx.test.runner.AndroidJUnit4;
+
+import com.android.common.content.SyncStateContentProviderHelper;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
 import java.util.Arrays;
 
-import junit.framework.TestCase;
-
-public class CalendarDatabaseHelperTest extends TestCase {
+@RunWith(AndroidJUnit4.class)
+public class CalendarDatabaseHelperTest {
     private static final String TAG = "CDbHelperTest";
 
     private SQLiteDatabase mBadDb;
@@ -38,7 +48,7 @@
     private DatabaseUtils.InsertHelper mBadEventsInserter;
     private DatabaseUtils.InsertHelper mGoodEventsInserter;
 
-    @Override
+    @Before
     public void setUp() {
         mBadDb = SQLiteDatabase.create(null);
         assertNotNull(mBadDb);
@@ -386,7 +396,7 @@
         assertEquals(mGoodDb.rawQuery("SELECT _id FROM Events;", null).getCount(), 2);
     }
 
-    @MediumTest
+    @Test
     public void testUpgradeToVersion69() {
         // Create event tables
         createVersion67EventsTable(mBadDb);
@@ -416,7 +426,8 @@
         }
     }
 
-    @MediumTest
+    @Test
+    @Ignore("b/140236227")
     public void testUpgradeToCurrentVersion() {
         // Create event tables
         bootstrapDbVersion50(mBadDb);
@@ -452,6 +463,8 @@
 
     private static final String[] PROJECTION = {"tbl_name", "sql"};
 
+    @Test
+    @Ignore("b/140236227")
     public void testSchemasEqualForAllTables() {
 
         CalendarDatabaseHelper cDbHelper = new CalendarDatabaseHelper(new MockContext());
diff --git a/tests/src/com/android/providers/calendar/CalendarProvider2Test.java b/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
index e0a4edf..466497c 100644
--- a/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
+++ b/tests/src/com/android/providers/calendar/CalendarProvider2Test.java
@@ -23,6 +23,7 @@
 import android.content.ContentValues;
 import android.content.Context;
 import android.content.Intent;
+import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
 import android.content.pm.ProviderInfo;
 import android.content.res.Resources;
@@ -988,15 +989,22 @@
         RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
                 new MockContext2(), // The context that most methods are delegated to
                 getContext(), // The context that file methods are delegated to
-                filenamePrefix);
+                filenamePrefix) {
+            @Override
+            public SharedPreferences getSharedPreferences(String name, int mode) {
+                return getContext().getSharedPreferences(name, mode);
+            }
+        };
         mContext = new IsolatedContext(mResolver, targetContextWrapper) {
             @Override
             public Object getSystemService(String name) {
-                // for accessing wakelock.
-                if (Context.POWER_SERVICE.equals(name)) {
-                    return getContext().getSystemService(name);
+                switch (name) {
+                    case Context.POWER_SERVICE:
+                    case Context.USER_SERVICE:
+                        return getContext().getSystemService(name);
+                    default:
+                        return super.getSystemService(name);
                 }
-                return super.getSystemService(name);
             }
         };
 
@@ -1005,6 +1013,17 @@
             public int getUserId() {
                 return WORK_PROFILE_USER_ID;
             }
+
+            @Override
+            public Object getSystemService(String name) {
+                switch (name) {
+                    case Context.POWER_SERVICE:
+                    case Context.USER_SERVICE:
+                        return getContext().getSystemService(name);
+                    default:
+                        return super.getSystemService(name);
+                }
+            }
         };
 
         mProvider = new CalendarProvider2ForTesting() {
diff --git a/tests/src/com/android/providers/calendar/CalendarSanityCheckerTest.java b/tests/src/com/android/providers/calendar/CalendarSanityCheckerTest.java
index 1586c61..4cd00c8 100644
--- a/tests/src/com/android/providers/calendar/CalendarSanityCheckerTest.java
+++ b/tests/src/com/android/providers/calendar/CalendarSanityCheckerTest.java
@@ -15,11 +15,23 @@
  */
 package com.android.providers.calendar;
 
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
 import android.content.Context;
-import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
 import android.text.format.DateUtils;
 
-public class CalendarSanityCheckerTest extends AndroidTestCase {
+import androidx.test.InstrumentationRegistry;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class CalendarSanityCheckerTest {
     private class CalendarSanityCheckerTestable extends CalendarSanityChecker {
         protected CalendarSanityCheckerTestable(Context context) {
             super(context);
@@ -41,73 +53,79 @@
         }
     }
 
+    private Context mContext;
+    private CalendarSanityCheckerTestable mSanityChecker;
+
     private long mInjectedRealtimeMillis = 1000000L;
     private long mInjectedBootCount = 1000;
     private long mInjectedUnlockTime = 0;
 
-    public void testWithoutLastCheckTime() {
-        CalendarSanityCheckerTestable target = new CalendarSanityCheckerTestable(getContext());
-        target.mPrefs.edit().clear().commit();
+    @Before
+    public void setUp() {
+        mContext = InstrumentationRegistry.getContext();
+        mSanityChecker = new CalendarSanityCheckerTestable(mContext);
+        mSanityChecker.mPrefs.edit().clear().commit();
+    }
 
-        assertTrue(target.checkLastCheckTime());
+    @Test
+    public void testWithoutLastCheckTime() {
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         // Unlock.
         mInjectedUnlockTime = mInjectedRealtimeMillis;
 
         mInjectedRealtimeMillis += 15 * 60 * 1000;
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedRealtimeMillis += 1;
-        assertFalse(target.checkLastCheckTime());
+        assertFalse(mSanityChecker.checkLastCheckTime());
     }
 
+    @Test
     public void testWithLastCheckTime() {
-        CalendarSanityCheckerTestable target = new CalendarSanityCheckerTestable(getContext());
-        target.mPrefs.edit().clear().commit();
-
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedUnlockTime = mInjectedRealtimeMillis;
 
         // Update the last check time.
         mInjectedRealtimeMillis += 1 * 60 * 1000;
-        target.updateLastCheckTime();
+        mSanityChecker.updateLastCheckTime();
 
         // Right after, okay.
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         // Still okay.
         mInjectedRealtimeMillis += DateUtils.DAY_IN_MILLIS - (15 * DateUtils.MINUTE_IN_MILLIS);
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedRealtimeMillis += 1;
-        assertFalse(target.checkLastCheckTime());
+        assertFalse(mSanityChecker.checkLastCheckTime());
 
         // Repeat the same thing.
         mInjectedRealtimeMillis += 1 * 60 * 1000;
-        target.updateLastCheckTime();
+        mSanityChecker.updateLastCheckTime();
 
         // Right after, okay.
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         // Still okay.
         mInjectedRealtimeMillis += DateUtils.DAY_IN_MILLIS - (15 * DateUtils.MINUTE_IN_MILLIS);
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedRealtimeMillis += 1;
-        assertFalse(target.checkLastCheckTime());
+        assertFalse(mSanityChecker.checkLastCheckTime());
 
         // Check again right after. This should pass because of WTF_INTERVAL_MS.
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedRealtimeMillis += 60 * 60 * 1000;
 
         // Still okay.
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         // Now WTF again.
         mInjectedRealtimeMillis += 1;
-        assertFalse(target.checkLastCheckTime());
+        assertFalse(mSanityChecker.checkLastCheckTime());
 
         // Reboot.
         mInjectedRealtimeMillis = 1000000L;
@@ -117,12 +135,12 @@
         mInjectedUnlockTime = mInjectedRealtimeMillis;
 
         mInjectedRealtimeMillis += 15 * 60 * 1000;
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
 
         mInjectedRealtimeMillis += 1;
-        assertFalse(target.checkLastCheckTime());
+        assertFalse(mSanityChecker.checkLastCheckTime());
 
         // Check again right after. This should pass because of WTF_INTERVAL_MS.
-        assertTrue(target.checkLastCheckTime());
+        assertTrue(mSanityChecker.checkLastCheckTime());
     }
 }