Merge "Reduce extraneous loading of task snapshots/icons" into ub-launcher3-master
diff --git a/Android.mk b/Android.mk
index cddd53d..b8e6c85 100644
--- a/Android.mk
+++ b/Android.mk
@@ -28,6 +28,35 @@
 LOCAL_SDK_VERSION := current
 include $(BUILD_PREBUILT)
 
+include $(CLEAR_VARS)
+LOCAL_MODULE := libPluginCore
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE_CLASS := JAVA_LIBRARIES
+LOCAL_SRC_FILES := libs/plugin_core.jar
+LOCAL_UNINSTALLABLE_MODULE := true
+LOCAL_SDK_VERSION := current
+include $(BUILD_PREBUILT)
+
+#
+# Build rule for plugin lib (needed to write a plugin).
+#
+include $(CLEAR_VARS)
+LOCAL_USE_AAPT2 := true
+LOCAL_AAPT2_ONLY := true
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_STATIC_JAVA_LIBRARIES := libPluginCore
+
+LOCAL_SRC_FILES := \
+    $(call all-java-files-under, src_plugins)
+
+LOCAL_SDK_VERSION := current
+LOCAL_MIN_SDK_VERSION := 28
+LOCAL_MODULE := LauncherPluginLib
+LOCAL_PRIVILEGED_MODULE := true
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
 #
 # Build rule for Launcher3 dependencies lib.
 #
@@ -40,6 +69,8 @@
     androidx.recyclerview_recyclerview \
     androidx.dynamicanimation_dynamicanimation
 
+LOCAL_STATIC_JAVA_LIBRARIES := libPluginCore
+
 LOCAL_SRC_FILES := \
     $(call all-proto-files-under, protos) \
     $(call all-proto-files-under, proto_overrides)
@@ -74,6 +105,8 @@
     $(call all-java-files-under, src_flags)
 
 LOCAL_PROGUARD_FLAG_FILES := proguard.flags
+# Proguard is disable for testing. Derivarive prjects to keep proguard enabled
+LOCAL_PROGUARD_ENABLED := disabled
 
 LOCAL_SDK_VERSION := current
 LOCAL_MIN_SDK_VERSION := 21
diff --git a/libs/plugin_core.jar b/libs/plugin_core.jar
new file mode 100644
index 0000000..dd27f86
--- /dev/null
+++ b/libs/plugin_core.jar
Binary files differ
diff --git a/quickstep/libs/sysui_shared.jar b/quickstep/libs/sysui_shared.jar
index 7ff664d..c5a7c05 100644
--- a/quickstep/libs/sysui_shared.jar
+++ b/quickstep/libs/sysui_shared.jar
Binary files differ
diff --git a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginEnablerImpl.java b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginEnablerImpl.java
new file mode 100644
index 0000000..e9fac26
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginEnablerImpl.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.launcher3.uioverrides.plugins;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.SharedPreferences;
+
+import com.android.launcher3.Utilities;
+import com.android.systemui.shared.plugins.PluginEnabler;
+
+public class PluginEnablerImpl implements PluginEnabler {
+
+    final private SharedPreferences mSharedPrefs;
+
+    public PluginEnablerImpl(Context context) {
+        mSharedPrefs = Utilities.getDevicePrefs(context);
+    }
+
+    @Override
+    public void setEnabled(ComponentName component, boolean enabled) {
+        mSharedPrefs.edit().putBoolean(toPrefString(component), enabled).apply();
+    }
+
+    @Override
+    public boolean isEnabled(ComponentName component) {
+        return mSharedPrefs.getBoolean(toPrefString(component), true);
+    }
+
+    private String toPrefString(ComponentName component) {
+        return "PLUGIN_ENABLED_" + component.flattenToString();
+    }
+}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginInitializerImpl.java b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginInitializerImpl.java
new file mode 100644
index 0000000..8a6aa05
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginInitializerImpl.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.launcher3.uioverrides.plugins;
+
+import android.content.Context;
+import android.os.Looper;
+
+import com.android.launcher3.LauncherModel;
+import com.android.systemui.shared.plugins.PluginEnabler;
+import com.android.systemui.shared.plugins.PluginInitializer;
+
+public class PluginInitializerImpl implements PluginInitializer {
+    @Override
+    public Looper getBgLooper() {
+        return LauncherModel.getWorkerLooper();
+    }
+
+    @Override
+    public void onPluginManagerInit() {
+    }
+
+    @Override
+    public String[] getWhitelistedPlugins(Context context) {
+        return new String[0];
+    }
+
+    @Override
+    public PluginEnabler getPluginEnabler(Context context) {
+        return new PluginEnablerImpl(context);
+    }
+
+    @Override
+    public void handleWtfs() {
+    }
+}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
new file mode 100644
index 0000000..ca12951
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.launcher3.uioverrides.plugins;
+
+import android.content.Context;
+
+import com.android.launcher3.util.MainThreadInitializedObject;
+import com.android.systemui.plugins.Plugin;
+import com.android.systemui.plugins.PluginListener;
+import com.android.systemui.shared.plugins.PluginEnabler;
+import com.android.systemui.shared.plugins.PluginInitializer;
+import com.android.systemui.shared.plugins.PluginManager;
+import com.android.systemui.shared.plugins.PluginManagerImpl;
+
+public class PluginManagerWrapper {
+
+    public static final MainThreadInitializedObject<PluginManagerWrapper> INSTANCE =
+            new MainThreadInitializedObject<>(PluginManagerWrapper::new);
+
+    private final PluginManager mPluginManager;
+    private final PluginEnabler mPluginEnabler;
+
+    private PluginManagerWrapper(Context c) {
+        PluginInitializer pluginInitializer  = new PluginInitializerImpl();
+        mPluginManager = new PluginManagerImpl(c, pluginInitializer);
+        mPluginEnabler = pluginInitializer.getPluginEnabler(c);
+    }
+
+    PluginEnabler getPluginEnabler() {
+        return mPluginEnabler;
+    }
+
+    public void addPluginListener(PluginListener<? extends Plugin> listener, Class<?> pluginClass) {
+        mPluginManager.addPluginListener(listener, pluginClass);
+    }
+
+    public void removePluginListener(PluginListener<? extends Plugin> listener) {
+        mPluginManager.removePluginListener(listener);
+    }
+}
diff --git a/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginPreferencesFragment.java b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginPreferencesFragment.java
new file mode 100644
index 0000000..3da4f84
--- /dev/null
+++ b/quickstep/src/com/android/launcher3/uioverrides/plugins/PluginPreferencesFragment.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.launcher3.uioverrides.plugins;
+
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.net.Uri;
+import android.os.Bundle;
+import android.preference.PreferenceFragment;
+import android.preference.PreferenceScreen;
+import android.preference.SwitchPreference;
+import android.provider.Settings;
+import android.util.ArrayMap;
+import android.util.ArraySet;
+import android.view.View;
+
+import com.android.launcher3.R;
+import com.android.systemui.shared.plugins.PluginEnabler;
+import com.android.systemui.shared.plugins.PluginManager;
+import com.android.systemui.shared.plugins.PluginPrefs;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class is copied from System UI Tuner, except using our PluginEnablerImpl. The reason we
+ * can't share a common base class in the shared lib is because the androidx preference dependency
+ * interferes with our recyclerview and fragment dependencies.
+ */
+public class PluginPreferencesFragment extends PreferenceFragment {
+    public static final String ACTION_PLUGIN_SETTINGS
+            = "com.android.systemui.action.PLUGIN_SETTINGS";
+
+    private static final String PLUGIN_PERMISSION = "com.android.systemui.permission.PLUGIN";
+
+    private PluginPrefs mPluginPrefs;
+    private PluginEnabler mPluginEnabler;
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
+        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
+        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+        filter.addDataScheme("package");
+        getContext().registerReceiver(mReceiver, filter);
+        filter = new IntentFilter(Intent.ACTION_USER_UNLOCKED);
+        getContext().registerReceiver(mReceiver, filter);
+
+        mPluginEnabler = PluginManagerWrapper.INSTANCE.get(getContext()).getPluginEnabler();
+        loadPrefs();
+    }
+
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        getContext().unregisterReceiver(mReceiver);
+    }
+
+    private void loadPrefs() {
+        PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getContext());
+        screen.setOrderingAsAdded(false);
+        Context prefContext = getContext();
+        mPluginPrefs = new PluginPrefs(getContext());
+        PackageManager pm = getContext().getPackageManager();
+
+        Set<String> pluginActions = mPluginPrefs.getPluginList();
+        ArrayMap<String, ArraySet<String>> plugins = new ArrayMap<>();
+        for (String action : pluginActions) {
+            String name = toName(action);
+            List<ResolveInfo> result = pm.queryIntentServices(
+                    new Intent(action), PackageManager.MATCH_DISABLED_COMPONENTS);
+            for (ResolveInfo info : result) {
+                String packageName = info.serviceInfo.packageName;
+                if (!plugins.containsKey(packageName)) {
+                    plugins.put(packageName, new ArraySet<>());
+                }
+                plugins.get(packageName).add(name);
+            }
+        }
+
+        List<PackageInfo> apps = pm.getPackagesHoldingPermissions(new String[]{PLUGIN_PERMISSION},
+                PackageManager.MATCH_DISABLED_COMPONENTS | PackageManager.GET_SERVICES);
+        apps.forEach(app -> {
+            if (!plugins.containsKey(app.packageName)) return;
+            SwitchPreference pref = new PluginPreference(prefContext, app, mPluginEnabler);
+            pref.setSummary("Plugins: " + toString(plugins.get(app.packageName)));
+            screen.addPreference(pref);
+        });
+        setPreferenceScreen(screen);
+    }
+
+    private String toString(ArraySet<String> plugins) {
+        StringBuilder b = new StringBuilder();
+        for (String string : plugins) {
+            if (b.length() != 0) {
+                b.append(", ");
+            }
+            b.append(string);
+        }
+        return b.toString();
+    }
+
+    private String toName(String action) {
+        String str = action.replace("com.android.systemui.action.PLUGIN_", "");
+        StringBuilder b = new StringBuilder();
+        for (String s : str.split("_")) {
+            if (b.length() != 0) {
+                b.append(' ');
+            }
+            b.append(s.substring(0, 1));
+            b.append(s.substring(1).toLowerCase());
+        }
+        return b.toString();
+    }
+
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            loadPrefs();
+        }
+    };
+
+    private static class PluginPreference extends SwitchPreference {
+        private final boolean mHasSettings;
+        private final PackageInfo mInfo;
+        private final PluginEnabler mPluginEnabler;
+
+        public PluginPreference(Context prefContext, PackageInfo info, PluginEnabler pluginEnabler) {
+            super(prefContext);
+            PackageManager pm = prefContext.getPackageManager();
+            mHasSettings = pm.resolveActivity(new Intent(ACTION_PLUGIN_SETTINGS)
+                    .setPackage(info.packageName), 0) != null;
+            mInfo = info;
+            mPluginEnabler = pluginEnabler;
+            setTitle(info.applicationInfo.loadLabel(pm));
+            setChecked(isPluginEnabled());
+            setWidgetLayoutResource(R.layout.switch_preference_with_settings);
+        }
+
+        private boolean isPluginEnabled() {
+            for (int i = 0; i < mInfo.services.length; i++) {
+                ComponentName componentName = new ComponentName(mInfo.packageName,
+                        mInfo.services[i].name);
+                if (!mPluginEnabler.isEnabled(componentName)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        @Override
+        protected boolean persistBoolean(boolean isEnabled) {
+            boolean shouldSendBroadcast = false;
+            for (int i = 0; i < mInfo.services.length; i++) {
+                ComponentName componentName = new ComponentName(mInfo.packageName,
+                        mInfo.services[i].name);
+
+                if (mPluginEnabler.isEnabled(componentName) != isEnabled) {
+                    mPluginEnabler.setEnabled(componentName, isEnabled);
+                    shouldSendBroadcast = true;
+                }
+            }
+            if (shouldSendBroadcast) {
+                final String pkg = mInfo.packageName;
+                final Intent intent = new Intent(PluginManager.PLUGIN_CHANGED,
+                        pkg != null ? Uri.fromParts("package", pkg, null) : null);
+                getContext().sendBroadcast(intent);
+            }
+            setChecked(isEnabled);
+            return true;
+        }
+
+        @Override
+        protected void onBindView(View view) {
+            super.onBindView(view);
+            view.findViewById(R.id.settings).setVisibility(mHasSettings ? View.VISIBLE
+                    : View.GONE);
+            view.findViewById(R.id.divider).setVisibility(mHasSettings ? View.VISIBLE
+                    : View.GONE);
+            view.findViewById(R.id.settings).setOnClickListener(v -> {
+                ResolveInfo result = v.getContext().getPackageManager().resolveActivity(
+                        new Intent(ACTION_PLUGIN_SETTINGS).setPackage(
+                                mInfo.packageName), 0);
+                if (result != null) {
+                    v.getContext().startActivity(new Intent().setComponent(
+                            new ComponentName(result.activityInfo.packageName,
+                                    result.activityInfo.name)));
+                }
+            });
+            view.setOnLongClickListener(v -> {
+                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
+                intent.setData(Uri.fromParts("package", mInfo.packageName, null));
+                getContext().startActivity(intent);
+                return true;
+            });
+        }
+    }
+}
diff --git a/quickstep/src/com/android/quickstep/NormalizedIconLoader.java b/quickstep/src/com/android/quickstep/NormalizedIconLoader.java
index 6557761..bd6204a 100644
--- a/quickstep/src/com/android/quickstep/NormalizedIconLoader.java
+++ b/quickstep/src/com/android/quickstep/NormalizedIconLoader.java
@@ -43,7 +43,6 @@
     private final SparseArray<BitmapInfo> mDefaultIcons = new SparseArray<>();
     private final DrawableFactory mDrawableFactory;
     private final boolean mDisableColorExtraction;
-    private LauncherIcons mLauncherIcons;
 
     public NormalizedIconLoader(Context context, TaskKeyLruCache<Drawable> iconCache,
             LruCache<ComponentName, ActivityInfo> activityInfoCache,
@@ -73,19 +72,18 @@
                 false));
     }
 
-    private synchronized BitmapInfo getBitmapInfo(Drawable drawable, int userId,
+    private BitmapInfo getBitmapInfo(Drawable drawable, int userId,
             int primaryColor, boolean isInstantApp) {
-        if (mLauncherIcons == null) {
-            mLauncherIcons = LauncherIcons.obtain(mContext);
+        try (LauncherIcons la = LauncherIcons.obtain(mContext)) {
             if (mDisableColorExtraction) {
-                mLauncherIcons.disableColorExtraction();
+                la.disableColorExtraction();
             }
-        }
+            la.setWrapperBackgroundColor(primaryColor);
 
-        mLauncherIcons.setWrapperBackgroundColor(primaryColor);
-        // User version code O, so that the icon is always wrapped in an adaptive icon container.
-        return mLauncherIcons.createBadgedIconBitmap(drawable, UserHandle.of(userId),
-                Build.VERSION_CODES.O, isInstantApp);
+            // User version code O, so that the icon is always wrapped in an adaptive icon container
+            return la.createBadgedIconBitmap(drawable, UserHandle.of(userId),
+                    Build.VERSION_CODES.O, isInstantApp);
+        }
     }
 
     @Override
diff --git a/quickstep/tests/src/com/android/quickstep/FallbackRecentsTest.java b/quickstep/tests/src/com/android/quickstep/FallbackRecentsTest.java
new file mode 100644
index 0000000..88b50d9
--- /dev/null
+++ b/quickstep/tests/src/com/android/quickstep/FallbackRecentsTest.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.android.quickstep;
+
+import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
+
+import static com.android.launcher3.tapl.LauncherInstrumentation.WAIT_TIME_MS;
+import static com.android.launcher3.tapl.TestHelpers.getHomeIntentInPackage;
+import static com.android.launcher3.tapl.TestHelpers.getLauncherInMyProcess;
+import static com.android.launcher3.util.rule.ShellCommandRule.disableHeadsUpNotification;
+import static com.android.launcher3.util.rule.ShellCommandRule.getLauncherCommand;
+import static com.android.quickstep.QuickStepOnOffRule.Mode.OFF;
+
+import static org.junit.Assert.assertTrue;
+
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
+import android.app.Instrumentation;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+
+import com.android.launcher3.MainThreadExecutor;
+import com.android.launcher3.tapl.LauncherInstrumentation;
+import com.android.launcher3.testcomponent.TestCommandReceiver;
+import com.android.quickstep.QuickStepOnOffRule.QuickstepOnOff;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestRule;
+import org.junit.runner.RunWith;
+import org.junit.runners.model.Statement;
+
+import androidx.test.filters.LargeTest;
+import androidx.test.runner.AndroidJUnit4;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.Until;
+
+@LargeTest
+@RunWith(AndroidJUnit4.class)
+/**
+ * TODO: Fix fallback when quickstep is enabled
+ */
+public class FallbackRecentsTest {
+
+    private final UiDevice mDevice;
+    private final LauncherInstrumentation mLauncher;
+    private final ActivityInfo mOtherLauncherActivity;
+
+    @Rule public final TestRule mDisableHeadsUpNotification = disableHeadsUpNotification();
+    @Rule public final TestRule mQuickstepOnOffExecutor;
+
+    @Rule public final TestRule mSetLauncherCommand;
+
+    public FallbackRecentsTest() {
+        Instrumentation instrumentation = getInstrumentation();
+        Context context = instrumentation.getContext();
+        mDevice = UiDevice.getInstance(instrumentation);
+        mLauncher = new LauncherInstrumentation(instrumentation);
+
+        mQuickstepOnOffExecutor = new QuickStepOnOffRule(new MainThreadExecutor(), mLauncher);
+        mOtherLauncherActivity = context.getPackageManager().queryIntentActivities(
+                getHomeIntentInPackage(context),
+                MATCH_DISABLED_COMPONENTS).get(0).activityInfo;
+
+        mSetLauncherCommand = (base, desc) -> new Statement() {
+            @Override
+            public void evaluate() throws Throwable {
+                TestCommandReceiver.callCommand(TestCommandReceiver.ENABLE_TEST_LAUNCHER);
+                UiDevice.getInstance(getInstrumentation()).executeShellCommand(
+                        getLauncherCommand(mOtherLauncherActivity));
+                try {
+                    base.evaluate();
+                } finally {
+                    TestCommandReceiver.callCommand(TestCommandReceiver.DISABLE_TEST_LAUNCHER);
+                    UiDevice.getInstance(getInstrumentation()).executeShellCommand(
+                            getLauncherCommand(getLauncherInMyProcess()));
+                }
+            }
+        };
+    }
+
+    @QuickstepOnOff(mode = OFF)
+    @Test
+    public void goToOverviewFromHome() {
+        mDevice.pressHome();
+        assertTrue("Fallback Launcher not visible", mDevice.wait(Until.hasObject(By.pkg(
+                mOtherLauncherActivity.packageName)), WAIT_TIME_MS));
+
+        mLauncher.getBackground().switchToOverview();
+    }
+
+    @QuickstepOnOff(mode = OFF)
+    @Test
+    public void goToOverviewFromApp() {
+        startAppFast("com.android.settings");
+
+        mLauncher.getBackground().switchToOverview();
+    }
+
+    private void startAppFast(String packageName) {
+        final Instrumentation instrumentation = getInstrumentation();
+        final Intent intent = instrumentation.getContext().getPackageManager().
+                getLaunchIntentForPackage(packageName);
+        intent.addCategory(Intent.CATEGORY_LAUNCHER);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        instrumentation.getTargetContext().startActivity(intent);
+        assertTrue(packageName + " didn't start",
+                mDevice.wait(Until.hasObject(By.pkg(packageName).depth(0)), WAIT_TIME_MS));
+    }
+
+}
diff --git a/quickstep/tests/src/com/android/quickstep/QuickStepOnOffRule.java b/quickstep/tests/src/com/android/quickstep/QuickStepOnOffRule.java
index 6a149b7..b801b4f 100644
--- a/quickstep/tests/src/com/android/quickstep/QuickStepOnOffRule.java
+++ b/quickstep/tests/src/com/android/quickstep/QuickStepOnOffRule.java
@@ -16,10 +16,14 @@
 
 package com.android.quickstep;
 
+import static com.android.quickstep.QuickStepOnOffRule.Mode.BOTH;
+import static com.android.quickstep.QuickStepOnOffRule.Mode.OFF;
+import static com.android.quickstep.QuickStepOnOffRule.Mode.ON;
+
 import androidx.test.InstrumentationRegistry;
 
 import com.android.launcher3.tapl.LauncherInstrumentation;
-import com.android.launcher3.ui.TestHelpers;
+import com.android.launcher3.tapl.TestHelpers;
 
 import org.junit.rules.TestRule;
 import org.junit.runner.Description;
@@ -36,10 +40,16 @@
  * The test should be annotated with @QuickstepOnOff.
  */
 public class QuickStepOnOffRule implements TestRule {
+
+    public enum Mode {
+        ON, OFF, BOTH
+    }
+
     // Annotation for tests that need to be run with quickstep enabled and disabled.
     @Retention(RetentionPolicy.RUNTIME)
     @Target(ElementType.METHOD)
     public @interface QuickstepOnOff {
+        Mode mode() default BOTH;
     }
 
     private final Executor mMainThreadExecutor;
@@ -54,12 +64,17 @@
     public Statement apply(Statement base, Description description) {
         if (TestHelpers.isInLauncherProcess() &&
                 description.getAnnotation(QuickstepOnOff.class) != null) {
+            Mode mode = description.getAnnotation(QuickstepOnOff.class).mode();
             return new Statement() {
                 @Override
                 public void evaluate() throws Throwable {
                     try {
-                        evaluateWithQuickstepOn();
-                        evaluateWithQuickstepOff();
+                        if (mode == ON || mode == BOTH) {
+                            evaluateWithQuickstepOn();
+                        }
+                        if (mode == OFF || mode == BOTH) {
+                            evaluateWithQuickstepOff();
+                        }
                     } finally {
                         overrideSwipeUpEnabled(null);
                     }
diff --git a/res/layout/switch_preference_with_settings.xml b/res/layout/switch_preference_with_settings.xml
new file mode 100644
index 0000000..d319561
--- /dev/null
+++ b/res/layout/switch_preference_with_settings.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:orientation="horizontal"
+    android:gravity="center_vertical">
+
+    <ImageView
+        android:id="@+id/settings"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:src="@drawable/ic_setting"
+        android:tint="@android:color/black"
+        android:padding="12dp"
+        android:background="?android:attr/selectableItemBackgroundBorderless" />
+
+    <View
+        android:id="@+id/divider"
+        android:layout_width="1dp"
+        android:layout_height="30dp"
+        android:layout_marginEnd="8dp"
+        android:background="?android:attr/listDivider" />
+
+    <!-- Note: seems we need focusable="false" and clickable="false" when moving to androidx -->
+    <Switch
+        android:id="@android:id/switch_widget"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:background="@null" />
+</LinearLayout>
\ No newline at end of file
diff --git a/src/com/android/launcher3/AutoInstallsLayout.java b/src/com/android/launcher3/AutoInstallsLayout.java
index 4c34071..c7c1d6a 100644
--- a/src/com/android/launcher3/AutoInstallsLayout.java
+++ b/src/com/android/launcher3/AutoInstallsLayout.java
@@ -40,6 +40,7 @@
 import com.android.launcher3.LauncherProvider.SqlArguments;
 import com.android.launcher3.LauncherSettings.Favorites;
 import com.android.launcher3.icons.LauncherIcons;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.Thunk;
 
 import org.xmlpull.v1.XmlPullParser;
@@ -163,7 +164,7 @@
     private final int mRowCount;
     private final int mColumnCount;
 
-    private final long[] mTemp = new long[2];
+    private final int[] mTemp = new int[2];
     @Thunk final ContentValues mValues;
     protected final String mRootTag;
 
@@ -191,7 +192,7 @@
     /**
      * Loads the layout in the db and returns the number of entries added on the desktop.
      */
-    public int loadLayout(SQLiteDatabase db, ArrayList<Long> screenIds) {
+    public int loadLayout(SQLiteDatabase db, IntArray screenIds) {
         mDb = db;
         try {
             return parseLayout(mLayoutId, screenIds);
@@ -204,7 +205,7 @@
     /**
      * Parses the layout and returns the number of elements added on the homescreen.
      */
-    protected int parseLayout(int layoutId, ArrayList<Long> screenIds)
+    protected int parseLayout(int layoutId, IntArray screenIds)
             throws XmlPullParserException, IOException {
         XmlResourceParser parser = mSourceRes.getXml(layoutId);
         beginDocument(parser, mRootTag);
@@ -227,14 +228,14 @@
      * Parses container and screenId attribute from the current tag, and puts it in the out.
      * @param out array of size 2.
      */
-    protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
+    protected void parseContainerAndScreen(XmlResourceParser parser, int[] out) {
         if (HOTSEAT_CONTAINER_NAME.equals(getAttributeValue(parser, ATTR_CONTAINER))) {
             out[0] = Favorites.CONTAINER_HOTSEAT;
             // Hack: hotseat items are stored using screen ids
-            out[1] = Long.parseLong(getAttributeValue(parser, ATTR_RANK));
+            out[1] = Integer.parseInt(getAttributeValue(parser, ATTR_RANK));
         } else {
             out[0] = Favorites.CONTAINER_DESKTOP;
-            out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
+            out[1] = Integer.parseInt(getAttributeValue(parser, ATTR_SCREEN));
         }
     }
 
@@ -242,9 +243,7 @@
      * Parses the current node and returns the number of elements added.
      */
     protected int parseAndAddNode(
-        XmlResourceParser parser,
-        ArrayMap<String, TagParser> tagParserMap,
-        ArrayList<Long> screenIds)
+            XmlResourceParser parser, ArrayMap<String, TagParser> tagParserMap, IntArray screenIds)
         throws XmlPullParserException, IOException {
 
         if (TAG_INCLUDE.equals(parser.getName())) {
@@ -259,8 +258,8 @@
 
         mValues.clear();
         parseContainerAndScreen(parser, mTemp);
-        final long container = mTemp[0];
-        final long screenId = mTemp[1];
+        final int container = mTemp[0];
+        final int screenId = mTemp[1];
 
         mValues.put(Favorites.CONTAINER, container);
         mValues.put(Favorites.SCREEN, screenId);
@@ -275,7 +274,7 @@
             if (LOGD) Log.d(TAG, "Ignoring unknown element tag: " + parser.getName());
             return 0;
         }
-        long newElementId = tagParser.parseAndAdd(parser);
+        int newElementId = tagParser.parseAndAdd(parser);
         if (newElementId >= 0) {
             // Keep track of the set of screens which need to be added to the db.
             if (!screenIds.contains(screenId) &&
@@ -287,8 +286,8 @@
         return 0;
     }
 
-    protected long addShortcut(String title, Intent intent, int type) {
-        long id = mCallback.generateNewItemId();
+    protected int addShortcut(String title, Intent intent, int type) {
+        int id = mCallback.generateNewItemId();
         mValues.put(Favorites.INTENT, intent.toUri(0));
         mValues.put(Favorites.TITLE, title);
         mValues.put(Favorites.ITEM_TYPE, type);
@@ -325,7 +324,7 @@
          * Parses the tag and adds to the db
          * @return the id of the row added or -1;
          */
-        long parseAndAdd(XmlResourceParser parser)
+        int parseAndAdd(XmlResourceParser parser)
                 throws XmlPullParserException, IOException;
     }
 
@@ -335,7 +334,7 @@
     protected class AppShortcutParser implements TagParser {
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) {
+        public int parseAndAdd(XmlResourceParser parser) {
             final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
             final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
 
@@ -372,7 +371,7 @@
         /**
          * Helper method to allow extending the parser capabilities
          */
-        protected long invalidPackageOrClass(XmlResourceParser parser) {
+        protected int invalidPackageOrClass(XmlResourceParser parser) {
             Log.w(TAG, "Skipping invalid <favorite> with no component");
             return -1;
         }
@@ -384,7 +383,7 @@
     protected class AutoInstallParser implements TagParser {
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) {
+        public int parseAndAdd(XmlResourceParser parser) {
             final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
             final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
             if (TextUtils.isEmpty(packageName) || TextUtils.isEmpty(className)) {
@@ -415,7 +414,7 @@
         }
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) {
+        public int parseAndAdd(XmlResourceParser parser) {
             final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
             final int iconId = getAttributeResourceValue(parser, ATTR_ICON, 0);
 
@@ -471,7 +470,7 @@
     protected class PendingWidgetParser implements TagParser {
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser)
+        public int parseAndAdd(XmlResourceParser parser)
                 throws XmlPullParserException, IOException {
             final String packageName = getAttributeValue(parser, ATTR_PACKAGE_NAME);
             final String className = getAttributeValue(parser, ATTR_CLASS_NAME);
@@ -510,7 +509,7 @@
             return verifyAndInsert(new ComponentName(packageName, className), extras);
         }
 
-        protected long verifyAndInsert(ComponentName cn, Bundle extras) {
+        protected int verifyAndInsert(ComponentName cn, Bundle extras) {
             mValues.put(Favorites.APPWIDGET_PROVIDER, cn.flattenToString());
             mValues.put(Favorites.RESTORED,
                     LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
@@ -521,7 +520,7 @@
                 mValues.put(Favorites.INTENT, new Intent().putExtras(extras).toUri(0));
             }
 
-            long insertedId = mCallback.insertAndCheck(mDb, mValues);
+            int insertedId = mCallback.insertAndCheck(mDb, mValues);
             if (insertedId < 0) {
                 return -1;
             } else {
@@ -542,7 +541,7 @@
         }
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser)
+        public int parseAndAdd(XmlResourceParser parser)
                 throws XmlPullParserException, IOException {
             final String title;
             final int titleResId = getAttributeResourceValue(parser, ATTR_TITLE, 0);
@@ -557,14 +556,14 @@
             mValues.put(Favorites.SPANX, 1);
             mValues.put(Favorites.SPANY, 1);
             mValues.put(Favorites._ID, mCallback.generateNewItemId());
-            long folderId = mCallback.insertAndCheck(mDb, mValues);
+            int folderId = mCallback.insertAndCheck(mDb, mValues);
             if (folderId < 0) {
                 if (LOGD) Log.e(TAG, "Unable to add folder");
                 return -1;
             }
 
             final ContentValues myValues = new ContentValues(mValues);
-            ArrayList<Long> folderItems = new ArrayList<>();
+            IntArray folderItems = new IntArray();
 
             int type;
             int folderDepth = parser.getDepth();
@@ -580,7 +579,7 @@
 
                 TagParser tagParser = mFolderElements.get(parser.getName());
                 if (tagParser != null) {
-                    final long id = tagParser.parseAndAdd(parser);
+                    final int id = tagParser.parseAndAdd(parser);
                     if (id >= 0) {
                         folderItems.add(id);
                         rank++;
@@ -590,7 +589,7 @@
                 }
             }
 
-            long addedId = folderId;
+            int addedId = folderId;
 
             // We can only have folders with >= 2 items, so we need to remove the
             // folder and clean up if less than 2 items were included, or some
@@ -675,9 +674,9 @@
     }
 
     public interface LayoutParserCallback {
-        long generateNewItemId();
+        int generateNewItemId();
 
-        long insertAndCheck(SQLiteDatabase db, ContentValues values);
+        int insertAndCheck(SQLiteDatabase db, ContentValues values);
     }
 
     @Thunk static void copyInteger(ContentValues from, ContentValues to, String key) {
diff --git a/src/com/android/launcher3/CellLayout.java b/src/com/android/launcher3/CellLayout.java
index a42238e..92404d4 100644
--- a/src/com/android/launcher3/CellLayout.java
+++ b/src/com/android/launcher3/CellLayout.java
@@ -2063,7 +2063,7 @@
     private void commitTempPlacement() {
         mTmpOccupied.copyTo(mOccupied);
 
-        long screenId = mLauncher.getWorkspace().getIdForScreen(this);
+        int screenId = mLauncher.getWorkspace().getIdForScreen(this);
         int container = Favorites.CONTAINER_DESKTOP;
 
         if (mContainerType == HOTSEAT) {
@@ -2688,8 +2688,8 @@
     //    the CellLayout that was long clicked
     public static final class CellInfo extends CellAndSpan {
         public final View cell;
-        final long screenId;
-        final long container;
+        final int screenId;
+        final int container;
 
         public CellInfo(View v, ItemInfo info) {
             cellX = info.cellX;
diff --git a/src/com/android/launcher3/DefaultLayoutParser.java b/src/com/android/launcher3/DefaultLayoutParser.java
index 1ec30ba..44830e8 100644
--- a/src/com/android/launcher3/DefaultLayoutParser.java
+++ b/src/com/android/launcher3/DefaultLayoutParser.java
@@ -76,13 +76,13 @@
     }
 
     @Override
-    protected void parseContainerAndScreen(XmlResourceParser parser, long[] out) {
+    protected void parseContainerAndScreen(XmlResourceParser parser, int[] out) {
         out[0] = LauncherSettings.Favorites.CONTAINER_DESKTOP;
         String strContainer = getAttributeValue(parser, ATTR_CONTAINER);
         if (strContainer != null) {
-            out[0] = Long.valueOf(strContainer);
+            out[0] = Integer.parseInt(strContainer);
         }
-        out[1] = Long.parseLong(getAttributeValue(parser, ATTR_SCREEN));
+        out[1] = Integer.parseInt(getAttributeValue(parser, ATTR_SCREEN));
     }
 
     /**
@@ -91,7 +91,7 @@
     public class AppShortcutWithUriParser extends AppShortcutParser {
 
         @Override
-        protected long invalidPackageOrClass(XmlResourceParser parser) {
+        protected int invalidPackageOrClass(XmlResourceParser parser) {
             final String uri = getAttributeValue(parser, ATTR_URI);
             if (TextUtils.isEmpty(uri)) {
                 Log.e(TAG, "Skipping invalid <favorite> with no component or uri");
@@ -205,11 +205,11 @@
         private final AppShortcutWithUriParser mChildParser = new AppShortcutWithUriParser();
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
+        public int parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
                 IOException {
             final int groupDepth = parser.getDepth();
             int type;
-            long addedId = -1;
+            int addedId = -1;
             while ((type = parser.next()) != XmlPullParser.END_TAG ||
                     parser.getDepth() > groupDepth) {
                 if (type != XmlPullParser.START_TAG || addedId > -1) {
@@ -233,7 +233,7 @@
     @Thunk class PartnerFolderParser implements TagParser {
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
+        public int parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
                 IOException {
             // Folder contents come from an external XML resource
             final Partner partner = Partner.get(mPackageManager);
@@ -259,7 +259,7 @@
     @Thunk class MyFolderParser extends FolderParser {
 
         @Override
-        public long parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
+        public int parseAndAdd(XmlResourceParser parser) throws XmlPullParserException,
                 IOException {
             final int resId = getAttributeResourceValue(parser, ATTR_FOLDER_ITEMS, 0);
             if (resId != 0) {
@@ -277,7 +277,7 @@
     protected class AppWidgetParser extends PendingWidgetParser {
 
         @Override
-        protected long verifyAndInsert(ComponentName cn, Bundle extras) {
+        protected int verifyAndInsert(ComponentName cn, Bundle extras) {
             try {
                 mPackageManager.getReceiverInfo(cn, 0);
             } catch (Exception e) {
@@ -293,7 +293,7 @@
             }
 
             final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
-            long insertedId = -1;
+            int insertedId = -1;
             try {
                 int appWidgetId = mAppWidgetHost.allocateAppWidgetId();
 
diff --git a/src/com/android/launcher3/ItemInfo.java b/src/com/android/launcher3/ItemInfo.java
index fa3253c..bffdd72 100644
--- a/src/com/android/launcher3/ItemInfo.java
+++ b/src/com/android/launcher3/ItemInfo.java
@@ -34,7 +34,7 @@
     /**
      * The id in the settings database for this item
      */
-    public long id = NO_ID;
+    public int id = NO_ID;
 
     /**
      * One of {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION},
@@ -52,14 +52,14 @@
      * will be {@link #NO_ID} (since it is not stored in the settings DB). For user folders
      * it will be the id of the folder.
      */
-    public long container = NO_ID;
+    public int container = NO_ID;
 
     /**
      * Indicates the screen in which the shortcut appears if the container types is
      * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP}. (i.e., ignore if the container type is
      * {@link LauncherSettings.Favorites#CONTAINER_HOTSEAT})
      */
-    public long screenId = -1;
+    public int screenId = -1;
 
     /**
      * Indicates the X position of the associated cell.
@@ -158,8 +158,8 @@
 
     public void readFromValues(ContentValues values) {
         itemType = values.getAsInteger(LauncherSettings.Favorites.ITEM_TYPE);
-        container = values.getAsLong(LauncherSettings.Favorites.CONTAINER);
-        screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
+        container = values.getAsInteger(LauncherSettings.Favorites.CONTAINER);
+        screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
         cellX = values.getAsInteger(LauncherSettings.Favorites.CELLX);
         cellY = values.getAsInteger(LauncherSettings.Favorites.CELLY);
         spanX = values.getAsInteger(LauncherSettings.Favorites.SPANX);
diff --git a/src/com/android/launcher3/Launcher.java b/src/com/android/launcher3/Launcher.java
index 5eb5688..4b181d8 100644
--- a/src/com/android/launcher3/Launcher.java
+++ b/src/com/android/launcher3/Launcher.java
@@ -108,6 +108,7 @@
 import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
 import com.android.launcher3.util.ActivityResultInfo;
 import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.ItemInfoMatcher;
 import com.android.launcher3.util.MultiHashMap;
 import com.android.launcher3.util.MultiValueAlpha;
@@ -490,9 +491,9 @@
      * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
      * a configuration step, this allows the proper animations to run after other transitions.
      */
-    private long completeAdd(
+    private int completeAdd(
             int requestCode, Intent intent, int appWidgetId, PendingRequestArgs info) {
-        long screenId = info.screenId;
+        int screenId = info.screenId;
         if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
             // When the screen id represents an actual screen (as opposed to a rank) we make sure
             // that the drop page actually exists.
@@ -694,7 +695,7 @@
      * @param screenId the screen id to check
      * @return the new screen, or screenId if it exists
      */
-    private long ensurePendingDropLayoutExists(long screenId) {
+    private int ensurePendingDropLayoutExists(int screenId) {
         CellLayout dropLayout = mWorkspace.getScreenWithId(screenId);
         if (dropLayout == null) {
             // it's possible that the add screen was removed because it was
@@ -974,7 +975,7 @@
      *
      * @param data The intent describing the shortcut.
      */
-    private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
+    private void completeAddShortcut(Intent data, int container, int screenId, int cellX,
             int cellY, PendingRequestArgs args) {
         if (args.getRequestCode() != REQUEST_CREATE_SHORTCUT
                 || args.getPendingIntent().getComponent() == null) {
@@ -1050,7 +1051,7 @@
         }
     }
 
-    public FolderIcon findFolderIcon(final long folderIconId) {
+    public FolderIcon findFolderIcon(final int folderIconId) {
         return (FolderIcon) mWorkspace.getHomescreenIconByItemId(folderIconId);
     }
 
@@ -1413,7 +1414,7 @@
         }
     }
 
-    public void addPendingItem(PendingAddItemInfo info, long container, long screenId,
+    public void addPendingItem(PendingAddItemInfo info, int container, int screenId,
             int[] cell, int spanX, int spanY) {
         info.container = container;
         info.screenId = screenId;
@@ -1489,7 +1490,7 @@
         }
     }
 
-    FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
+    FolderIcon addFolder(CellLayout layout, int container, final int screenId, int cellX,
             int cellY) {
         final FolderInfo folderInfo = new FolderInfo();
         folderInfo.title = getText(R.string.folder_name);
@@ -1650,7 +1651,7 @@
     /**
      * Returns the CellLayout of the specified container at the specified screen.
      */
-    public CellLayout getCellLayout(long container, long screenId) {
+    public CellLayout getCellLayout(int container, int screenId) {
         if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
             if (mHotseat != null) {
                 return mHotseat.getLayout();
@@ -1750,11 +1751,11 @@
     }
 
     @Override
-    public void bindScreens(ArrayList<Long> orderedScreenIds) {
+    public void bindScreens(IntArray orderedScreenIds) {
         // Make sure the first screen is always at the start.
         if (FeatureFlags.getInstance(this).isQsbOnFirstScreenEnabled() &&
                 orderedScreenIds.indexOf(Workspace.FIRST_SCREEN_ID) != 0) {
-            orderedScreenIds.remove(Workspace.FIRST_SCREEN_ID);
+            orderedScreenIds.removeValue(Workspace.FIRST_SCREEN_ID);
             orderedScreenIds.add(0, Workspace.FIRST_SCREEN_ID);
             LauncherModel.updateWorkspaceScreenOrder(this, orderedScreenIds);
         } else if (!FeatureFlags.getInstance(this).isQsbOnFirstScreenEnabled()
@@ -1770,10 +1771,10 @@
         mWorkspace.unlockWallpaperFromDefaultPageOnNextLayout();
     }
 
-    private void bindAddScreens(ArrayList<Long> orderedScreenIds) {
+    private void bindAddScreens(IntArray orderedScreenIds) {
         int count = orderedScreenIds.size();
         for (int i = 0; i < count; i++) {
-            long screenId = orderedScreenIds.get(i);
+            int screenId = orderedScreenIds.get(i);
             if (!FeatureFlags.getInstance(this).isQsbOnFirstScreenEnabled()
                     || screenId != Workspace.FIRST_SCREEN_ID) {
                 // No need to bind the first screen, as its always bound.
@@ -1794,7 +1795,7 @@
     }
 
     @Override
-    public void bindAppsAdded(ArrayList<Long> newScreens, ArrayList<ItemInfo> addNotAnimated,
+    public void bindAppsAdded(IntArray newScreens, ArrayList<ItemInfo> addNotAnimated,
             ArrayList<ItemInfo> addAnimated) {
         // Add the new screens
         if (newScreens != null) {
@@ -1825,7 +1826,7 @@
         final Collection<Animator> bounceAnims = new ArrayList<>();
         final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
         Workspace workspace = mWorkspace;
-        long newItemsScreenId = -1;
+        int newItemsScreenId = -1;
         int end = items.size();
         for (int i = 0; i < end; i++) {
             final ItemInfo item = items.get(i);
@@ -1898,7 +1899,7 @@
             AnimatorSet anim = new AnimatorSet();
             anim.playTogether(bounceAnims);
 
-            long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
+            int currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
             final int newScreenIndex = mWorkspace.getPageIndexForScreenId(newItemsScreenId);
             final Runnable startBounceAnimRunnable = anim::start;
 
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java
index 5424d97..cbfde25 100644
--- a/src/com/android/launcher3/LauncherModel.java
+++ b/src/com/android/launcher3/LauncherModel.java
@@ -55,6 +55,7 @@
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.shortcuts.ShortcutInfoCompat;
 import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.ItemInfoMatcher;
 import com.android.launcher3.util.MultiHashMap;
 import com.android.launcher3.util.PackageUserKey;
@@ -143,15 +144,14 @@
         public void clearPendingBinds();
         public void startBinding();
         public void bindItems(List<ItemInfo> shortcuts, boolean forceAnimateIcons);
-        public void bindScreens(ArrayList<Long> orderedScreenIds);
+        public void bindScreens(IntArray orderedScreenIds);
         public void finishFirstPageBind(ViewOnDrawExecutor executor);
         public void finishBindingItems(int currentScreen);
         public void bindAllApplications(ArrayList<AppInfo> apps);
         public void bindAppsAddedOrUpdated(ArrayList<AppInfo> apps);
         public void preAddApps();
-        public void bindAppsAdded(ArrayList<Long> newScreens,
-                                  ArrayList<ItemInfo> addNotAnimated,
-                                  ArrayList<ItemInfo> addAnimated);
+        public void bindAppsAdded(IntArray newScreens,
+                ArrayList<ItemInfo> addNotAnimated, ArrayList<ItemInfo> addAnimated);
         public void bindPromiseAppProgressUpdated(PromiseAppInfo app);
         public void bindShortcutsChanged(ArrayList<ShortcutInfo> updated, UserHandle user);
         public void bindWidgetsRestored(ArrayList<LauncherAppWidgetInfo> widgets);
@@ -211,7 +211,7 @@
     }
 
     static void checkItemInfoLocked(
-            final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
+            final int itemId, final ItemInfo item, StackTraceElement[] stackTrace) {
         if (com.android.launcher3.Utilities.IS_RUNNING_IN_TEST_HARNESS
                 && com.android.launcher3.Utilities.IS_DEBUG_DEVICE) {
             android.util.Log.d("b/117332845",
@@ -255,7 +255,7 @@
 
     static void checkItemInfo(final ItemInfo item) {
         final StackTraceElement[] stackTrace = new Throwable().getStackTrace();
-        final long itemId = item.id;
+        final int itemId = item.id;
         Runnable r = new Runnable() {
             public void run() {
                 synchronized (sBgDataModel) {
@@ -270,17 +270,16 @@
      * Update the order of the workspace screens in the database. The array list contains
      * a list of screen ids in the order that they should appear.
      */
-    public static void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) {
-        final ArrayList<Long> screensCopy = new ArrayList<Long>(screens);
+    public static void updateWorkspaceScreenOrder(Context context, IntArray screens) {
         final ContentResolver cr = context.getContentResolver();
         final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
 
-        // Remove any negative screen ids -- these aren't persisted
-        Iterator<Long> iter = screensCopy.iterator();
-        while (iter.hasNext()) {
-            long id = iter.next();
-            if (id < 0) {
-                iter.remove();
+        // Create a copy with only non-negative values
+        final IntArray screensCopy = new IntArray();
+        for (int i = 0; i < screens.size(); i++) {
+            int id = screens.get(i);
+            if (id >= 0) {
+                screensCopy.add(id);
             }
         }
 
@@ -293,7 +292,7 @@
                 int count = screensCopy.size();
                 for (int i = 0; i < count; i++) {
                     ContentValues v = new ContentValues();
-                    long screenId = screensCopy.get(i);
+                    int screenId = screensCopy.get(i);
                     v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                     v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                     ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
@@ -452,6 +451,11 @@
      * @return true if the page could be bound synchronously.
      */
     public boolean startLoader(int synchronousBindPage) {
+        if (com.android.launcher3.Utilities.IS_RUNNING_IN_TEST_HARNESS
+                && com.android.launcher3.Utilities.IS_DEBUG_DEVICE) {
+            android.util.Log.d("b/117332845",
+                    android.util.Log.getStackTraceString(new Throwable()));
+        }
         // Enable queue before starting loader. It will get disabled in Launcher#finishBindingItems
         InstallShortcutReceiver.enableInstallQueue(InstallShortcutReceiver.FLAG_LOADER_RUNNING);
         synchronized (mLock) {
@@ -516,7 +520,7 @@
     /**
      * Loads the workspace screen ids in an ordered list.
      */
-    public static ArrayList<Long> loadWorkspaceScreensDb(Context context) {
+    public static IntArray loadWorkspaceScreensDb(Context context) {
         final ContentResolver contentResolver = context.getContentResolver();
         final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
 
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index ddb2721..a423a90 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -58,6 +58,8 @@
 import com.android.launcher3.provider.LauncherDbUtils;
 import com.android.launcher3.provider.LauncherDbUtils.SQLiteTransaction;
 import com.android.launcher3.provider.RestoreDbTask;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSet;
 import com.android.launcher3.util.NoLocaleSQLiteHelper;
 import com.android.launcher3.util.Preconditions;
 import com.android.launcher3.util.Thunk;
@@ -67,6 +69,7 @@
 import java.io.PrintWriter;
 import java.net.URISyntaxException;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
@@ -170,7 +173,7 @@
         return result;
     }
 
-    @Thunk static long dbInsertAndCheck(DatabaseHelper helper,
+    @Thunk static int dbInsertAndCheck(DatabaseHelper helper,
             SQLiteDatabase db, String table, String nullColumnHack, ContentValues values) {
         if (values == null) {
             throw new RuntimeException("Error: attempting to insert null values");
@@ -179,7 +182,7 @@
             throw new RuntimeException("Error: attempting to add item without specifying an id");
         }
         helper.checkId(table, values);
-        return db.insert(table, nullColumnHack, values);
+        return (int) db.insert(table, nullColumnHack, values);
     }
 
     private void reloadLauncherIfExternal() {
@@ -205,7 +208,7 @@
 
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         addModifiedTime(initialValues);
-        final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
+        final int rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
         if (rowId < 0) return null;
 
         uri = ContentUris.withAppendedId(uri, rowId);
@@ -230,7 +233,7 @@
 
     private boolean initializeExternalAdd(ContentValues values) {
         // 1. Ensure that externally added items have a valid item id
-        long id = mOpenHelper.generateNewItemId();
+        int id = mOpenHelper.generateNewItemId();
         values.put(LauncherSettings.Favorites._ID, id);
 
         // 2. In the case of an app widget, and if no app widget id is specified, we
@@ -263,7 +266,7 @@
         }
 
         // Add screen id if not present
-        long screenId = values.getAsLong(LauncherSettings.Favorites.SCREEN);
+        int screenId = values.getAsInteger(LauncherSettings.Favorites.SCREEN);
         SQLiteStatement stmp = null;
         try {
             stmp = mOpenHelper.getWritableDatabase().compileStatement(
@@ -369,17 +372,18 @@
             }
             case LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS: {
                 Bundle result = new Bundle();
-                result.putSerializable(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders());
+                result.putIntArray(LauncherSettings.Settings.EXTRA_VALUE, deleteEmptyFolders()
+                        .toArray());
                 return result;
             }
             case LauncherSettings.Settings.METHOD_NEW_ITEM_ID: {
                 Bundle result = new Bundle();
-                result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
+                result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewItemId());
                 return result;
             }
             case LauncherSettings.Settings.METHOD_NEW_SCREEN_ID: {
                 Bundle result = new Bundle();
-                result.putLong(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
+                result.putInt(LauncherSettings.Settings.EXTRA_VALUE, mOpenHelper.generateNewScreenId());
                 return result;
             }
             case LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB: {
@@ -402,8 +406,8 @@
      * Deletes any empty folder from the DB.
      * @return Ids of deleted folders.
      */
-    private ArrayList<Long> deleteEmptyFolders() {
-        ArrayList<Long> folderIds = new ArrayList<>();
+    private IntArray deleteEmptyFolders() {
+        IntArray folderIds = new IntArray();
         SQLiteDatabase db = mOpenHelper.getWritableDatabase();
         try (SQLiteTransaction t = new SQLiteTransaction(db)) {
             // Select folders whose id do not match any container value.
@@ -542,8 +546,8 @@
     public static class DatabaseHelper extends NoLocaleSQLiteHelper implements LayoutParserCallback {
         private final Handler mWidgetHostResetHandler;
         private final Context mContext;
-        private long mMaxItemId = -1;
-        private long mMaxScreenId = -1;
+        private int mMaxItemId = -1;
+        private int mMaxScreenId = -1;
 
         DatabaseHelper(Context context, Handler widgetHostResetHandler) {
             this(context, widgetHostResetHandler, LauncherFiles.LAUNCHER_DB);
@@ -844,7 +848,7 @@
                 Log.e(TAG, "getAppWidgetIds not supported", e);
                 return;
             }
-            final HashSet<Integer> validWidgets = new HashSet<>();
+            final IntSet validWidgets = new IntSet();
             try (Cursor c = db.query(Favorites.TABLE_NAME,
                     new String[] {Favorites.APPWIDGET_ID },
                     "itemType=" + Favorites.ITEM_TYPE_APPWIDGET, null, null, null, null)) {
@@ -899,7 +903,7 @@
                         continue;
                     }
 
-                    long id = c.getLong(idIndex);
+                    int id = c.getInt(idIndex);
                     updateStmt.bindLong(1, id);
                     updateStmt.executeUpdateDelete();
                 }
@@ -914,15 +918,14 @@
          */
         public boolean recreateWorkspaceTable(SQLiteDatabase db) {
             try (SQLiteTransaction t = new SQLiteTransaction(db)) {
-                final ArrayList<Long> sortedIDs;
+                final IntArray sortedIDs;
 
                 try (Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
                         new String[] {LauncherSettings.WorkspaceScreens._ID},
                         null, null, null, null,
                         LauncherSettings.WorkspaceScreens.SCREEN_RANK)) {
                     // Use LinkedHashSet so that ordering is preserved
-                    sortedIDs = new ArrayList<>(
-                            LauncherDbUtils.iterateCursor(c, 0, new LinkedHashSet<Long>()));
+                    sortedIDs = LauncherDbUtils.getScreenIdsFromCursor(c);
                 }
                 db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
                 addWorkspacesTable(db, false);
@@ -937,7 +940,11 @@
                     db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
                 }
                 t.commit();
-                mMaxScreenId = sortedIDs.isEmpty() ? 0 : Collections.max(sortedIDs);
+
+                mMaxScreenId = 0;
+                for (int i = 0; i < sortedIDs.size(); i++) {
+                    mMaxScreenId = Math.max(mMaxScreenId, sortedIDs.get(i));
+                }
             } catch (SQLException ex) {
                 // Old version remains, which means we wipe old data
                 Log.e(TAG, ex.getMessage(), ex);
@@ -997,7 +1004,7 @@
         // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
         // after that point
         @Override
-        public long generateNewItemId() {
+        public int generateNewItemId() {
             if (mMaxItemId < 0) {
                 throw new RuntimeException("Error: max item id was not initialized");
             }
@@ -1010,12 +1017,12 @@
         }
 
         @Override
-        public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
+        public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
             return dbInsertAndCheck(this, db, Favorites.TABLE_NAME, null, values);
         }
 
         public void checkId(String table, ContentValues values) {
-            long id = values.getAsLong(LauncherSettings.BaseLauncherColumns._ID);
+            int id = values.getAsInteger(LauncherSettings.BaseLauncherColumns._ID);
             if (WorkspaceScreens.TABLE_NAME.equals(table)) {
                 mMaxScreenId = Math.max(id, mMaxScreenId);
             }  else {
@@ -1023,7 +1030,7 @@
             }
         }
 
-        private long initializeMaxItemId(SQLiteDatabase db) {
+        private int initializeMaxItemId(SQLiteDatabase db) {
             return getMaxId(db, Favorites.TABLE_NAME);
         }
 
@@ -1032,7 +1039,7 @@
         // call the constructor from the worker thread; however, this doesn't extend until after the
         // constructor is called, and we only pass a reference to LauncherProvider to LauncherApp
         // after that point
-        public long generateNewScreenId() {
+        public int generateNewScreenId() {
             if (mMaxScreenId < 0) {
                 throw new RuntimeException("Error: max screen id was not initialized");
             }
@@ -1040,20 +1047,21 @@
             return mMaxScreenId;
         }
 
-        private long initializeMaxScreenId(SQLiteDatabase db) {
+        private int initializeMaxScreenId(SQLiteDatabase db) {
             return getMaxId(db, WorkspaceScreens.TABLE_NAME);
         }
 
         @Thunk int loadFavorites(SQLiteDatabase db, AutoInstallsLayout loader) {
-            ArrayList<Long> screenIds = new ArrayList<Long>();
+            IntArray screenIds = new IntArray();
             // TODO: Use multiple loaders with fall-back and transaction.
             int count = loader.loadLayout(db, screenIds);
 
             // Add the screens specified by the items above
-            Collections.sort(screenIds);
+            int[] sortedScreenIds = screenIds.toArray();
+            Arrays.sort(sortedScreenIds);
             int rank = 0;
             ContentValues values = new ContentValues();
-            for (Long id : screenIds) {
+            for (int id : sortedScreenIds) {
                 values.clear();
                 values.put(LauncherSettings.WorkspaceScreens._ID, id);
                 values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, rank);
@@ -1075,12 +1083,12 @@
     /**
      * @return the max _id in the provided table.
      */
-    @Thunk static long getMaxId(SQLiteDatabase db, String table) {
+    @Thunk static int getMaxId(SQLiteDatabase db, String table) {
         Cursor c = db.rawQuery("SELECT MAX(_id) FROM " + table, null);
         // get the result
-        long id = -1;
+        int id = -1;
         if (c != null && c.moveToNext()) {
-            id = c.getLong(0);
+            id = c.getInt(0);
         }
         if (c != null) {
             c.close();
diff --git a/src/com/android/launcher3/LauncherSettings.java b/src/com/android/launcher3/LauncherSettings.java
index 3b337ef..0b12b15 100644
--- a/src/com/android/launcher3/LauncherSettings.java
+++ b/src/com/android/launcher3/LauncherSettings.java
@@ -128,7 +128,7 @@
          *
          * @return The unique content URL for the specified row.
          */
-        public static Uri getContentUri(long id) {
+        public static Uri getContentUri(int id) {
             return Uri.parse("content://" + LauncherProvider.AUTHORITY +
                     "/" + TABLE_NAME + "/" + id);
         }
diff --git a/src/com/android/launcher3/Utilities.java b/src/com/android/launcher3/Utilities.java
index 231c4b7..d11cfcb 100644
--- a/src/com/android/launcher3/Utilities.java
+++ b/src/com/android/launcher3/Utilities.java
@@ -52,6 +52,7 @@
 import android.view.animation.Interpolator;
 
 import com.android.launcher3.config.FeatureFlags;
+import com.android.launcher3.util.IntArray;
 
 import java.io.ByteArrayOutputStream;
 import java.io.Closeable;
@@ -456,8 +457,8 @@
                 size, metrics));
     }
 
-    public static String createDbSelectionQuery(String columnName, Iterable<?> values) {
-        return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, TextUtils.join(", ", values));
+    public static String createDbSelectionQuery(String columnName, IntArray values) {
+        return String.format(Locale.ENGLISH, "%s IN (%s)", columnName, values.toConcatString());
     }
 
     public static boolean isBootCompleted() {
@@ -514,13 +515,6 @@
         return spanned;
     }
 
-    /**
-     * Replacement for Long.compare() which was added in API level 19.
-     */
-    public static int longCompare(long lhs, long rhs) {
-        return lhs < rhs ? -1 : (lhs == rhs ? 0 : 1);
-    }
-
     public static SharedPreferences getPrefs(Context context) {
         return context.getSharedPreferences(
                 LauncherFiles.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
diff --git a/src/com/android/launcher3/Workspace.java b/src/com/android/launcher3/Workspace.java
index df43483..5e1c54c 100644
--- a/src/com/android/launcher3/Workspace.java
+++ b/src/com/android/launcher3/Workspace.java
@@ -28,7 +28,6 @@
 import android.animation.AnimatorListenerAdapter;
 import android.animation.LayoutTransition;
 import android.animation.ObjectAnimator;
-import android.animation.PropertyValuesHolder;
 import android.animation.ValueAnimator;
 import android.animation.ValueAnimator.AnimatorUpdateListener;
 import android.annotation.SuppressLint;
@@ -85,8 +84,10 @@
 import com.android.launcher3.userevent.nano.LauncherLogProto.Action;
 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
 import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
+import com.android.launcher3.util.IntSet;
 import com.android.launcher3.util.ItemInfoMatcher;
-import com.android.launcher3.util.LongArrayMap;
 import com.android.launcher3.util.PackageUserKey;
 import com.android.launcher3.util.Thunk;
 import com.android.launcher3.util.WallpaperOffsetInterpolator;
@@ -130,17 +131,17 @@
     private static final boolean MAP_RECURSE = true;
 
     // The screen id used for the empty screen always present to the right.
-    public static final long EXTRA_EMPTY_SCREEN_ID = -201;
+    public static final int EXTRA_EMPTY_SCREEN_ID = -201;
     // The is the first screen. It is always present, even if its empty.
-    public static final long FIRST_SCREEN_ID = 0;
+    public static final int FIRST_SCREEN_ID = 0;
 
     private LayoutTransition mLayoutTransition;
     @Thunk final WallpaperManager mWallpaperManager;
 
     private ShortcutAndWidgetContainer mDragSourceInternal;
 
-    @Thunk final LongArrayMap<CellLayout> mWorkspaceScreens = new LongArrayMap<>();
-    @Thunk final ArrayList<Long> mScreenOrder = new ArrayList<>();
+    @Thunk final IntSparseArrayMap<CellLayout> mWorkspaceScreens = new IntSparseArrayMap<>();
+    @Thunk final IntArray mScreenOrder = new IntArray();
 
     @Thunk Runnable mRemoveEmptyScreenRunnable;
     @Thunk boolean mDeferRemoveExtraEmptyScreen = false;
@@ -227,7 +228,7 @@
     @Thunk int mLastReorderY = -1;
 
     private SparseArray<Parcelable> mSavedStates;
-    private final ArrayList<Integer> mRestoredPages = new ArrayList<>();
+    private final IntArray mRestoredPages = new IntArray();
 
     private float mCurrentScale;
     private float mTransitionProgress;
@@ -523,7 +524,7 @@
         enableLayoutTransitions();
     }
 
-    public void insertNewWorkspaceScreenBeforeEmptyScreen(long screenId) {
+    public void insertNewWorkspaceScreenBeforeEmptyScreen(int screenId) {
         // Find the index to insert this view into.  If the empty screen exists, then
         // insert it before that.
         int insertIndex = mScreenOrder.indexOf(EXTRA_EMPTY_SCREEN_ID);
@@ -533,11 +534,11 @@
         insertNewWorkspaceScreen(screenId, insertIndex);
     }
 
-    public void insertNewWorkspaceScreen(long screenId) {
+    public void insertNewWorkspaceScreen(int screenId) {
         insertNewWorkspaceScreen(screenId, getChildCount());
     }
 
-    public CellLayout insertNewWorkspaceScreen(long screenId, int insertIndex) {
+    public CellLayout insertNewWorkspaceScreen(int screenId, int insertIndex) {
         if (mWorkspaceScreens.containsKey(screenId)) {
             throw new RuntimeException("Screen id " + screenId + " already exists!");
         }
@@ -604,7 +605,7 @@
         }
 
         if (hasExtraEmptyScreen() || mScreenOrder.size() == 0) return;
-        long finalScreenId = mScreenOrder.get(mScreenOrder.size() - 1);
+        int finalScreenId = mScreenOrder.get(mScreenOrder.size() - 1);
 
         CellLayout finalScreen = mWorkspaceScreens.get(finalScreenId);
 
@@ -612,7 +613,7 @@
         if (finalScreen.getShortcutsAndWidgets().getChildCount() == 0 &&
                 !finalScreen.isDropPending()) {
             mWorkspaceScreens.remove(finalScreenId);
-            mScreenOrder.remove(finalScreenId);
+            mScreenOrder.removeValue(finalScreenId);
 
             // if this is the last screen, convert it to the empty screen
             mWorkspaceScreens.put(EXTRA_EMPTY_SCREEN_ID, finalScreen);
@@ -678,7 +679,7 @@
             public void run() {
                 if (hasExtraEmptyScreen()) {
                     mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
-                    mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
+                    mScreenOrder.removeValue(EXTRA_EMPTY_SCREEN_ID);
                     removeView(cl);
                     if (stripEmptyScreens) {
                         stripEmptyScreens();
@@ -710,7 +711,7 @@
         return mWorkspaceScreens.containsKey(EXTRA_EMPTY_SCREEN_ID) && getChildCount() > 1;
     }
 
-    public long commitExtraEmptyScreen() {
+    public int commitExtraEmptyScreen() {
         if (mLauncher.isWorkspaceLoading()) {
             // Invalid and dangerous operation if workspace is loading
             return -1;
@@ -718,11 +719,11 @@
 
         CellLayout cl = mWorkspaceScreens.get(EXTRA_EMPTY_SCREEN_ID);
         mWorkspaceScreens.remove(EXTRA_EMPTY_SCREEN_ID);
-        mScreenOrder.remove(EXTRA_EMPTY_SCREEN_ID);
+        mScreenOrder.removeValue(EXTRA_EMPTY_SCREEN_ID);
 
-        long newId = LauncherSettings.Settings.call(getContext().getContentResolver(),
+        int newId = LauncherSettings.Settings.call(getContext().getContentResolver(),
                 LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
-                .getLong(LauncherSettings.Settings.EXTRA_VALUE);
+                .getInt(LauncherSettings.Settings.EXTRA_VALUE);
         mWorkspaceScreens.put(newId, cl);
         mScreenOrder.add(newId);
 
@@ -732,11 +733,11 @@
         return newId;
     }
 
-    public CellLayout getScreenWithId(long screenId) {
+    public CellLayout getScreenWithId(int screenId) {
         return mWorkspaceScreens.get(screenId);
     }
 
-    public long getIdForScreen(CellLayout layout) {
+    public int getIdForScreen(CellLayout layout) {
         int index = mWorkspaceScreens.indexOfValue(layout);
         if (index != -1) {
             return mWorkspaceScreens.keyAt(index);
@@ -744,18 +745,18 @@
         return -1;
     }
 
-    public int getPageIndexForScreenId(long screenId) {
+    public int getPageIndexForScreenId(int screenId) {
         return indexOfChild(mWorkspaceScreens.get(screenId));
     }
 
-    public long getScreenIdForPageIndex(int index) {
+    public int getScreenIdForPageIndex(int index) {
         if (0 <= index && index < mScreenOrder.size()) {
             return mScreenOrder.get(index);
         }
         return -1;
     }
 
-    public ArrayList<Long> getScreenOrder() {
+    public IntArray getScreenOrder() {
         return mScreenOrder;
     }
 
@@ -772,10 +773,10 @@
         }
 
         int currentPage = getNextPage();
-        ArrayList<Long> removeScreens = new ArrayList<>();
+        IntArray removeScreens = new IntArray();
         int total = mWorkspaceScreens.size();
         for (int i = 0; i < total; i++) {
-            long id = mWorkspaceScreens.keyAt(i);
+            int id = mWorkspaceScreens.keyAt(i);
             CellLayout cl = mWorkspaceScreens.valueAt(i);
             // FIRST_SCREEN_ID can never be removed.
             boolean qsbFirstScreenEnabled = 
@@ -793,10 +794,11 @@
         int minScreens = 1;
 
         int pageShift = 0;
-        for (Long id: removeScreens) {
+        for (int i = 0; i < removeScreens.size(); i++) {
+            int id = removeScreens.get(i);
             CellLayout cl = mWorkspaceScreens.get(id);
             mWorkspaceScreens.remove(id);
-            mScreenOrder.remove(id);
+            mScreenOrder.removeValue(id);
 
             if (getChildCount() > minScreens) {
                 if (indexOfChild(cl) < currentPage) {
@@ -845,7 +847,7 @@
 
     /**
      * Adds the specified child in the specified screen based on the {@param info}
-     * See {@link #addInScreen(View, long, long, int, int, int, int)}.
+     * See {@link #addInScreen(View, int, int, int, int, int, int)}.
      */
     public void addInScreen(View child, ItemInfo info) {
         addInScreen(child, info.container, info.screenId, info.cellX, info.cellY,
@@ -863,7 +865,7 @@
      * @param spanX The number of cells spanned horizontally by the child.
      * @param spanY The number of cells spanned vertically by the child.
      */
-    private void addInScreen(View child, long container, long screenId, int x, int y,
+    private void addInScreen(View child, int container, int screenId, int x, int y,
             int spanX, int spanY) {
         if (container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
             if (getScreenWithId(screenId) == null) {
@@ -1677,7 +1679,7 @@
             }
         }
 
-        long screenId = getIdForScreen(dropTargetLayout);
+        int screenId = getIdForScreen(dropTargetLayout);
         if (screenId == EXTRA_EMPTY_SCREEN_ID) {
             commitExtraEmptyScreen();
         }
@@ -1742,7 +1744,7 @@
         return false;
     }
 
-    boolean createUserFolderIfNecessary(View newView, long container, CellLayout target,
+    boolean createUserFolderIfNecessary(View newView, int container, CellLayout target,
             int[] targetCell, float distance, boolean external, DragView dragView) {
         if (distance > mMaxDistanceForFolderCreation) return false;
         View v = target.getChildAt(targetCell[0], targetCell[1]);
@@ -1756,7 +1758,7 @@
 
         if (v == null || hasntMoved || !mCreateUserFolderOnDrop) return false;
         mCreateUserFolderOnDrop = false;
-        final long screenId = getIdForScreen(target);
+        final int screenId = getIdForScreen(target);
 
         boolean aboveShortcut = (v.getTag() instanceof ShortcutInfo);
         boolean willBecomeShortcut = (newView.getTag() instanceof ShortcutInfo);
@@ -1855,10 +1857,10 @@
                 // Move internally
                 boolean hasMovedLayouts = (getParentCellLayoutForView(cell) != dropTargetLayout);
                 boolean hasMovedIntoHotseat = mLauncher.isHotseatLayout(dropTargetLayout);
-                long container = hasMovedIntoHotseat ?
+                int container = hasMovedIntoHotseat ?
                         LauncherSettings.Favorites.CONTAINER_HOTSEAT :
                         LauncherSettings.Favorites.CONTAINER_DESKTOP;
-                long screenId = (mTargetCell[0] < 0) ?
+                int screenId = (mTargetCell[0] < 0) ?
                         mDragInfo.screenId : getIdForScreen(dropTargetLayout);
                 int spanX = mDragInfo != null ? mDragInfo.spanX : 1;
                 int spanY = mDragInfo != null ? mDragInfo.spanY : 1;
@@ -2532,10 +2534,10 @@
             spanY = mDragInfo.spanY;
         }
 
-        final long container = mLauncher.isHotseatLayout(cellLayout) ?
+        final int container = mLauncher.isHotseatLayout(cellLayout) ?
                 LauncherSettings.Favorites.CONTAINER_HOTSEAT :
                     LauncherSettings.Favorites.CONTAINER_DESKTOP;
-        final long screenId = getIdForScreen(cellLayout);
+        final int screenId = getIdForScreen(cellLayout);
         if (!mLauncher.isHotseatLayout(cellLayout)
                 && screenId != getScreenIdForPageIndex(mCurrentPage)
                 && !mLauncher.isInState(SPRING_LOADED)) {
@@ -3008,7 +3010,7 @@
         return childrenLayouts;
     }
 
-    public View getHomescreenIconByItemId(final long id) {
+    public View getHomescreenIconByItemId(final int id) {
         return getFirstMatch(new ItemOperator() {
 
             @Override
@@ -3067,7 +3069,7 @@
         for (final CellLayout layoutParent: cellLayouts) {
             final ViewGroup layout = layoutParent.getShortcutsAndWidgets();
 
-            LongArrayMap<View> idToViewMap = new LongArrayMap<>();
+            IntSparseArrayMap<View> idToViewMap = new IntSparseArrayMap<>();
             ArrayList<ItemInfo> items = new ArrayList<>();
             for (int j = 0; j < layout.getChildCount(); j++) {
                 final View view = layout.getChildAt(j);
@@ -3155,7 +3157,7 @@
     void updateShortcuts(ArrayList<ShortcutInfo> shortcuts) {
         int total  = shortcuts.size();
         final HashSet<ShortcutInfo> updates = new HashSet<>(total);
-        final HashSet<Long> folderIds = new HashSet<>();
+        final IntSet folderIds = new IntSet();
 
         for (int i = 0; i < total; i++) {
             ShortcutInfo s = shortcuts.get(i);
@@ -3195,7 +3197,7 @@
 
     public void updateIconBadges(final Set<PackageUserKey> updatedBadges) {
         final PackageUserKey packageUserKey = new PackageUserKey(null, null);
-        final HashSet<Long> folderIds = new HashSet<>();
+        final IntSet folderIds = new IntSet();
         mapOverItems(MAP_RECURSE, new ItemOperator() {
             @Override
             public boolean evaluate(ItemInfo info, View v) {
diff --git a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
index 81a0e1d..84edb3d 100644
--- a/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/LauncherAccessibilityDelegate.java
@@ -39,6 +39,7 @@
 import com.android.launcher3.popup.PopupContainerWithArrow;
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.touch.ItemLongClickListener;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.Thunk;
 import com.android.launcher3.widget.LauncherAppWidgetHostView;
 
@@ -159,7 +160,7 @@
             beginAccessibleDrag(host, item);
         } else if (action == ADD_TO_WORKSPACE) {
             final int[] coordinates = new int[2];
-            final long screenId = findSpaceOnWorkspace(item, coordinates);
+            final int screenId = findSpaceOnWorkspace(item, coordinates);
             mLauncher.getStateManager().goToState(NORMAL, true, new Runnable() {
 
                 @Override
@@ -191,7 +192,7 @@
             folder.getInfo().remove(info, false);
 
             final int[] coordinates = new int[2];
-            final long screenId = findSpaceOnWorkspace(item, coordinates);
+            final int screenId = findSpaceOnWorkspace(item, coordinates);
             mLauncher.getModelWriter().moveItemInDatabase(info,
                     LauncherSettings.Favorites.CONTAINER_DESKTOP,
                     screenId, coordinates[0], coordinates[1]);
@@ -210,7 +211,7 @@
             });
         } else if (action == RESIZE) {
             final LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) item;
-            final ArrayList<Integer> actions = getSupportedResizeActions(host, info);
+            final IntArray actions = getSupportedResizeActions(host, info);
             CharSequence[] labels = new CharSequence[actions.size()];
             for (int i = 0; i < actions.size(); i++) {
                 labels[i] = mLauncher.getText(actions.get(i));
@@ -242,8 +243,8 @@
         return false;
     }
 
-    private ArrayList<Integer> getSupportedResizeActions(View host, LauncherAppWidgetInfo info) {
-        ArrayList<Integer> actions = new ArrayList<>();
+    private IntArray getSupportedResizeActions(View host, LauncherAppWidgetInfo info) {
+        IntArray actions = new IntArray();
 
         AppWidgetProviderInfo providerInfo = ((LauncherAppWidgetHostView) host).getAppWidgetInfo();
         if (providerInfo == null) {
@@ -392,10 +393,10 @@
     /**
      * Find empty space on the workspace and returns the screenId.
      */
-    protected long findSpaceOnWorkspace(ItemInfo info, int[] outCoordinates) {
+    protected int findSpaceOnWorkspace(ItemInfo info, int[] outCoordinates) {
         Workspace workspace = mLauncher.getWorkspace();
-        ArrayList<Long> workspaceScreens = workspace.getScreenOrder();
-        long screenId;
+        IntArray workspaceScreens = workspace.getScreenOrder();
+        int screenId;
 
         // First check if there is space on the current screen.
         int screenIndex = workspace.getCurrentPage();
diff --git a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
index cfb0520..f37f70b 100644
--- a/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
+++ b/src/com/android/launcher3/accessibility/ShortcutMenuAccessibilityDelegate.java
@@ -66,7 +66,7 @@
             }
             final ShortcutInfo info = ((DeepShortcutView) host.getParent()).getFinalInfo();
             final int[] coordinates = new int[2];
-            final long screenId = findSpaceOnWorkspace(item, coordinates);
+            final int screenId = findSpaceOnWorkspace(item, coordinates);
             Runnable onComplete = new Runnable() {
                 @Override
                 public void run() {
diff --git a/src/com/android/launcher3/compat/UserManagerCompatVL.java b/src/com/android/launcher3/compat/UserManagerCompatVL.java
index eec3438..ef72842 100644
--- a/src/com/android/launcher3/compat/UserManagerCompatVL.java
+++ b/src/com/android/launcher3/compat/UserManagerCompatVL.java
@@ -17,32 +17,29 @@
 package com.android.launcher3.compat;
 
 import android.content.Context;
-import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.util.ArrayMap;
-import com.android.launcher3.util.LongArrayMap;
+import android.util.LongSparseArray;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
 public class UserManagerCompatVL extends UserManagerCompat {
-    private static final String USER_CREATION_TIME_KEY = "user_creation_time_";
 
     protected final UserManager mUserManager;
     private final PackageManager mPm;
-    private final Context mContext;
 
-    protected LongArrayMap<UserHandle> mUsers;
-    // Create a separate reverse map as LongArrayMap.indexOfValue checks if objects are same
+    protected LongSparseArray<UserHandle> mUsers;
+    // Create a separate reverse map as LongSparseArray.indexOfValue checks if objects are same
     // and not {@link Object#equals}
     protected ArrayMap<UserHandle, Long> mUserToSerialMap;
 
     UserManagerCompatVL(Context context) {
         mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
         mPm = context.getPackageManager();
-        mContext = context;
     }
 
     @Override
@@ -94,7 +91,7 @@
     @Override
     public void enableAndResetCache() {
         synchronized (this) {
-            mUsers = new LongArrayMap<>();
+            mUsers = new LongSparseArray<>();
             mUserToSerialMap = new ArrayMap<>();
             List<UserHandle> users = mUserManager.getUserProfiles();
             if (users != null) {
diff --git a/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java b/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
index 5576d91..9f0d678 100644
--- a/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
+++ b/src/com/android/launcher3/dragndrop/FolderAdaptiveIcon.java
@@ -65,7 +65,7 @@
     }
 
     public static FolderAdaptiveIcon createFolderAdaptiveIcon(
-            Launcher launcher, long folderId, Point dragViewSize) {
+            Launcher launcher, int folderId, Point dragViewSize) {
         Preconditions.assertNonUiThread();
         int margin = launcher.getResources()
                 .getDimensionPixelSize(R.dimen.blur_size_medium_outline);
diff --git a/src/com/android/launcher3/icons/IconCacheUpdateHandler.java b/src/com/android/launcher3/icons/IconCacheUpdateHandler.java
index 8b3af01..07451b9 100644
--- a/src/com/android/launcher3/icons/IconCacheUpdateHandler.java
+++ b/src/com/android/launcher3/icons/IconCacheUpdateHandler.java
@@ -29,6 +29,7 @@
 
 import com.android.launcher3.Utilities;
 import com.android.launcher3.icons.BaseIconCache.IconDB;
+import com.android.launcher3.util.IntArray;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -205,7 +206,7 @@
 
     public void finish() {
         // Commit all deletes
-        ArrayList<Integer> deleteIds = new ArrayList<>();
+        IntArray deleteIds = new IntArray();
         int count = mItemsToDelete.size();
         for (int i = 0;  i < count; i++) {
             if (mItemsToDelete.valueAt(i)) {
diff --git a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
index fefe07d..756d44e 100644
--- a/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
+++ b/src/com/android/launcher3/model/AddWorkspaceItemsTask.java
@@ -34,6 +34,8 @@
 import com.android.launcher3.ShortcutInfo;
 import com.android.launcher3.Utilities;
 import com.android.launcher3.util.GridOccupancy;
+import com.android.launcher3.util.IntArray;
+
 import java.util.ArrayList;
 import java.util.List;
 
@@ -59,12 +61,12 @@
         Context context = app.getContext();
 
         final ArrayList<ItemInfo> addedItemsFinal = new ArrayList<>();
-        final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<>();
+        final IntArray addedWorkspaceScreensFinal = new IntArray();
 
         // Get the list of workspace screens.  We need to append to this list and
         // can not use sBgWorkspaceScreens because loadWorkspace() may not have been
         // called.
-        ArrayList<Long> workspaceScreens = LauncherModel.loadWorkspaceScreensDb(context);
+        IntArray workspaceScreens = LauncherModel.loadWorkspaceScreensDb(context);
         synchronized(dataModel) {
 
             List<ItemInfo> filteredItems = new ArrayList<>();
@@ -90,10 +92,9 @@
 
             for (ItemInfo item : filteredItems) {
                 // Find appropriate space for the item.
-                Pair<Long, int[]> coords = findSpaceForItem(app, dataModel, workspaceScreens,
+                int[] coords = findSpaceForItem(app, dataModel, workspaceScreens,
                         addedWorkspaceScreensFinal, item.spanX, item.spanY);
-                long screenId = coords.first;
-                int[] cordinates = coords.second;
+                int screenId = coords[0];
 
                 ItemInfo itemInfo;
                 if (item instanceof ShortcutInfo || item instanceof FolderInfo ||
@@ -108,7 +109,7 @@
                 // Add the shortcut to the db
                 getModelWriter().addItemToDatabase(itemInfo,
                         LauncherSettings.Favorites.CONTAINER_DESKTOP, screenId,
-                        cordinates[0], cordinates[1]);
+                        coords[1], coords[2]);
 
                 // Save the ShortcutInfo for binding in the workspace
                 addedItemsFinal.add(itemInfo);
@@ -126,7 +127,7 @@
                     final ArrayList<ItemInfo> addNotAnimated = new ArrayList<>();
                     if (!addedItemsFinal.isEmpty()) {
                         ItemInfo info = addedItemsFinal.get(addedItemsFinal.size() - 1);
-                        long lastScreenId = info.screenId;
+                        int lastScreenId = info.screenId;
                         for (ItemInfo i : addedItemsFinal) {
                             if (i.screenId == lastScreenId) {
                                 addAnimated.add(i);
@@ -142,7 +143,7 @@
         }
     }
 
-    protected void updateScreens(Context context, ArrayList<Long> workspaceScreens) {
+    protected void updateScreens(Context context, IntArray workspaceScreens) {
         LauncherModel.updateWorkspaceScreenOrder(context, workspaceScreens);
     }
 
@@ -204,13 +205,10 @@
 
     /**
      * Find a position on the screen for the given size or adds a new screen.
-     * @return screenId and the coordinates for the item.
+     * @return screenId and the coordinates for the item in an int array of size 3.
      */
-    protected Pair<Long, int[]> findSpaceForItem(
-            LauncherAppState app, BgDataModel dataModel,
-            ArrayList<Long> workspaceScreens,
-            ArrayList<Long> addedWorkspaceScreensFinal,
-            int spanX, int spanY) {
+    protected int[] findSpaceForItem( LauncherAppState app, BgDataModel dataModel,
+            IntArray workspaceScreens, IntArray addedWorkspaceScreensFinal, int spanX, int spanY) {
         LongSparseArray<ArrayList<ItemInfo>> screenItems = new LongSparseArray<>();
 
         // Use sBgItemsIdMap as all the items are already loaded.
@@ -228,7 +226,7 @@
         }
 
         // Find appropriate space for the item.
-        long screenId = 0;
+        int screenId = 0;
         int[] cordinates = new int[2];
         boolean found = false;
 
@@ -258,7 +256,7 @@
             // Still no position found. Add a new screen to the end.
             screenId = LauncherSettings.Settings.call(app.getContext().getContentResolver(),
                     LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
-                    .getLong(LauncherSettings.Settings.EXTRA_VALUE);
+                    .getInt(LauncherSettings.Settings.EXTRA_VALUE);
 
             // Save the screen id for binding in the workspace
             workspaceScreens.add(screenId);
@@ -270,7 +268,7 @@
                 throw new RuntimeException("Can't find space to add the item");
             }
         }
-        return Pair.create(screenId, cordinates);
+        return new int[] {screenId, cordinates[0], cordinates[1]};
     }
 
     private boolean findNextAvailableIconSpaceInScreen(
diff --git a/src/com/android/launcher3/model/BgDataModel.java b/src/com/android/launcher3/model/BgDataModel.java
index fff1e69..81eefc4 100644
--- a/src/com/android/launcher3/model/BgDataModel.java
+++ b/src/com/android/launcher3/model/BgDataModel.java
@@ -36,7 +36,8 @@
 import com.android.launcher3.shortcuts.ShortcutInfoCompat;
 import com.android.launcher3.shortcuts.ShortcutKey;
 import com.android.launcher3.util.ComponentKey;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
 import com.android.launcher3.util.MultiHashMap;
 import com.google.protobuf.nano.MessageNano;
 
@@ -62,7 +63,7 @@
      * Map of all the ItemInfos (shortcuts, folders, and widgets) created by
      * LauncherModel to their ids
      */
-    public final LongArrayMap<ItemInfo> itemsIdMap = new LongArrayMap<>();
+    public final IntSparseArrayMap<ItemInfo> itemsIdMap = new IntSparseArrayMap<>();
 
     /**
      * List of all the folders and shortcuts directly on the home screen (no widgets
@@ -78,12 +79,12 @@
     /**
      * Map of id to FolderInfos of all the folders created by LauncherModel
      */
-    public final LongArrayMap<FolderInfo> folders = new LongArrayMap<>();
+    public final IntSparseArrayMap<FolderInfo> folders = new IntSparseArrayMap<>();
 
     /**
      * Ordered list of workspace screens ids.
      */
-    public final ArrayList<Long> workspaceScreens = new ArrayList<>();
+    public final IntArray workspaceScreens = new IntArray();
 
     /**
      * Map of ShortcutKey to the number of times it is pinned.
@@ -132,7 +133,7 @@
         writer.println(prefix + "Data Model:");
         writer.print(prefix + " ---- workspace screens: ");
         for (int i = 0; i < workspaceScreens.size(); i++) {
-            writer.print(" " + workspaceScreens.get(i).toString());
+            writer.print(" " + workspaceScreens.get(i));
         }
         writer.println();
         writer.println(prefix + " ---- workspace items ");
@@ -169,7 +170,7 @@
 
         // Add top parent nodes. (L1)
         DumpTargetWrapper hotseat = new DumpTargetWrapper(ContainerType.HOTSEAT, 0);
-        LongArrayMap<DumpTargetWrapper> workspaces = new LongArrayMap<>();
+        IntSparseArrayMap<DumpTargetWrapper> workspaces = new IntSparseArrayMap<>();
         for (int i = 0; i < workspaceScreens.size(); i++) {
             workspaces.put(workspaceScreens.get(i),
                     new DumpTargetWrapper(ContainerType.WORKSPACE, i));
@@ -346,7 +347,7 @@
      * Return an existing FolderInfo object if we have encountered this ID previously,
      * or make a new one.
      */
-    public synchronized FolderInfo findOrMakeFolder(long id) {
+    public synchronized FolderInfo findOrMakeFolder(int id) {
         // See if a placeholder was created for us already
         FolderInfo folderInfo = folders.get(id);
         if (folderInfo == null) {
diff --git a/src/com/android/launcher3/model/GridSizeMigrationTask.java b/src/com/android/launcher3/model/GridSizeMigrationTask.java
index fc3ca76..0115fd9 100644
--- a/src/com/android/launcher3/model/GridSizeMigrationTask.java
+++ b/src/com/android/launcher3/model/GridSizeMigrationTask.java
@@ -11,7 +11,6 @@
 import android.database.Cursor;
 import android.graphics.Point;
 import android.net.Uri;
-import android.text.TextUtils;
 import android.util.Log;
 import com.android.launcher3.InvariantDeviceProfile;
 import com.android.launcher3.ItemInfo;
@@ -27,7 +26,9 @@
 import com.android.launcher3.compat.PackageInstallerCompat;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.util.GridOccupancy;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
@@ -59,7 +60,7 @@
     private final InvariantDeviceProfile mIdp;
 
     private final ContentValues mTempValues = new ContentValues();
-    protected final ArrayList<Long> mEntryToRemove = new ArrayList<>();
+    protected final IntArray mEntryToRemove = new IntArray();
     private final ArrayList<ContentProviderOperation> mUpdateOperations = new ArrayList<>();
     protected final ArrayList<DbEntry> mCarryOver = new ArrayList<>();
     private final HashSet<String> mValidPackages;
@@ -118,7 +119,7 @@
 
         if (!mEntryToRemove.isEmpty()) {
             if (DEBUG) {
-                Log.d(TAG, "Removing items: " + TextUtils.join(", ", mEntryToRemove));
+                Log.d(TAG, "Removing items: " + mEntryToRemove.toConcatString());
             }
             mContext.getContentResolver().delete(LauncherSettings.Favorites.CONTENT_URI,
                     Utilities.createDbSelectionQuery(
@@ -177,12 +178,13 @@
      * @return true if any DB change was made
      */
     protected boolean migrateWorkspace() throws Exception {
-        ArrayList<Long> allScreens = LauncherModel.loadWorkspaceScreensDb(mContext);
+        IntArray allScreens = LauncherModel.loadWorkspaceScreensDb(mContext);
         if (allScreens.isEmpty()) {
             throw new Exception("Unable to get workspace screens");
         }
 
-        for (long screenId : allScreens) {
+        for (int i = 0; i < allScreens.size(); i++) {
+            int screenId = allScreens.get(i);
             if (DEBUG) {
                 Log.d(TAG, "Migrating " + screenId);
             }
@@ -190,7 +192,7 @@
         }
 
         if (!mCarryOver.isEmpty()) {
-            LongArrayMap<DbEntry> itemMap = new LongArrayMap<>();
+            IntSparseArrayMap<DbEntry> itemMap = new IntSparseArrayMap<>();
             for (DbEntry e : mCarryOver) {
                 itemMap.put(e.id, e);
             }
@@ -205,10 +207,10 @@
                         new GridOccupancy(mTrgX, mTrgY), deepCopy(mCarryOver), 0, true);
                 placement.find();
                 if (placement.finalPlacedItems.size() > 0) {
-                    long newScreenId = LauncherSettings.Settings.call(
+                    int newScreenId = LauncherSettings.Settings.call(
                             mContext.getContentResolver(),
                             LauncherSettings.Settings.METHOD_NEW_SCREEN_ID)
-                            .getLong(LauncherSettings.Settings.EXTRA_VALUE);
+                            .getInt(LauncherSettings.Settings.EXTRA_VALUE);
 
                     allScreens.add(newScreenId);
                     for (DbEntry item : placement.finalPlacedItems) {
@@ -230,7 +232,7 @@
             int count = allScreens.size();
             for (int i = 0; i < count; i++) {
                 ContentValues v = new ContentValues();
-                long screenId = allScreens.get(i);
+                int screenId = allScreens.get(i);
                 v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
                 v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
                 mUpdateOperations.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
@@ -249,7 +251,7 @@
      *   3) If all those items from the above list can be placed on this screen, place them
      *      (otherwise they are placed on a new screen).
      */
-    protected void migrateScreen(long screenId) {
+    protected void migrateScreen(int screenId) {
         // If we are migrating the first screen, do not touch the first row.
         int startY =
                 (FeatureFlags.getInstance(mContext).isQsbOnFirstScreenEnabled()
@@ -304,7 +306,7 @@
                     removedRow, removedCol, screenId));
         }
 
-        LongArrayMap<DbEntry> itemMap = new LongArrayMap<>();
+        IntSparseArrayMap<DbEntry> itemMap = new IntSparseArrayMap<>();
         for (DbEntry e : deepCopy(items)) {
             itemMap.put(e.id, e);
         }
@@ -615,9 +617,9 @@
         ArrayList<DbEntry> entries = new ArrayList<>();
         while (c.moveToNext()) {
             DbEntry entry = new DbEntry();
-            entry.id = c.getLong(indexId);
+            entry.id = c.getInt(indexId);
             entry.itemType = c.getInt(indexItemType);
-            entry.screenId = c.getLong(indexScreen);
+            entry.screenId = c.getInt(indexScreen);
 
             if (entry.screenId >= mSrcHotseatSize) {
                 mEntryToRemove.add(entry.id);
@@ -663,7 +665,7 @@
     /**
      * Loads entries for a particular screen id.
      */
-    protected ArrayList<DbEntry> loadWorkspaceEntries(long screen) {
+    protected ArrayList<DbEntry> loadWorkspaceEntries(int screen) {
         Cursor c = queryWorkspace(
                 new String[]{
                         Favorites._ID,                  // 0
@@ -691,7 +693,7 @@
         ArrayList<DbEntry> entries = new ArrayList<>();
         while (c.moveToNext()) {
             DbEntry entry = new DbEntry();
-            entry.id = c.getLong(indexId);
+            entry.id = c.getInt(indexId);
             entry.itemType = c.getInt(indexItemType);
             entry.cellX = c.getInt(indexCellX);
             entry.cellY = c.getInt(indexCellY);
@@ -764,7 +766,7 @@
     /**
      * @return the number of valid items in the folder.
      */
-    private int getFolderItemsCount(long folderId) {
+    private int getFolderItemsCount(int folderId) {
         Cursor c = queryWorkspace(
                 new String[]{Favorites._ID, Favorites.INTENT},
                 Favorites.CONTAINER + " = " + folderId);
@@ -775,7 +777,7 @@
                 verifyIntent(c.getString(1));
                 total++;
             } catch (Exception e) {
-                mEntryToRemove.add(c.getLong(0));
+                mEntryToRemove.add(c.getInt(0));
             }
         }
         c.close();
@@ -970,7 +972,7 @@
      * Removes any broken item from the hotseat.
      * @return a map with occupied hotseat position set to non-null value.
      */
-    public static LongArrayMap<Object> removeBrokenHotseatItems(Context context) throws Exception {
+    public static IntSparseArrayMap<Object> removeBrokenHotseatItems(Context context) throws Exception {
         GridSizeMigrationTask task = new GridSizeMigrationTask(
                 context, LauncherAppState.getIDP(context), getValidPackages(context),
                 Integer.MAX_VALUE, Integer.MAX_VALUE);
@@ -979,7 +981,7 @@
         ArrayList<DbEntry> items = task.loadHotseatEntries();
         // Delete any entry marked for deletion by above load.
         task.applyOperations();
-        LongArrayMap<Object> positions = new LongArrayMap<>();
+        IntSparseArrayMap<Object> positions = new IntSparseArrayMap<>();
         for (DbEntry item : items) {
             positions.put(item.screenId, item);
         }
diff --git a/src/com/android/launcher3/model/LoaderCursor.java b/src/com/android/launcher3/model/LoaderCursor.java
index 958e1de..bb3a760 100644
--- a/src/com/android/launcher3/model/LoaderCursor.java
+++ b/src/com/android/launcher3/model/LoaderCursor.java
@@ -48,11 +48,11 @@
 import com.android.launcher3.logging.FileLog;
 import com.android.launcher3.util.ContentWriter;
 import com.android.launcher3.util.GridOccupancy;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
 
 import java.net.URISyntaxException;
 import java.security.InvalidParameterException;
-import java.util.ArrayList;
 
 /**
  * Extension of {@link Cursor} with utility methods for workspace loading.
@@ -68,9 +68,9 @@
     private final IconCache mIconCache;
     private final InvariantDeviceProfile mIDP;
 
-    private final ArrayList<Long> itemsToRemove = new ArrayList<>();
-    private final ArrayList<Long> restoredRows = new ArrayList<>();
-    private final LongArrayMap<GridOccupancy> occupied = new LongArrayMap<>();
+    private final IntArray itemsToRemove = new IntArray();
+    private final IntArray restoredRows = new IntArray();
+    private final IntSparseArrayMap<GridOccupancy> occupied = new IntSparseArrayMap<>();
 
     private final int iconPackageIndex;
     private final int iconResourceIndex;
@@ -90,8 +90,8 @@
     // Properties loaded per iteration
     public long serialNumber;
     public UserHandle user;
-    public long id;
-    public long container;
+    public int id;
+    public int container;
     public int itemType;
     public int restoreFlag;
 
@@ -126,7 +126,7 @@
             // Load common properties.
             itemType = getInt(itemTypeIndex);
             container = getInt(containerIndex);
-            id = getLong(idIndex);
+            id = getInt(idIndex);
             serialNumber = getInt(profileIdIndex);
             user = allUsers.get(serialNumber);
             restoreFlag = getInt(restoredIndex);
@@ -293,7 +293,7 @@
      */
     public ContentWriter updater() {
        return new ContentWriter(mContext, new ContentWriter.CommitParams(
-               BaseColumns._ID + "= ?", new String[]{Long.toString(id)}));
+               BaseColumns._ID + "= ?", new String[]{Integer.toString(id)}));
     }
 
     /**
@@ -383,11 +383,11 @@
     /**
      * check & update map of what's occupied; used to discard overlapping/invalid items
      */
-    protected boolean checkItemPlacement(ItemInfo item, ArrayList<Long> workspaceScreens) {
-        long containerIndex = item.screenId;
+    protected boolean checkItemPlacement(ItemInfo item, IntArray workspaceScreens) {
+        int containerIndex = item.screenId;
         if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
             final GridOccupancy hotseatOccupancy =
-                    occupied.get((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT);
+                    occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT);
 
             if (item.screenId >= mIDP.numHotseatIcons) {
                 Log.e(TAG, "Error loading shortcut " + item
@@ -404,17 +404,17 @@
                             + item.cellY + ") already occupied");
                     return false;
                 } else {
-                    hotseatOccupancy.cells[(int) item.screenId][0] = true;
+                    hotseatOccupancy.cells[item.screenId][0] = true;
                     return true;
                 }
             } else {
                 final GridOccupancy occupancy = new GridOccupancy(mIDP.numHotseatIcons, 1);
-                occupancy.cells[(int) item.screenId][0] = true;
-                occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, occupancy);
+                occupancy.cells[item.screenId][0] = true;
+                occupied.put(LauncherSettings.Favorites.CONTAINER_HOTSEAT, occupancy);
                 return true;
             }
         } else if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
-            if (!workspaceScreens.contains((Long) item.screenId)) {
+            if (!workspaceScreens.contains(item.screenId)) {
                 // The item has an invalid screen id.
                 return false;
             }
diff --git a/src/com/android/launcher3/model/LoaderResults.java b/src/com/android/launcher3/model/LoaderResults.java
index 033e3f5..2c15df1 100644
--- a/src/com/android/launcher3/model/LoaderResults.java
+++ b/src/com/android/launcher3/model/LoaderResults.java
@@ -29,9 +29,10 @@
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.MainThreadExecutor;
 import com.android.launcher3.PagedView;
-import com.android.launcher3.Utilities;
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSet;
 import com.android.launcher3.util.LooperIdleLock;
 import com.android.launcher3.util.MultiHashMap;
 import com.android.launcher3.util.ViewOnDrawExecutor;
@@ -52,7 +53,7 @@
 public class LoaderResults {
 
     private static final String TAG = "LoaderResults";
-    private static final long INVALID_SCREEN_ID = -1L;
+    private static final int INVALID_SCREEN_ID = -1;
     private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons
 
     private final Executor mUiExecutor;
@@ -92,7 +93,7 @@
         // Save a copy of all the bg-thread collections
         ArrayList<ItemInfo> workspaceItems = new ArrayList<>();
         ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<>();
-        final ArrayList<Long> orderedScreenIds = new ArrayList<>();
+        final IntArray orderedScreenIds = new IntArray();
 
         synchronized (mBgDataModel) {
             workspaceItems.addAll(mBgDataModel.workspaceItems);
@@ -112,7 +113,7 @@
             currentScreen = currScreen;
         }
         final boolean validFirstPage = currentScreen >= 0;
-        final long currentScreenId =
+        final int currentScreenId =
                 validFirstPage ? orderedScreenIds.get(currentScreen) : INVALID_SCREEN_ID;
 
         // Separate the items that are on the current screen, and all the other remaining items
@@ -209,7 +210,7 @@
 
     /** Filters the set of items who are directly or indirectly (via another container) on the
      * specified screen. */
-    public static <T extends ItemInfo> void filterCurrentWorkspaceItems(long currentScreenId,
+    public static <T extends ItemInfo> void filterCurrentWorkspaceItems(int currentScreenId,
             ArrayList<T> allWorkspaceItems,
             ArrayList<T> currentScreenItems,
             ArrayList<T> otherScreenItems) {
@@ -225,13 +226,10 @@
         // Order the set of items by their containers first, this allows use to walk through the
         // list sequentially, build up a list of containers that are in the specified screen,
         // as well as all items in those containers.
-        Set<Long> itemsOnScreen = new HashSet<>();
-        Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() {
-            @Override
-            public int compare(ItemInfo lhs, ItemInfo rhs) {
-                return Utilities.longCompare(lhs.container, rhs.container);
-            }
-        });
+        IntSet itemsOnScreen = new IntSet();
+        Collections.sort(allWorkspaceItems,
+                (lhs, rhs) -> Integer.compare(lhs.container, rhs.container));
+
         for (T info : allWorkspaceItems) {
             if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
                 if (info.screenId == currentScreenId) {
@@ -267,15 +265,15 @@
                     // Within containers, order by their spatial position in that container
                     switch ((int) lhs.container) {
                         case LauncherSettings.Favorites.CONTAINER_DESKTOP: {
-                            long lr = (lhs.screenId * screenCellCount +
+                            int lr = (lhs.screenId * screenCellCount +
                                     lhs.cellY * screenCols + lhs.cellX);
-                            long rr = (rhs.screenId * screenCellCount +
+                            int rr = (rhs.screenId * screenCellCount +
                                     rhs.cellY * screenCols + rhs.cellX);
-                            return Utilities.longCompare(lr, rr);
+                            return Integer.compare(lr, rr);
                         }
                         case LauncherSettings.Favorites.CONTAINER_HOTSEAT: {
                             // We currently use the screen id as the rank
-                            return Utilities.longCompare(lhs.screenId, rhs.screenId);
+                            return Integer.compare(lhs.screenId, rhs.screenId);
                         }
                         default:
                             if (FeatureFlags.IS_DOGFOOD_BUILD) {
@@ -286,7 +284,7 @@
                     }
                 } else {
                     // Between containers, order by hotseat, desktop
-                    return Utilities.longCompare(lhs.container, rhs.container);
+                    return Integer.compare(lhs.container, rhs.container);
                 }
             }
         });
diff --git a/src/com/android/launcher3/model/LoaderTask.java b/src/com/android/launcher3/model/LoaderTask.java
index cb78038..1ec7af2 100644
--- a/src/com/android/launcher3/model/LoaderTask.java
+++ b/src/com/android/launcher3/model/LoaderTask.java
@@ -70,6 +70,7 @@
 import com.android.launcher3.shortcuts.ShortcutInfoCompat;
 import com.android.launcher3.shortcuts.ShortcutKey;
 import com.android.launcher3.util.ComponentKey;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.LooperIdleLock;
 import com.android.launcher3.util.MultiHashMap;
 import com.android.launcher3.util.PackageManagerHelper;
@@ -155,7 +156,7 @@
             allItems.addAll(mBgDataModel.workspaceItems);
             allItems.addAll(mBgDataModel.appWidgets);
         }
-        long firstScreen = mBgDataModel.workspaceScreens.isEmpty()
+        int firstScreen = mBgDataModel.workspaceScreens.isEmpty()
                 ? -1 // In this case, we can still look at the items in the hotseat.
                 : mBgDataModel.workspaceScreens.get(0);
         filterCurrentWorkspaceItems(firstScreen, allItems, firstScreenItems,
@@ -719,11 +720,11 @@
             // Remove dead items
             if (c.commitDeleted()) {
                 // Remove any empty folder
-                ArrayList<Long> deletedFolderIds = (ArrayList<Long>) LauncherSettings.Settings
+                int[] deletedFolderIds = LauncherSettings.Settings
                         .call(contentResolver,
                                 LauncherSettings.Settings.METHOD_DELETE_EMPTY_FOLDERS)
-                        .getSerializable(LauncherSettings.Settings.EXTRA_VALUE);
-                for (long folderId : deletedFolderIds) {
+                        .getIntArray(LauncherSettings.Settings.EXTRA_VALUE);
+                for (int folderId : deletedFolderIds) {
                     mBgDataModel.workspaceItems.remove(mBgDataModel.folders.get(folderId));
                     mBgDataModel.folders.remove(folderId);
                     mBgDataModel.itemsIdMap.remove(folderId);
@@ -778,18 +779,18 @@
             }
 
             // Remove any empty screens
-            ArrayList<Long> unusedScreens = new ArrayList<>(mBgDataModel.workspaceScreens);
+            IntArray unusedScreens = mBgDataModel.workspaceScreens.clone();
             for (ItemInfo item: mBgDataModel.itemsIdMap) {
-                long screenId = item.screenId;
+                int screenId = item.screenId;
                 if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP &&
                         unusedScreens.contains(screenId)) {
-                    unusedScreens.remove(screenId);
+                    unusedScreens.removeValue(screenId);
                 }
             }
 
             // If there are any empty screens remove them, and update.
             if (unusedScreens.size() != 0) {
-                mBgDataModel.workspaceScreens.removeAll(unusedScreens);
+                mBgDataModel.workspaceScreens.removeAllValues(unusedScreens);
                 LauncherModel.updateWorkspaceScreenOrder(context, mBgDataModel.workspaceScreens);
             }
         }
diff --git a/src/com/android/launcher3/model/ModelWriter.java b/src/com/android/launcher3/model/ModelWriter.java
index d81eb43..f7961d5d 100644
--- a/src/com/android/launcher3/model/ModelWriter.java
+++ b/src/com/android/launcher3/model/ModelWriter.java
@@ -79,7 +79,7 @@
     }
 
     private void updateItemInfoProps(
-            ItemInfo item, long container, long screenId, int cellX, int cellY) {
+            ItemInfo item, int container, int screenId, int cellX, int cellY) {
         item.container = container;
         item.cellX = cellX;
         item.cellY = cellY;
@@ -98,7 +98,7 @@
      * <container, screen, cellX, cellY>
      */
     public void addOrMoveItemInDatabase(ItemInfo item,
-            long container, long screenId, int cellX, int cellY) {
+            int container, int screenId, int cellX, int cellY) {
         if (item.container == ItemInfo.NO_ID) {
             // From all apps
             addItemToDatabase(item, container, screenId, cellX, cellY);
@@ -108,7 +108,7 @@
         }
     }
 
-    private void checkItemInfoLocked(long itemId, ItemInfo item, StackTraceElement[] stackTrace) {
+    private void checkItemInfoLocked(int itemId, ItemInfo item, StackTraceElement[] stackTrace) {
         if (com.android.launcher3.Utilities.IS_RUNNING_IN_TEST_HARNESS
                 && com.android.launcher3.Utilities.IS_DEBUG_DEVICE) {
             android.util.Log.d("b/117332845",
@@ -154,7 +154,7 @@
      * Move an item in the DB to a new <container, screen, cellX, cellY>
      */
     public void moveItemInDatabase(final ItemInfo item,
-            long container, long screenId, int cellX, int cellY) {
+            int container, int screenId, int cellX, int cellY) {
         updateItemInfoProps(item, container, screenId, cellX, cellY);
 
         final ContentWriter writer = new ContentWriter(mContext)
@@ -171,7 +171,7 @@
      * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the
      * cellX, cellY have already been updated on the ItemInfos.
      */
-    public void moveItemsInDatabase(final ArrayList<ItemInfo> items, long container, int screen) {
+    public void moveItemsInDatabase(final ArrayList<ItemInfo> items, int container, int screen) {
         ArrayList<ContentValues> contentValues = new ArrayList<>();
         int count = items.size();
 
@@ -195,7 +195,7 @@
      * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY>
      */
     public void modifyItemInDatabase(final ItemInfo item,
-            long container, long screenId, int cellX, int cellY, int spanX, int spanY) {
+            int container, int screenId, int cellX, int cellY, int spanX, int spanY) {
         updateItemInfoProps(item, container, screenId, cellX, cellY);
         item.spanX = spanX;
         item.spanY = spanY;
@@ -226,14 +226,14 @@
      * cellY fields of the item. Also assigns an ID to the item.
      */
     public void addItemToDatabase(final ItemInfo item,
-            long container, long screenId, int cellX, int cellY) {
+            int container, int screenId, int cellX, int cellY) {
         updateItemInfoProps(item, container, screenId, cellX, cellY);
 
         final ContentWriter writer = new ContentWriter(mContext);
         final ContentResolver cr = mContext.getContentResolver();
         item.onAddToDatabase(writer);
 
-        item.id = Settings.call(cr, Settings.METHOD_NEW_ITEM_ID).getLong(Settings.EXTRA_VALUE);
+        item.id = Settings.call(cr, Settings.METHOD_NEW_ITEM_ID).getInt(Settings.EXTRA_VALUE);
         writer.put(Favorites._ID, item.id);
 
         ModelVerifier verifier = new ModelVerifier();
@@ -360,7 +360,7 @@
     private class UpdateItemRunnable extends UpdateItemBaseRunnable {
         private final ItemInfo mItem;
         private final ContentWriter mWriter;
-        private final long mItemId;
+        private final int mItemId;
 
         UpdateItemRunnable(ItemInfo item, ContentWriter writer) {
             if (com.android.launcher3.Utilities.IS_RUNNING_IN_TEST_HARNESS
@@ -396,7 +396,7 @@
             int count = mItems.size();
             for (int i = 0; i < count; i++) {
                 ItemInfo item = mItems.get(i);
-                final long itemId = item.id;
+                final int itemId = item.id;
                 final Uri uri = Favorites.getContentUri(itemId);
                 ContentValues values = mValues.get(i);
 
@@ -419,7 +419,7 @@
             mStackTrace = new Throwable().getStackTrace();
         }
 
-        protected void updateItemArrays(ItemInfo item, long itemId) {
+        protected void updateItemArrays(ItemInfo item, int itemId) {
             // Lock on mBgLock *after* the db operation
             synchronized (mBgDataModel) {
                 checkItemInfoLocked(itemId, item, mStackTrace);
diff --git a/src/com/android/launcher3/model/PackageUpdatedTask.java b/src/com/android/launcher3/model/PackageUpdatedTask.java
index c004e21..201a63e 100644
--- a/src/com/android/launcher3/model/PackageUpdatedTask.java
+++ b/src/com/android/launcher3/model/PackageUpdatedTask.java
@@ -44,8 +44,8 @@
 import com.android.launcher3.shortcuts.DeepShortcutManager;
 import com.android.launcher3.shortcuts.ShortcutInfoCompat;
 import com.android.launcher3.util.FlagOp;
+import com.android.launcher3.util.IntSparseArrayMap;
 import com.android.launcher3.util.ItemInfoMatcher;
-import com.android.launcher3.util.LongArrayMap;
 import com.android.launcher3.util.PackageManagerHelper;
 import com.android.launcher3.util.PackageUserKey;
 
@@ -171,7 +171,7 @@
             }
         }
 
-        final LongArrayMap<Boolean> removedShortcuts = new LongArrayMap<>();
+        final IntSparseArrayMap<Boolean> removedShortcuts = new IntSparseArrayMap<>();
 
         // Update shortcut infos
         if (mOp == OP_ADD || flagOp != FlagOp.NO_OP) {
diff --git a/src/com/android/launcher3/notification/NotificationListener.java b/src/com/android/launcher3/notification/NotificationListener.java
index 4c85c8b..68cf7de 100644
--- a/src/com/android/launcher3/notification/NotificationListener.java
+++ b/src/com/android/launcher3/notification/NotificationListener.java
@@ -33,6 +33,7 @@
 import android.util.Pair;
 
 import com.android.launcher3.LauncherModel;
+import com.android.launcher3.util.IntSet;
 import com.android.launcher3.util.PackageUserKey;
 import com.android.launcher3.util.SettingsObserver;
 
@@ -346,7 +347,7 @@
     private List<StatusBarNotification> filterNotifications(
             StatusBarNotification[] notifications) {
         if (notifications == null) return null;
-        Set<Integer> removedNotifications = new ArraySet<>();
+        IntSet removedNotifications = new IntSet();
         for (int i = 0; i < notifications.length; i++) {
             if (shouldBeFilteredOut(notifications[i])) {
                 removedNotifications.add(i);
diff --git a/src/com/android/launcher3/provider/ImportDataTask.java b/src/com/android/launcher3/provider/ImportDataTask.java
index 59c3c72..4edd30f 100644
--- a/src/com/android/launcher3/provider/ImportDataTask.java
+++ b/src/com/android/launcher3/provider/ImportDataTask.java
@@ -32,8 +32,9 @@
 import android.os.Process;
 import android.text.TextUtils;
 import android.util.ArrayMap;
-import android.util.LongSparseArray;
 import android.util.SparseBooleanArray;
+import android.util.SparseIntArray;
+
 import com.android.launcher3.AutoInstallsLayout.LayoutParserCallback;
 import com.android.launcher3.DefaultLayoutParser;
 import com.android.launcher3.LauncherAppState;
@@ -50,7 +51,9 @@
 import com.android.launcher3.config.FeatureFlags;
 import com.android.launcher3.logging.FileLog;
 import com.android.launcher3.model.GridSizeMigrationTask;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
+
 import java.net.URISyntaxException;
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -85,7 +88,7 @@
     }
 
     public boolean importWorkspace() throws Exception {
-        ArrayList<Long> allScreens = LauncherDbUtils.getScreenIdsFromCursor(
+        IntArray allScreens = LauncherDbUtils.getScreenIdsFromCursor(
                 mContext.getContentResolver().query(mOtherScreensUri, null, null, null,
                         LauncherSettings.WorkspaceScreens.SCREEN_RANK));
         FileLog.d(TAG, "Importing DB from " + mOtherFavoritesUri);
@@ -102,12 +105,12 @@
         // Build screen update
         ArrayList<ContentProviderOperation> screenOps = new ArrayList<>();
         int count = allScreens.size();
-        LongSparseArray<Long> screenIdMap = new LongSparseArray<>(count);
+        SparseIntArray screenIdMap = new SparseIntArray(count);
         for (int i = 0; i < count; i++) {
             ContentValues v = new ContentValues();
             v.put(LauncherSettings.WorkspaceScreens._ID, i);
             v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
-            screenIdMap.put(allScreens.get(i), (long) i);
+            screenIdMap.put(allScreens.get(i), i);
             screenOps.add(ContentProviderOperation.newInsert(
                     LauncherSettings.WorkspaceScreens.CONTENT_URI).withValues(v).build());
         }
@@ -128,7 +131,7 @@
      * 3) In the end fills any holes in hotseat with items from default hotseat layout.
      */
     private void importWorkspaceItems(
-            long firsetScreenId, LongSparseArray<Long> screenIdMap) throws Exception {
+            int firstScreenId, SparseIntArray screenIdMap) throws Exception {
         String profileId = Long.toString(UserManagerCompat.getInstance(mContext)
                 .getSerialNumberForUser(Process.myUserHandle()));
 
@@ -137,7 +140,7 @@
             try (Cursor c = mContext.getContentResolver().query(mOtherFavoritesUri, null,
                     // get items on the first row of the first screen
                     "profileId = ? AND container = -100 AND screen = ? AND cellY = 0",
-                    new String[]{profileId, Long.toString(firsetScreenId)},
+                    new String[]{profileId, Integer.toString(firstScreenId)},
                     null)) {
                 // First row of first screen is not empty
                 createEmptyRowOnFirstScreen = c.moveToNext();
@@ -190,7 +193,7 @@
                 int type = c.getInt(itemTypeIndex);
                 int container = c.getInt(containerIndex);
 
-                long screen = c.getLong(screenIndex);
+                int screen = c.getInt(screenIndex);
 
                 int cellX = c.getInt(cellXIndex);
                 int cellY = c.getInt(cellYIndex);
@@ -199,7 +202,7 @@
 
                 switch (container) {
                     case Favorites.CONTAINER_DESKTOP: {
-                        Long newScreenId = screenIdMap.get(screen);
+                        Integer newScreenId = screenIdMap.get(screen);
                         if (newScreenId == null) {
                             FileLog.d(TAG, String.format("Skipping item %d, type %d not on a valid screen %d", id, type, screen));
                             continue;
@@ -306,15 +309,15 @@
             insertOperations.clear();
         }
 
-        LongArrayMap<Object> hotseatItems = GridSizeMigrationTask.removeBrokenHotseatItems(mContext);
+        IntSparseArrayMap<Object> hotseatItems = GridSizeMigrationTask.removeBrokenHotseatItems(mContext);
         int myHotseatCount = LauncherAppState.getIDP(mContext).numHotseatIcons;
         if (hotseatItems.size() < myHotseatCount) {
             // Insufficient hotseat items. Add a few more.
             HotseatParserCallback parserCallback = new HotseatParserCallback(
                     hotseatTargetApps, hotseatItems, insertOperations, maxId + 1, myHotseatCount);
             new HotseatLayoutParser(mContext,
-                    parserCallback).loadLayout(null, new ArrayList<Long>());
-            mHotseatSize = (int) hotseatItems.keyAt(hotseatItems.size() - 1) + 1;
+                    parserCallback).loadLayout(null, new IntArray());
+            mHotseatSize = hotseatItems.keyAt(hotseatItems.size() - 1) + 1;
 
             if (!insertOperations.isEmpty()) {
                 mContext.getContentResolver().applyBatch(LauncherProvider.AUTHORITY,
@@ -405,13 +408,13 @@
      */
     private static class HotseatParserCallback implements LayoutParserCallback {
         private final HashSet<String> mExistingApps;
-        private final LongArrayMap<Object> mExistingItems;
+        private final IntSparseArrayMap<Object> mExistingItems;
         private final ArrayList<ContentProviderOperation> mOutOps;
         private final int mRequiredSize;
         private int mStartItemId;
 
         HotseatParserCallback(
-                HashSet<String> existingApps, LongArrayMap<Object> existingItems,
+                HashSet<String> existingApps, IntSparseArrayMap<Object> existingItems,
                 ArrayList<ContentProviderOperation> outOps, int startItemId, int requiredSize) {
             mExistingApps = existingApps;
             mExistingItems = existingItems;
@@ -421,12 +424,12 @@
         }
 
         @Override
-        public long generateNewItemId() {
+        public int generateNewItemId() {
             return mStartItemId++;
         }
 
         @Override
-        public long insertAndCheck(SQLiteDatabase db, ContentValues values) {
+        public int insertAndCheck(SQLiteDatabase db, ContentValues values) {
             if (mExistingItems.size() >= mRequiredSize) {
                 // No need to add more items.
                 return 0;
@@ -445,7 +448,7 @@
             mExistingApps.add(pkg);
 
             // find next vacant spot.
-            long screen = 0;
+            int screen = 0;
             while (mExistingItems.get(screen) != null) {
                 screen++;
             }
diff --git a/src/com/android/launcher3/provider/LauncherDbUtils.java b/src/com/android/launcher3/provider/LauncherDbUtils.java
index 74373d3..ab0703f 100644
--- a/src/com/android/launcher3/provider/LauncherDbUtils.java
+++ b/src/com/android/launcher3/provider/LauncherDbUtils.java
@@ -26,6 +26,7 @@
 import com.android.launcher3.LauncherAppState;
 import com.android.launcher3.LauncherSettings.Favorites;
 import com.android.launcher3.LauncherSettings.WorkspaceScreens;
+import com.android.launcher3.util.IntArray;
 
 import java.util.ArrayList;
 import java.util.Collection;
@@ -47,7 +48,7 @@
     public static boolean prepareScreenZeroToHostQsb(Context context, SQLiteDatabase db) {
         try (SQLiteTransaction t = new SQLiteTransaction(db)) {
             // Get the existing screens
-            ArrayList<Long> screenIds = getScreenIdsFromCursor(db.query(WorkspaceScreens.TABLE_NAME,
+            IntArray screenIds = getScreenIdsFromCursor(db.query(WorkspaceScreens.TABLE_NAME,
                     null, null, null, null, null, WorkspaceScreens.SCREEN_RANK));
 
             if (screenIds.isEmpty()) {
@@ -57,10 +58,10 @@
             }
             if (screenIds.get(0) != 0) {
                 // First screen is not 0, we need to rename screens
-                if (screenIds.indexOf(0L) > -1) {
+                if (screenIds.contains(0)) {
                     // There is already a screen 0. First rename it to a different screen.
-                    long newScreenId = 1;
-                    while (screenIds.indexOf(newScreenId) > -1) newScreenId++;
+                    int newScreenId = 1;
+                    while (screenIds.contains(newScreenId)) newScreenId++;
                     renameScreen(db, 0, newScreenId);
                 }
 
@@ -86,8 +87,8 @@
         }
     }
 
-    private static void renameScreen(SQLiteDatabase db, long oldScreen, long newScreen) {
-        String[] whereParams = new String[] { Long.toString(oldScreen) };
+    private static void renameScreen(SQLiteDatabase db, int oldScreen, int newScreen) {
+        String[] whereParams = new String[] { Integer.toString(oldScreen) };
 
         ContentValues values = new ContentValues();
         values.put(WorkspaceScreens._ID, newScreen);
@@ -101,19 +102,18 @@
     /**
      * Parses the cursor containing workspace screens table and returns the list of screen IDs
      */
-    public static ArrayList<Long> getScreenIdsFromCursor(Cursor sc) {
+    public static IntArray getScreenIdsFromCursor(Cursor sc) {
         try {
             return iterateCursor(sc,
-                    sc.getColumnIndexOrThrow(WorkspaceScreens._ID),
-                    new ArrayList<Long>());
+                    sc.getColumnIndexOrThrow(WorkspaceScreens._ID), new IntArray());
         } finally {
             sc.close();
         }
     }
 
-    public static <T extends Collection<Long>> T iterateCursor(Cursor c, int columnIndex, T out) {
+    public static IntArray iterateCursor(Cursor c, int columnIndex, IntArray out) {
         while (c.moveToNext()) {
-            out.add(c.getLong(columnIndex));
+            out.add(c.getInt(columnIndex));
         }
         return out;
     }
diff --git a/src/com/android/launcher3/provider/LossyScreenMigrationTask.java b/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
index 51890d1..9166b83 100644
--- a/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
+++ b/src/com/android/launcher3/provider/LossyScreenMigrationTask.java
@@ -27,7 +27,7 @@
 import com.android.launcher3.Utilities;
 import com.android.launcher3.Workspace;
 import com.android.launcher3.model.GridSizeMigrationTask;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntSparseArrayMap;
 
 import java.util.ArrayList;
 
@@ -39,8 +39,8 @@
 
     private final SQLiteDatabase mDb;
 
-    private final LongArrayMap<DbEntry> mOriginalItems;
-    private final LongArrayMap<DbEntry> mUpdates;
+    private final IntSparseArrayMap<DbEntry> mOriginalItems;
+    private final IntSparseArrayMap<DbEntry> mUpdates;
 
     protected LossyScreenMigrationTask(
             Context context, InvariantDeviceProfile idp, SQLiteDatabase db) {
@@ -50,8 +50,8 @@
                 new Point(idp.numColumns, idp.numRows));
 
         mDb = db;
-        mOriginalItems = new LongArrayMap<>();
-        mUpdates = new LongArrayMap<>();
+        mOriginalItems = new IntSparseArrayMap<>();
+        mUpdates = new IntSparseArrayMap<>();
     }
 
     @Override
@@ -65,7 +65,7 @@
     }
 
     @Override
-    protected ArrayList<DbEntry> loadWorkspaceEntries(long screen) {
+    protected ArrayList<DbEntry> loadWorkspaceEntries(int screen) {
         ArrayList<DbEntry> result = super.loadWorkspaceEntries(screen);
         for (DbEntry entry : result) {
             mOriginalItems.put(entry.id, entry.copy());
@@ -90,7 +90,7 @@
                 tempValues.clear();
                 update.addToContentValues(tempValues);
                 mDb.update(Favorites.TABLE_NAME, tempValues, "_id = ?",
-                        new String[] {Long.toString(update.id)});
+                        new String[] {Integer.toString(update.id)});
             }
         }
 
diff --git a/src/com/android/launcher3/provider/RestoreDbTask.java b/src/com/android/launcher3/provider/RestoreDbTask.java
index 5230160..17c66b4 100644
--- a/src/com/android/launcher3/provider/RestoreDbTask.java
+++ b/src/com/android/launcher3/provider/RestoreDbTask.java
@@ -92,7 +92,7 @@
                 new String[]{Integer.toString(Favorites.ITEM_TYPE_APPWIDGET)});
 
         long myProfileId = helper.getDefaultUserSerial();
-        if (Utilities.longCompare(oldProfileId, myProfileId) != 0) {
+        if (myProfileId != oldProfileId) {
             FileLog.d(TAG, "Changing primary user id from " + oldProfileId + " to " + myProfileId);
             migrateProfileId(db, myProfileId);
         }
diff --git a/src/com/android/launcher3/util/IntArray.java b/src/com/android/launcher3/util/IntArray.java
new file mode 100644
index 0000000..b2fb32a
--- /dev/null
+++ b/src/com/android/launcher3/util/IntArray.java
@@ -0,0 +1,236 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.util;
+
+import java.util.Arrays;
+
+/**
+ * Copy of the platform hidden implementation of android.util.IntArray.
+ * Implements a growing array of int primitives.
+ */
+public class IntArray implements Cloneable {
+    private static final int MIN_CAPACITY_INCREMENT = 12;
+
+    private static final int[] EMPTY_INT = new int[0];
+
+    /* package private */ int[] mValues;
+    /* package private */ int mSize;
+
+    private  IntArray(int[] array, int size) {
+        mValues = array;
+        mSize = size;
+    }
+
+    /**
+     * Creates an empty IntArray with the default initial capacity.
+     */
+    public IntArray() {
+        this(10);
+    }
+
+    /**
+     * Creates an empty IntArray with the specified initial capacity.
+     */
+    public IntArray(int initialCapacity) {
+        if (initialCapacity == 0) {
+            mValues = EMPTY_INT;
+        } else {
+            mValues = new int[initialCapacity];
+        }
+        mSize = 0;
+    }
+
+    /**
+     * Creates an IntArray wrapping the given primitive int array.
+     */
+    public static IntArray wrap(int... array) {
+        return new IntArray(array, array.length);
+    }
+
+    /**
+     * Appends the specified value to the end of this array.
+     */
+    public void add(int value) {
+        add(mSize, value);
+    }
+
+    /**
+     * Inserts a value at the specified position in this array. If the specified index is equal to
+     * the length of the array, the value is added at the end.
+     *
+     * @throws IndexOutOfBoundsException when index &lt; 0 || index &gt; size()
+     */
+    public void add(int index, int value) {
+        ensureCapacity(1);
+        int rightSegment = mSize - index;
+        mSize++;
+        checkBounds(mSize, index);
+
+        if (rightSegment != 0) {
+            // Move by 1 all values from the right of 'index'
+            System.arraycopy(mValues, index, mValues, index + 1, rightSegment);
+        }
+
+        mValues[index] = value;
+    }
+
+    /**
+     * Adds the values in the specified array to this array.
+     */
+    public void addAll(IntArray values) {
+        final int count = values.mSize;
+        ensureCapacity(count);
+
+        System.arraycopy(values.mValues, 0, mValues, mSize, count);
+        mSize += count;
+    }
+
+    /**
+     * Ensures capacity to append at least <code>count</code> values.
+     */
+    private void ensureCapacity(int count) {
+        final int currentSize = mSize;
+        final int minCapacity = currentSize + count;
+        if (minCapacity >= mValues.length) {
+            final int targetCap = currentSize + (currentSize < (MIN_CAPACITY_INCREMENT / 2) ?
+                    MIN_CAPACITY_INCREMENT : currentSize >> 1);
+            final int newCapacity = targetCap > minCapacity ? targetCap : minCapacity;
+            final int[] newValues = new int[newCapacity];
+            System.arraycopy(mValues, 0, newValues, 0, currentSize);
+            mValues = newValues;
+        }
+    }
+
+    /**
+     * Removes all values from this array.
+     */
+    public void clear() {
+        mSize = 0;
+    }
+
+    @Override
+    public IntArray clone() {
+        return wrap(toArray());
+    }
+
+    /**
+     * Returns the value at the specified position in this array.
+     */
+    public int get(int index) {
+        checkBounds(mSize, index);
+        return mValues[index];
+    }
+
+    /**
+     * Sets the value at the specified position in this array.
+     */
+    public void set(int index, int value) {
+        checkBounds(mSize, index);
+        mValues[index] = value;
+    }
+
+    /**
+     * Returns the index of the first occurrence of the specified value in this
+     * array, or -1 if this array does not contain the value.
+     */
+    public int indexOf(int value) {
+        final int n = mSize;
+        for (int i = 0; i < n; i++) {
+            if (mValues[i] == value) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    public boolean contains(int value) {
+        return indexOf(value) >= 0;
+    }
+
+    public boolean isEmpty() {
+        return mSize == 0;
+    }
+
+    /**
+     * Removes the value at the specified index from this array.
+     */
+    public void removeIndex(int index) {
+        checkBounds(mSize, index);
+        System.arraycopy(mValues, index + 1, mValues, index, mSize - index - 1);
+        mSize--;
+    }
+
+    /**
+     * Removes the values if it exists
+     */
+    public void removeValue(int value) {
+        int index = indexOf(value);
+        if (index >= 0) {
+            removeIndex(index);
+        }
+    }
+
+    /**
+     * Removes the values if it exists
+     */
+    public void removeAllValues(IntArray values) {
+        for (int i = 0; i < values.mSize; i++) {
+            removeValue(values.mValues[i]);
+        }
+    }
+
+    /**
+     * Returns the number of values in this array.
+     */
+    public int size() {
+        return mSize;
+    }
+
+    /**
+     * Returns a new array with the contents of this IntArray.
+     */
+    public int[] toArray() {
+        return mSize == 0 ? EMPTY_INT : Arrays.copyOf(mValues, mSize);
+    }
+
+    /**
+     * Returns a comma separate list of all values.
+     */
+    public String toConcatString() {
+        StringBuilder b = new StringBuilder();
+        for (int i = 0; i < mSize ; i++) {
+            if (i > 0) {
+                b.append(", ");
+            }
+            b.append(mValues[i]);
+        }
+        return b.toString();
+    }
+
+    /**
+     * Throws {@link ArrayIndexOutOfBoundsException} if the index is out of bounds.
+     *
+     * @param len length of the array. Must be non-negative
+     * @param index the index to check
+     * @throws ArrayIndexOutOfBoundsException if the {@code index} is out of bounds of the array
+     */
+    private static void checkBounds(int len, int index) {
+        if (index < 0 || len <= index) {
+            throw new ArrayIndexOutOfBoundsException("length=" + len + "; index=" + index);
+        }
+    }
+}
\ No newline at end of file
diff --git a/src/com/android/launcher3/util/IntSet.java b/src/com/android/launcher3/util/IntSet.java
new file mode 100644
index 0000000..63499b0
--- /dev/null
+++ b/src/com/android/launcher3/util/IntSet.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.util;
+
+import java.util.Arrays;
+
+/**
+ * A wrapper over IntArray implementing a growing set of int primitives.
+ */
+public class IntSet {
+
+    final IntArray mArray = new IntArray();
+
+    /**
+     * Appends the specified value to the set if it does not exist.
+     */
+    public void add(int value) {
+        int index = Arrays.binarySearch(mArray.mValues, 0, mArray.mSize, value);
+        if (index < 0) {
+            mArray.add(-index - 1, value);
+        }
+    }
+
+    public boolean contains(int value) {
+        return Arrays.binarySearch(mArray.mValues, 0, mArray.mSize, value) >= 0;
+    }
+
+    public boolean isEmpty() {
+        return mArray.isEmpty();
+    }
+
+    /**
+     * Returns the number of values in this set.
+     */
+    public int size() {
+        return mArray.size();
+    }
+}
diff --git a/src/com/android/launcher3/util/LongArrayMap.java b/src/com/android/launcher3/util/IntSparseArrayMap.java
similarity index 80%
rename from src/com/android/launcher3/util/LongArrayMap.java
rename to src/com/android/launcher3/util/IntSparseArrayMap.java
index a337e85..9d5391b 100644
--- a/src/com/android/launcher3/util/LongArrayMap.java
+++ b/src/com/android/launcher3/util/IntSparseArrayMap.java
@@ -16,16 +16,16 @@
 
 package com.android.launcher3.util;
 
-import android.util.LongSparseArray;
+import android.util.SparseArray;
 
 import java.util.Iterator;
 
 /**
- * Extension of {@link LongSparseArray} with some utility methods.
+ * Extension of {@link SparseArray} with some utility methods.
  */
-public class LongArrayMap<E> extends LongSparseArray<E> implements Iterable<E> {
+public class IntSparseArrayMap<E> extends SparseArray<E> implements Iterable<E> {
 
-    public boolean containsKey(long key) {
+    public boolean containsKey(int key) {
         return indexOfKey(key) >= 0;
     }
 
@@ -34,8 +34,8 @@
     }
 
     @Override
-    public LongArrayMap<E> clone() {
-        return (LongArrayMap<E>) super.clone();
+    public IntSparseArrayMap<E> clone() {
+        return (IntSparseArrayMap<E>) super.clone();
     }
 
     @Override
diff --git a/src/com/android/launcher3/util/ItemInfoMatcher.java b/src/com/android/launcher3/util/ItemInfoMatcher.java
index 19cf6c1..c3570fe 100644
--- a/src/com/android/launcher3/util/ItemInfoMatcher.java
+++ b/src/com/android/launcher3/util/ItemInfoMatcher.java
@@ -105,7 +105,7 @@
                         keys.contains(ShortcutKey.fromItemInfo(info));
     }
 
-    static ItemInfoMatcher ofItemIds(LongArrayMap<Boolean> ids, Boolean matchDefault) {
+    static ItemInfoMatcher ofItemIds(IntSparseArrayMap<Boolean> ids, Boolean matchDefault) {
         return (info, cn) -> ids.get(info.id, matchDefault);
     }
 }
diff --git a/src_plugins/README.md b/src_plugins/README.md
new file mode 100644
index 0000000..c7ce1da
--- /dev/null
+++ b/src_plugins/README.md
@@ -0,0 +1,3 @@
+This directory contains plugin interfaces that launcher listens for and plugins implement. In other words, these are the hooks that specify what plugins launcher currently supports. 
+
+Details about how to create a new plugin interface, or to use existing interfaces to write a plugin can be found at go/gnl/plugins.
diff --git a/src_ui_overrides/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java b/src_ui_overrides/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
new file mode 100644
index 0000000..fcb2abe
--- /dev/null
+++ b/src_ui_overrides/com/android/launcher3/uioverrides/plugins/PluginManagerWrapper.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.launcher3.uioverrides.plugins;
+
+import android.content.Context;
+
+import com.android.launcher3.util.MainThreadInitializedObject;
+import com.android.systemui.plugins.Plugin;
+import com.android.systemui.plugins.PluginListener;
+
+public class PluginManagerWrapper {
+
+    public static final MainThreadInitializedObject<PluginManagerWrapper> INSTANCE =
+            new MainThreadInitializedObject<>(PluginManagerWrapper::new);
+
+    private PluginManagerWrapper(Context c) {
+    }
+
+    public void addPluginListener(PluginListener<? extends Plugin> listener, Class<?> pluginClass) {
+    }
+
+    public void removePluginListener(PluginListener<? extends Plugin> listener) {
+    }
+}
diff --git a/tests/AndroidManifest-common.xml b/tests/AndroidManifest-common.xml
index 89ca7f3..439058c 100644
--- a/tests/AndroidManifest-common.xml
+++ b/tests/AndroidManifest-common.xml
@@ -67,5 +67,33 @@
                 <category android:name="android.intent.category.DEFAULT"/>
             </intent-filter>
         </activity>
+
+        <provider
+            android:name="com.android.launcher3.testcomponent.TestCommandReceiver"
+            android:authorities="${packageName}.commands"
+            android:exported="true" />
+
+        <activity
+            android:name="com.android.launcher3.testcomponent.TestLauncherActivity"
+            android:launchMode="singleTask"
+            android:clearTaskOnLaunch="true"
+            android:label="Test launcher"
+            android:stateNotNeeded="true"
+            android:theme="@android:style/Theme.DeviceDefault.Light"
+            android:windowSoftInputMode="adjustPan"
+            android:screenOrientation="unspecified"
+            android:configChanges="keyboard|keyboardHidden|mcc|mnc|navigation|orientation|screenSize|screenLayout|smallestScreenSize"
+            android:resizeableActivity="true"
+            android:taskAffinity=""
+            android:process=":testLauncherProcess"
+            android:enabled="false">
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.HOME" />
+                <category android:name="android.intent.category.DEFAULT" />
+                <category android:name="android.intent.category.MONKEY"/>
+                <category android:name="android.intent.category.LAUNCHER_APP" />
+            </intent-filter>
+        </activity>
     </application>
 </manifest>
diff --git a/tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java b/tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
index 38e211b..6673ba9 100644
--- a/tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
+++ b/tests/src/com/android/launcher3/model/AddWorkspaceItemsTaskTest.java
@@ -23,7 +23,8 @@
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.ShortcutInfo;
 import com.android.launcher3.util.GridOccupancy;
-import com.android.launcher3.util.LongArrayMap;
+import com.android.launcher3.util.IntArray;
+import com.android.launcher3.util.IntSparseArrayMap;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -43,15 +44,15 @@
     private final ComponentName mComponent1 = new ComponentName("a", "b");
     private final ComponentName mComponent2 = new ComponentName("b", "b");
 
-    private ArrayList<Long> existingScreens;
-    private ArrayList<Long> newScreens;
-    private LongArrayMap<GridOccupancy> screenOccupancy;
+    private IntArray existingScreens;
+    private IntArray newScreens;
+    private IntSparseArrayMap<GridOccupancy> screenOccupancy;
 
     @Before
     public void initData() throws Exception {
-        existingScreens = new ArrayList<>();
-        screenOccupancy = new LongArrayMap<>();
-        newScreens = new ArrayList<>();
+        existingScreens = new IntArray();
+        screenOccupancy = new IntSparseArrayMap<>();
+        newScreens = new IntArray();
 
         idp.numColumns = 5;
         idp.numRows = 5;
@@ -65,7 +66,7 @@
         return new AddWorkspaceItemsTask(list) {
 
             @Override
-            protected void updateScreens(Context context, ArrayList<Long> workspaceScreens) { }
+            protected void updateScreens(Context context, IntArray workspaceScreens) { }
         };
     }
 
@@ -77,18 +78,18 @@
         // Second screen has 2 holes of sizes 3x2 and 2x3
         setupWorkspaceWithHoles(nextId, 2, new Rect(2, 0, 5, 2), new Rect(0, 2, 2, 5));
 
-        Pair<Long, int[]> spaceFound = newTask()
+        int[] spaceFound = newTask()
                 .findSpaceForItem(appState, bgDataModel, existingScreens, newScreens, 1, 1);
-        assertEquals(2L, (long) spaceFound.first);
-        assertTrue(screenOccupancy.get(spaceFound.first)
-                .isRegionVacant(spaceFound.second[0], spaceFound.second[1], 1, 1));
+        assertEquals(2, spaceFound[0]);
+        assertTrue(screenOccupancy.get(spaceFound[0])
+                .isRegionVacant(spaceFound[1], spaceFound[2], 1, 1));
 
         // Find a larger space
         spaceFound = newTask()
                 .findSpaceForItem(appState, bgDataModel, existingScreens, newScreens, 2, 3);
-        assertEquals(2L, (long) spaceFound.first);
-        assertTrue(screenOccupancy.get(spaceFound.first)
-                .isRegionVacant(spaceFound.second[0], spaceFound.second[1], 2, 3));
+        assertEquals(2, spaceFound[0]);
+        assertTrue(screenOccupancy.get(spaceFound[0])
+                .isRegionVacant(spaceFound[1], spaceFound[2], 2, 3));
     }
 
     @Test
@@ -97,11 +98,11 @@
         setupWorkspaceWithHoles(1, 1, new Rect(2, 0, 5, 2), new Rect(0, 2, 2, 5));
         commitScreensToDb();
 
-        ArrayList<Long> oldScreens = new ArrayList<>(existingScreens);
-        Pair<Long, int[]> spaceFound = newTask()
+        IntArray oldScreens = existingScreens.clone();
+        int[] spaceFound = newTask()
                 .findSpaceForItem(appState, bgDataModel, existingScreens, newScreens, 3, 3);
-        assertFalse(oldScreens.contains(spaceFound.first));
-        assertTrue(newScreens.contains(spaceFound.first));
+        assertFalse(oldScreens.contains(spaceFound[0]));
+        assertTrue(newScreens.contains(spaceFound[0]));
     }
 
     @Test
@@ -135,7 +136,7 @@
 
         // only info2 should be added because info was already added to the workspace
         // in setupWorkspaceWithHoles()
-        verify(callbacks).bindAppsAdded(any(ArrayList.class), notAnimated.capture(),
+        verify(callbacks).bindAppsAdded(any(IntArray.class), notAnimated.capture(),
                 animated.capture());
         assertTrue(notAnimated.getValue().isEmpty());
 
@@ -143,7 +144,7 @@
         assertTrue(animated.getValue().contains(info2));
     }
 
-    private int setupWorkspaceWithHoles(int startId, long screenId, Rect... holes) {
+    private int setupWorkspaceWithHoles(int startId, int screenId, Rect... holes) {
         GridOccupancy occupancy = new GridOccupancy(idp.numColumns, idp.numRows);
         occupancy.markCells(0, 0, idp.numColumns, idp.numRows, true);
         for (Rect r : holes) {
@@ -183,7 +184,7 @@
         int count = existingScreens.size();
         for (int i = 0; i < count; i++) {
             ContentValues v = new ContentValues();
-            long screenId = existingScreens.get(i);
+            int screenId = existingScreens.get(i);
             v.put(LauncherSettings.WorkspaceScreens._ID, screenId);
             v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
             ops.add(ContentProviderOperation.newInsert(uri).withValues(v).build());
diff --git a/tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java b/tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
index db80044..5fe9018 100644
--- a/tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
+++ b/tests/src/com/android/launcher3/model/CacheDataUpdatedTaskTest.java
@@ -53,7 +53,7 @@
 
         // Verify that only the app icons of app1 (id 1 & 2) are updated. Custom shortcut (id 7)
         // is not updated
-        verifyUpdate(1L, 2L);
+        verifyUpdate(1, 2);
 
         // Verify that only app1 var updated in allAppsList
         assertFalse(allAppsList.data.isEmpty());
@@ -80,11 +80,11 @@
 
         // app3 has only restored apps (id 5, 6) and shortcuts (id 9). Verify that only apps were
         // were updated
-        verifyUpdate(5L, 6L);
+        verifyUpdate(5, 6);
     }
 
-    private void verifyUpdate(Long... idsUpdated) {
-        HashSet<Long> updates = new HashSet<>(Arrays.asList(idsUpdated));
+    private void verifyUpdate(Integer... idsUpdated) {
+        HashSet<Integer> updates = new HashSet<>(Arrays.asList(idsUpdated));
         for (ItemInfo info : bgDataModel.itemsIdMap) {
             if (updates.contains(info.id)) {
                 assertEquals(NEW_LABEL_PREFIX + info.id, info.title);
diff --git a/tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java b/tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
index b2fd1d9..7fa401b 100644
--- a/tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
+++ b/tests/src/com/android/launcher3/model/GridSizeMigrationTaskTest.java
@@ -17,6 +17,7 @@
 import com.android.launcher3.LauncherProvider;
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.model.GridSizeMigrationTask.MultiStepMigrationTask;
+import com.android.launcher3.util.IntArray;
 import com.android.launcher3.util.TestLauncherProvider;
 
 import org.junit.Before;
@@ -24,7 +25,6 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
-import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.LinkedList;
 
@@ -43,8 +43,8 @@
             new ProviderTestRule.Builder(TestLauncherProvider.class, LauncherProvider.AUTHORITY)
                     .build();
 
-    private static final long DESKTOP = LauncherSettings.Favorites.CONTAINER_DESKTOP;
-    private static final long HOTSEAT = LauncherSettings.Favorites.CONTAINER_HOTSEAT;
+    private static final int DESKTOP = LauncherSettings.Favorites.CONTAINER_DESKTOP;
+    private static final int HOTSEAT = LauncherSettings.Favorites.CONTAINER_HOTSEAT;
 
     private static final int APPLICATION = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
     private static final int SHORTCUT = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
@@ -75,7 +75,7 @@
 
     @Test
     public void testHotseatMigration_apps_dropped() throws Exception {
-        long[] hotseatItems = {
+        int[] hotseatItems = {
                 addItem(APPLICATION, 0, HOTSEAT, 0, 0),
                 addItem(SHORTCUT, 1, HOTSEAT, 0, 0),
                 -1,
@@ -92,7 +92,7 @@
 
     @Test
     public void testHotseatMigration_shortcuts_dropped() throws Exception {
-        long[] hotseatItems = {
+        int[] hotseatItems = {
                 addItem(APPLICATION, 0, HOTSEAT, 0, 0),
                 addItem(30, 1, HOTSEAT, 0, 0),
                 -1,
@@ -107,11 +107,11 @@
         verifyHotseat(hotseatItems[1], hotseatItems[3], hotseatItems[4]);
     }
 
-    private void verifyHotseat(long... sortedIds) {
+    private void verifyHotseat(int... sortedIds) {
         int screenId = 0;
         int total = 0;
 
-        for (long id : sortedIds) {
+        for (int id : sortedIds) {
             Cursor c = mProviderRule.getResolver().query(LauncherSettings.Favorites.CONTENT_URI,
                     new String[]{LauncherSettings.Favorites._ID},
                     "container=-101 and screen=" + screenId, null, null, null);
@@ -139,7 +139,7 @@
 
     @Test
     public void testWorkspace_empty_row_column_removed() throws Exception {
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 {  0,  0, -1,  1},
                 {  3,  1, -1,  4},
                 { -1, -1, -1, -1},
@@ -150,7 +150,7 @@
                 new Point(4, 4), new Point(3, 3)).migrateWorkspace();
 
         // Column 2 and row 2 got removed.
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {ids[0][0][0], ids[0][0][1], ids[0][0][3]},
                 {ids[0][1][0], ids[0][1][1], ids[0][1][3]},
                 {ids[0][3][0], ids[0][3][1], ids[0][3][3]},
@@ -159,7 +159,7 @@
 
     @Test
     public void testWorkspace_new_screen_created() throws Exception {
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 {  0,  0,  0,  1},
                 {  3,  1,  0,  4},
                 { -1, -1, -1, -1},
@@ -170,7 +170,7 @@
                 new Point(4, 4), new Point(3, 3)).migrateWorkspace();
 
         // Items in the second column get moved to new screen
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {ids[0][0][0], ids[0][0][1], ids[0][0][3]},
                 {ids[0][1][0], ids[0][1][1], ids[0][1][3]},
                 {ids[0][3][0], ids[0][3][1], ids[0][3][3]},
@@ -181,7 +181,7 @@
 
     @Test
     public void testWorkspace_items_merged_in_next_screen() throws Exception {
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 {  0,  0,  0,  1},
                 {  3,  1,  0,  4},
                 { -1, -1, -1, -1},
@@ -196,7 +196,7 @@
 
         // Items in the second column of the first screen should get placed on the 3rd
         // row of the second screen
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {ids[0][0][0], ids[0][0][1], ids[0][0][3]},
                 {ids[0][1][0], ids[0][1][1], ids[0][1][3]},
                 {ids[0][3][0], ids[0][3][1], ids[0][3][3]},
@@ -211,7 +211,7 @@
     public void testWorkspace_items_not_merged_in_next_screen() throws Exception {
         // First screen has 2 items that need to be moved, but second screen has only one
         // empty space after migration (top-left corner)
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 {  0,  0,  0,  1},
                 {  3,  1,  0,  4},
                 { -1, -1, -1, -1},
@@ -227,7 +227,7 @@
                 new Point(4, 4), new Point(3, 3)).migrateWorkspace();
 
         // Items in the second column of the first screen should get placed on a new screen.
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {ids[0][0][0], ids[0][0][1], ids[0][0][3]},
                 {ids[0][1][0], ids[0][1][1], ids[0][1][3]},
                 {ids[0][3][0], ids[0][3][1], ids[0][3][3]},
@@ -244,7 +244,7 @@
     public void testWorkspace_first_row_blocked() throws Exception {
         // The first screen has one item on the 4th column which needs moving, as the first row
         // will be kept empty.
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 { -1, -1, -1, -1},
                 {  3,  1,  7,  0},
                 {  8,  7,  7, -1},
@@ -255,7 +255,7 @@
                 new Point(4, 4), new Point(3, 4)).migrateWorkspace();
 
         // Items in the second column of the first screen should get placed on a new screen.
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {          -1,           -1,           -1},
                 {ids[0][1][0], ids[0][1][1], ids[0][1][2]},
                 {ids[0][2][0], ids[0][2][1], ids[0][2][2]},
@@ -268,7 +268,7 @@
     @Test
     public void testWorkspace_items_moved_to_empty_first_row() throws Exception {
         // Items will get moved to the next screen to keep the first screen empty.
-        long[][][] ids = createGrid(new int[][][]{{
+        int[][][] ids = createGrid(new int[][][]{{
                 { -1, -1, -1, -1},
                 {  0,  1,  0,  0},
                 {  8,  7,  7, -1},
@@ -279,7 +279,7 @@
                 new Point(4, 4), new Point(3, 3)).migrateWorkspace();
 
         // Items in the second column of the first screen should get placed on a new screen.
-        verifyWorkspace(new long[][][] {{
+        verifyWorkspace(new int[][][] {{
                 {          -1,           -1,           -1},
                 {ids[0][2][0], ids[0][2][1], ids[0][2][2]},
                 {ids[0][3][0], ids[0][3][1], ids[0][3][2]},
@@ -289,7 +289,7 @@
         }});
     }
 
-    private long[][][] createGrid(int[][][] typeArray) throws Exception {
+    private int[][][] createGrid(int[][][] typeArray) throws Exception {
         return createGrid(typeArray, 1);
     }
 
@@ -300,14 +300,14 @@
      *                  two represent the workspace grid.
      * @return the same grid representation where each entry is the corresponding item id.
      */
-    private long[][][] createGrid(int[][][] typeArray, long startScreen) throws Exception {
+    private int[][][] createGrid(int[][][] typeArray, int startScreen) throws Exception {
         LauncherSettings.Settings.call(mProviderRule.getResolver(),
                 LauncherSettings.Settings.METHOD_CREATE_EMPTY_DB);
-        long[][][] ids = new long[typeArray.length][][];
+        int[][][] ids = new int[typeArray.length][][];
 
         for (int i = 0; i < typeArray.length; i++) {
             // Add screen to DB
-            long screenId = startScreen + i;
+            int screenId = startScreen + i;
 
             // Keep the screen id counter up to date
             LauncherSettings.Settings.call(mProviderRule.getResolver(),
@@ -318,9 +318,9 @@
             v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
             mProviderRule.getResolver().insert(LauncherSettings.WorkspaceScreens.CONTENT_URI, v);
 
-            ids[i] = new long[typeArray[i].length][];
+            ids[i] = new int[typeArray[i].length][];
             for (int y = 0; y < typeArray[i].length; y++) {
-                ids[i][y] = new long[typeArray[i][y].length];
+                ids[i][y] = new int[typeArray[i][y].length];
                 for (int x = 0; x < typeArray[i][y].length; x++) {
                     if (typeArray[i][y][x] < 0) {
                         // Empty cell
@@ -339,16 +339,16 @@
      * @param ids A 3d array where the first dimension represents the screen, and the rest two
      *            represent the workspace grid.
      */
-    private void verifyWorkspace(long[][][] ids) {
-        ArrayList<Long> allScreens = LauncherModel.loadWorkspaceScreensDb(mContext);
+    private void verifyWorkspace(int[][][] ids) {
+        IntArray allScreens = LauncherModel.loadWorkspaceScreensDb(mContext);
         assertEquals(ids.length, allScreens.size());
         int total = 0;
 
         for (int i = 0; i < ids.length; i++) {
-            long screenId = allScreens.get(i);
+            int screenId = allScreens.get(i);
             for (int y = 0; y < ids[i].length; y++) {
                 for (int x = 0; x < ids[i][y].length; x++) {
-                    long id = ids[i][y][x];
+                    int id = ids[i][y][x];
 
                     Cursor c = mProviderRule.getResolver().query(
                             LauncherSettings.Favorites.CONTENT_URI,
@@ -382,10 +382,10 @@
      * @param type {@link #APPLICATION} or {@link #SHORTCUT} or >= 2 for
      *             folder (where the type represents the number of items in the folder).
      */
-    private long addItem(int type, long screen, long container, int x, int y) throws Exception {
-        long id = LauncherSettings.Settings.call(mProviderRule.getResolver(),
+    private int addItem(int type, int screen, int container, int x, int y) throws Exception {
+        int id = LauncherSettings.Settings.call(mProviderRule.getResolver(),
                 LauncherSettings.Settings.METHOD_NEW_ITEM_ID)
-                .getLong(LauncherSettings.Settings.EXTRA_VALUE);
+                .getInt(LauncherSettings.Settings.EXTRA_VALUE);
 
         ContentValues values = new ContentValues();
         values.put(LauncherSettings.Favorites._ID, id);
diff --git a/tests/src/com/android/launcher3/model/LoaderCursorTest.java b/tests/src/com/android/launcher3/model/LoaderCursorTest.java
index a21f861..ac1be17 100644
--- a/tests/src/com/android/launcher3/model/LoaderCursorTest.java
+++ b/tests/src/com/android/launcher3/model/LoaderCursorTest.java
@@ -18,6 +18,7 @@
 import com.android.launcher3.Utilities;
 import com.android.launcher3.compat.LauncherAppsCompat;
 import com.android.launcher3.icons.BitmapInfo;
+import com.android.launcher3.util.IntArray;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -149,83 +150,83 @@
 
     @Test
     public void checkItemPlacement_wrongWorkspaceScreen() {
-        ArrayList<Long> workspaceScreens = new ArrayList<>(Arrays.asList(1L, 3L));
+        IntArray workspaceScreens = IntArray.wrap(1, 3);
         mIDP.numRows = 4;
         mIDP.numColumns = 4;
         mIDP.numHotseatIcons = 3;
 
         // Item on unknown screen are not placed
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 4L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 4), workspaceScreens));
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 5L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 5), workspaceScreens));
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2), workspaceScreens));
 
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1), workspaceScreens));
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 3L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 3), workspaceScreens));
 
     }
     @Test
     public void checkItemPlacement_outsideBounds() {
-        ArrayList<Long> workspaceScreens = new ArrayList<>(Arrays.asList(1L, 2L));
+        IntArray workspaceScreens = IntArray.wrap(1, 2);
         mIDP.numRows = 4;
         mIDP.numColumns = 4;
         mIDP.numHotseatIcons = 3;
 
         // Item outside screen bounds are not placed
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(4, 4, 1, 1, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(4, 4, 1, 1, CONTAINER_DESKTOP, 1), workspaceScreens));
     }
 
     @Test
     public void checkItemPlacement_overlappingItems() {
-        ArrayList<Long> workspaceScreens = new ArrayList<>(Arrays.asList(1L, 2L));
+        IntArray workspaceScreens = IntArray.wrap(1, 2);
         mIDP.numRows = 4;
         mIDP.numColumns = 4;
         mIDP.numHotseatIcons = 3;
 
         // Overlapping items are not placed
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1), workspaceScreens));
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 1), workspaceScreens));
 
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2), workspaceScreens));
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2L), workspaceScreens));
+                newItemInfo(0, 0, 1, 1, CONTAINER_DESKTOP, 2), workspaceScreens));
 
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(1, 1, 1, 1, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(1, 1, 1, 1, CONTAINER_DESKTOP, 1), workspaceScreens));
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(2, 2, 2, 2, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(2, 2, 2, 2, CONTAINER_DESKTOP, 1), workspaceScreens));
 
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(3, 2, 1, 2, CONTAINER_DESKTOP, 1L), workspaceScreens));
+                newItemInfo(3, 2, 1, 2, CONTAINER_DESKTOP, 1), workspaceScreens));
     }
 
     @Test
     public void checkItemPlacement_hotseat() {
-        ArrayList<Long> workspaceScreens = new ArrayList<>();
+        IntArray workspaceScreens = new IntArray();
         mIDP.numRows = 4;
         mIDP.numColumns = 4;
         mIDP.numHotseatIcons = 3;
 
         // Hotseat items are only placed based on screenId
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 1L), workspaceScreens));
+                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 1), workspaceScreens));
         assertTrue(mLoaderCursor.checkItemPlacement(
-                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 2L), workspaceScreens));
+                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 2), workspaceScreens));
 
         assertFalse(mLoaderCursor.checkItemPlacement(
-                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 3L), workspaceScreens));
+                newItemInfo(3, 3, 1, 1, CONTAINER_HOTSEAT, 3), workspaceScreens));
     }
 
     private ItemInfo newItemInfo(int cellX, int cellY, int spanX, int spanY,
-            long container, long screenId) {
+            int container, int screenId) {
         ItemInfo info = new ItemInfo();
         info.cellX = cellX;
         info.cellY = cellY;
diff --git a/tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java b/tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
index 435686f..25100dc 100644
--- a/tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
+++ b/tests/src/com/android/launcher3/model/PackageInstallStateChangedTaskTest.java
@@ -48,18 +48,18 @@
     public void testSessionUpdate_shortcuts_updated() throws Exception {
         executeTaskForTest(newTask("app3", 30));
 
-        verifyProgressUpdate(30, 5L, 6L, 7L);
+        verifyProgressUpdate(30, 5, 6, 7);
     }
 
     @Test
     public void testSessionUpdate_widgets_updated() throws Exception {
         executeTaskForTest(newTask("app4", 30));
 
-        verifyProgressUpdate(30, 8L, 9L);
+        verifyProgressUpdate(30, 8, 9);
     }
 
-    private void verifyProgressUpdate(int progress, Long... idsUpdated) {
-        HashSet<Long> updates = new HashSet<>(Arrays.asList(idsUpdated));
+    private void verifyProgressUpdate(int progress, Integer... idsUpdated) {
+        HashSet<Integer> updates = new HashSet<>(Arrays.asList(idsUpdated));
         for (ItemInfo info : bgDataModel.itemsIdMap) {
             if (info instanceof ShortcutInfo) {
                 assertEquals(updates.contains(info.id) ? progress: 0,
diff --git a/tests/src/com/android/launcher3/testcomponent/TestCommandReceiver.java b/tests/src/com/android/launcher3/testcomponent/TestCommandReceiver.java
new file mode 100644
index 0000000..04c04f5
--- /dev/null
+++ b/tests/src/com/android/launcher3/testcomponent/TestCommandReceiver.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.android.launcher3.testcomponent;
+
+import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
+import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+import static android.content.pm.PackageManager.DONT_KILL_APP;
+
+import android.app.Instrumentation;
+import android.content.ComponentName;
+import android.content.ContentProvider;
+import android.content.ContentValues;
+import android.database.Cursor;
+import android.net.Uri;
+import android.os.Bundle;
+
+import androidx.test.InstrumentationRegistry;
+
+/**
+ * Content provider to receive commands from tests
+ */
+public class TestCommandReceiver extends ContentProvider {
+
+    public static final String ENABLE_TEST_LAUNCHER = "enable-test-launcher";
+    public static final String DISABLE_TEST_LAUNCHER = "disable-test-launcher";
+
+    @Override
+    public boolean onCreate() {
+        return true;
+    }
+
+    @Override
+    public int delete(Uri uri, String selection, String[] selectionArgs) {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
+    @Override
+    public String getType(Uri uri) {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
+    @Override
+    public Uri insert(Uri uri, ContentValues values) {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
+    @Override
+    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
+            String sortOrder) {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
+    @Override
+    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
+        throw new UnsupportedOperationException("unimplemented mock method");
+    }
+
+    @Override
+    public Bundle call(String method, String arg, Bundle extras) {
+        switch (method) {
+            case ENABLE_TEST_LAUNCHER: {
+                getContext().getPackageManager().setComponentEnabledSetting(
+                        new ComponentName(getContext(), TestLauncherActivity.class),
+                        COMPONENT_ENABLED_STATE_ENABLED, DONT_KILL_APP);
+                return null;
+            }
+            case DISABLE_TEST_LAUNCHER: {
+                getContext().getPackageManager().setComponentEnabledSetting(
+                        new ComponentName(getContext(), TestLauncherActivity.class),
+                        COMPONENT_ENABLED_STATE_DISABLED, DONT_KILL_APP);
+                return null;
+            }
+
+        }
+        return super.call(method, arg, extras);
+    }
+
+    public static Bundle callCommand(String command) {
+        Instrumentation inst = InstrumentationRegistry.getInstrumentation();
+        Uri uri = Uri.parse("content://" + inst.getContext().getPackageName() + ".commands");
+        return inst.getTargetContext().getContentResolver().call(uri, command, null, null);
+    }
+}
diff --git a/tests/src/com/android/launcher3/testcomponent/TestLauncherActivity.java b/tests/src/com/android/launcher3/testcomponent/TestLauncherActivity.java
new file mode 100644
index 0000000..357a232
--- /dev/null
+++ b/tests/src/com/android/launcher3/testcomponent/TestLauncherActivity.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+package com.android.launcher3.testcomponent;
+
+import static android.content.Intent.ACTION_MAIN;
+import static android.content.Intent.CATEGORY_LAUNCHER;
+import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
+import static android.content.Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED;
+
+import android.app.LauncherActivity;
+import android.content.Intent;
+
+public class TestLauncherActivity extends LauncherActivity {
+
+    @Override
+    protected Intent getTargetIntent() {
+        return new Intent(ACTION_MAIN, null)
+                .addCategory(CATEGORY_LAUNCHER)
+                .addFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
+    }
+}
diff --git a/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java b/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
index 00df4e7..6db784a 100644
--- a/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
+++ b/tests/src/com/android/launcher3/ui/AbstractLauncherUiTest.java
@@ -19,6 +19,8 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
 import android.app.Instrumentation;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
@@ -45,6 +47,7 @@
 import com.android.launcher3.Launcher;
 import com.android.launcher3.LauncherAppState;
 import com.android.launcher3.LauncherAppWidgetProviderInfo;
+import com.android.launcher3.LauncherModel;
 import com.android.launcher3.LauncherSettings;
 import com.android.launcher3.LauncherState;
 import com.android.launcher3.MainThreadExecutor;
@@ -53,10 +56,12 @@
 import com.android.launcher3.compat.AppWidgetManagerCompat;
 import com.android.launcher3.compat.LauncherAppsCompat;
 import com.android.launcher3.tapl.LauncherInstrumentation;
+import com.android.launcher3.tapl.TestHelpers;
 import com.android.launcher3.testcomponent.AppWidgetNoConfig;
 import com.android.launcher3.testcomponent.AppWidgetWithConfig;
 import com.android.launcher3.util.Wait;
 import com.android.launcher3.util.rule.LauncherActivityRule;
+import com.android.launcher3.util.rule.ShellCommandRule;
 
 import org.junit.After;
 import org.junit.Before;
@@ -95,7 +100,7 @@
     private static final String TAG = "AbstractLauncherUiTest";
 
     protected AbstractLauncherUiTest() {
-        final Instrumentation instrumentation = TestHelpers.getInstrumentation();
+        final Instrumentation instrumentation = getInstrumentation();
         mDevice = UiDevice.getInstance(instrumentation);
         try {
             mDevice.setOrientationNatural();
@@ -109,6 +114,11 @@
     @Rule
     public LauncherActivityRule mActivityMonitor = new LauncherActivityRule();
 
+    @Rule public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
+
+    @Rule public ShellCommandRule mDisableHeadsUpNotification =
+            ShellCommandRule.disableHeadsUpNotification();
+
     // Annotation for tests that need to be run in portrait and landscape modes.
     @Retention(RetentionPolicy.RUNTIME)
     @Target(ElementType.METHOD)
@@ -124,7 +134,8 @@
                     try {
                         // Create launcher activity if necessary and bring it to the front.
                         mDevice.pressHome();
-                        waitForLauncherCondition(launcher -> launcher != null);
+                        waitForLauncherCondition("Launcher activity wasn't created",
+                                launcher -> launcher != null);
 
                         executeOnLauncher(launcher ->
                                 launcher.getRotationHelper().forceAllowRotationForTesting(true));
@@ -156,14 +167,12 @@
     public void setUp() throws Exception {
         mTargetContext = InstrumentationRegistry.getTargetContext();
         mTargetPackage = mTargetContext.getPackageName();
-        mDevice.executeShellCommand("settings put global heads_up_notifications_enabled 0");
     }
 
     @After
     public void tearDown() throws Exception {
-        mDevice.executeShellCommand("settings put global heads_up_notifications_enabled 1");
         // Limits UI tests affecting tests running after them.
-        resetLoaderState();
+        waitForModelLoaded();
     }
 
     protected void lockRotation(boolean naturalOrientation) throws RemoteException {
@@ -282,7 +291,7 @@
     protected void sendPointer(int action, Point point) {
         MotionEvent event = MotionEvent.obtain(SystemClock.uptimeMillis(),
                 SystemClock.uptimeMillis(), action, point.x, point.y, 0);
-        TestHelpers.getInstrumentation().sendPointerSync(event);
+        getInstrumentation().sendPointerSync(event);
         event.recycle();
     }
 
@@ -313,8 +322,7 @@
         } catch (Throwable t) {
             throw new IllegalArgumentException(t);
         }
-        waitForLauncherCondition(launcher ->
-                LauncherAppState.getInstance(mTargetContext).getModel().isModelLoaded());
+        waitForModelLoaded();
         if (com.android.launcher3.Utilities.IS_RUNNING_IN_TEST_HARNESS
                 && com.android.launcher3.Utilities.IS_DEBUG_DEVICE) {
             android.util.Log.d("b/117332845",
@@ -322,6 +330,13 @@
         }
     }
 
+    protected void waitForModelLoaded() {
+        waitForLauncherCondition("Launcher model didn't load", launcher -> {
+            final LauncherModel model = LauncherAppState.getInstance(mTargetContext).getModel();
+            return model.getCallback() == null || model.isModelLoaded();
+        });
+    }
+
     /**
      * Runs the callback on the UI thread and returns the result.
      */
@@ -347,22 +362,23 @@
 
     // Cannot be used in TaplTests between a Tapl call injecting a gesture and a tapl call expecting
     // the results of that gesture because the wait can hide flakeness.
-    protected boolean waitForState(LauncherState state) {
-        return waitForLauncherCondition(launcher -> launcher.getStateManager().getState() == state);
+    protected void waitForState(String message, LauncherState state) {
+        waitForLauncherCondition(message,
+                launcher -> launcher.getStateManager().getState() == state);
     }
 
     // Cannot be used in TaplTests after injecting any gesture using Tapl because this can hide
     // flakiness.
-    protected boolean waitForLauncherCondition(Function<Launcher, Boolean> condition) {
-        return waitForLauncherCondition(condition, DEFAULT_ACTIVITY_TIMEOUT);
+    protected void waitForLauncherCondition(String message, Function<Launcher, Boolean> condition) {
+        waitForLauncherCondition(message, condition, DEFAULT_ACTIVITY_TIMEOUT);
     }
 
     // Cannot be used in TaplTests after injecting any gesture using Tapl because this can hide
     // flakiness.
-    protected boolean waitForLauncherCondition(
-            Function<Launcher, Boolean> condition, long timeout) {
-        if (!TestHelpers.isInLauncherProcess()) return true;
-        return Wait.atMost(() -> getFromLauncher(condition), timeout);
+    protected void waitForLauncherCondition(
+            String message, Function<Launcher, Boolean> condition, long timeout) {
+        if (!TestHelpers.isInLauncherProcess()) return;
+        Wait.atMost(message, () -> getFromLauncher(condition), timeout);
     }
 
     /**
@@ -374,7 +390,7 @@
                 getOnUiThread(new Callable<LauncherAppWidgetProviderInfo>() {
             @Override
             public LauncherAppWidgetProviderInfo call() throws Exception {
-                ComponentName cn = new ComponentName(TestHelpers.getInstrumentation().getContext(),
+                ComponentName cn = new ComponentName(getInstrumentation().getContext(),
                         hasConfigureScreen ? AppWidgetWithConfig.class : AppWidgetNoConfig.class);
                 Log.d(TAG, "findWidgetProvider componentName=" + cn.flattenToString());
                 return AppWidgetManagerCompat.getInstance(mTargetContext)
diff --git a/tests/src/com/android/launcher3/ui/AllAppsIconToHomeTest.java b/tests/src/com/android/launcher3/ui/AllAppsIconToHomeTest.java
index a0f4620..a6830fc 100644
--- a/tests/src/com/android/launcher3/ui/AllAppsIconToHomeTest.java
+++ b/tests/src/com/android/launcher3/ui/AllAppsIconToHomeTest.java
@@ -11,10 +11,8 @@
 
 import com.android.launcher3.util.Condition;
 import com.android.launcher3.util.Wait;
-import com.android.launcher3.util.rule.ShellCommandRule;
 
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -25,8 +23,6 @@
 @RunWith(AndroidJUnit4.class)
 public class AllAppsIconToHomeTest extends AbstractLauncherUiTest {
 
-    @Rule public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
-
     @Test
     @Ignore
     public void testDragIcon_portrait() throws Throwable {
@@ -50,7 +46,7 @@
 
         // Open all apps and wait for load complete.
         final UiObject2 appsContainer = openAllApps();
-        assertTrue(Wait.atMost(Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Drag icon to homescreen.
         UiObject2 icon = scrollAndFind(appsContainer, By.text(settingsApp.getLabel().toString()));
diff --git a/tests/src/com/android/launcher3/ui/ShortcutsLaunchTest.java b/tests/src/com/android/launcher3/ui/ShortcutsLaunchTest.java
index 83a6734..f773000 100644
--- a/tests/src/com/android/launcher3/ui/ShortcutsLaunchTest.java
+++ b/tests/src/com/android/launcher3/ui/ShortcutsLaunchTest.java
@@ -15,10 +15,8 @@
 import com.android.launcher3.R;
 import com.android.launcher3.util.Condition;
 import com.android.launcher3.util.Wait;
-import com.android.launcher3.util.rule.ShellCommandRule;
 
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -29,8 +27,6 @@
 @RunWith(AndroidJUnit4.class)
 public class ShortcutsLaunchTest extends AbstractLauncherUiTest {
 
-    @Rule public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
-
     @Test
     @Ignore
     public void testAppLauncher_portrait() throws Exception {
@@ -51,8 +47,7 @@
 
         // Open all apps and wait for load complete
         final UiObject2 appsContainer = openAllApps();
-        assertTrue(Wait.atMost(Condition.minChildCount(appsContainer, 2),
-                DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Find settings app and verify shortcuts appear when long pressed
         UiObject2 icon = scrollAndFind(appsContainer, By.text(testApp.getLabel().toString()));
diff --git a/tests/src/com/android/launcher3/ui/ShortcutsToHomeTest.java b/tests/src/com/android/launcher3/ui/ShortcutsToHomeTest.java
index 793bd8f..bc1b519 100644
--- a/tests/src/com/android/launcher3/ui/ShortcutsToHomeTest.java
+++ b/tests/src/com/android/launcher3/ui/ShortcutsToHomeTest.java
@@ -15,10 +15,8 @@
 import com.android.launcher3.R;
 import com.android.launcher3.util.Condition;
 import com.android.launcher3.util.Wait;
-import com.android.launcher3.util.rule.ShellCommandRule;
 
 import org.junit.Ignore;
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
@@ -29,8 +27,6 @@
 @RunWith(AndroidJUnit4.class)
 public class ShortcutsToHomeTest extends AbstractLauncherUiTest {
 
-    @Rule public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
-
     @Test
     @Ignore
     public void testDragIcon_portrait() throws Throwable {
@@ -53,8 +49,7 @@
 
         // Open all apps and wait for load complete.
         final UiObject2 appsContainer = openAllApps();
-        assertTrue(Wait.atMost(Condition.minChildCount(appsContainer, 2),
-                DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Find the app and long press it to show shortcuts.
         UiObject2 icon = scrollAndFind(appsContainer, By.text(testApp.getLabel().toString()));
diff --git a/tests/src/com/android/launcher3/ui/TestHelpers.java b/tests/src/com/android/launcher3/ui/TestHelpers.java
deleted file mode 100644
index da21a5d..0000000
--- a/tests/src/com/android/launcher3/ui/TestHelpers.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License"); you may not
- * use this file except in compliance with the License. You may obtain a copy of
- * the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.android.launcher3.ui;
-
-import android.app.Instrumentation;
-
-import androidx.test.InstrumentationRegistry;
-import androidx.test.uiautomator.UiDevice;
-
-public class TestHelpers {
-    private static final boolean IS_IN_LAUNCHER_PROCESS =
-            getInstrumentation().getTargetContext().getPackageName().equals(
-                    UiDevice.getInstance(getInstrumentation()).getLauncherPackageName());
-
-    public static Instrumentation getInstrumentation() {
-        return InstrumentationRegistry.getInstrumentation();
-    }
-
-    public static boolean isInLauncherProcess() {
-        return IS_IN_LAUNCHER_PROCESS;
-    }
-}
diff --git a/tests/src/com/android/launcher3/ui/WorkTabTest.java b/tests/src/com/android/launcher3/ui/WorkTabTest.java
index 044b7f3..c93c20a 100644
--- a/tests/src/com/android/launcher3/ui/WorkTabTest.java
+++ b/tests/src/com/android/launcher3/ui/WorkTabTest.java
@@ -22,19 +22,14 @@
 import androidx.test.filters.LargeTest;
 import androidx.test.runner.AndroidJUnit4;
 
-import com.android.launcher3.util.rule.ShellCommandRule;
-
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Rule;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 
 @LargeTest
 @RunWith(AndroidJUnit4.class)
 public class WorkTabTest extends AbstractLauncherUiTest {
-    @Rule
-    public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
 
     private int mProfileUserId;
 
diff --git a/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
index 0635e11..14141f0 100644
--- a/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/AddConfigWidgetTest.java
@@ -20,6 +20,8 @@
 import static org.junit.Assert.assertNotSame;
 import static org.junit.Assert.assertTrue;
 
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
 import android.appwidget.AppWidgetManager;
 import android.content.Intent;
 import androidx.test.filters.LargeTest;
@@ -34,7 +36,7 @@
 import com.android.launcher3.Workspace;
 import com.android.launcher3.testcomponent.WidgetConfigActivity;
 import com.android.launcher3.ui.AbstractLauncherUiTest;
-import com.android.launcher3.ui.TestHelpers;
+import com.android.launcher3.tapl.TestHelpers;
 import com.android.launcher3.util.Condition;
 import com.android.launcher3.util.Wait;
 import com.android.launcher3.util.rule.ShellCommandRule;
@@ -69,16 +71,19 @@
     }
 
     @Test
+    @Ignore
     public void testWidgetConfig() throws Throwable {
         runTest(false, true);
     }
 
     @Test
+    @Ignore
     public void testWidgetConfig_rotate() throws Throwable {
         runTest(true, true);
     }
 
     @Test
+    @Ignore
     public void testConfigCancelled() throws Throwable {
         runTest(false, false);
     }
@@ -101,7 +106,7 @@
 
         // Open widget tray and wait for load complete.
         final UiObject2 widgetContainer = openWidgetsTray();
-        assertTrue(Wait.atMost(Condition.minChildCount(widgetContainer, 2), DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(widgetContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Drag widget to homescreen
         WidgetConfigStartupMonitor monitor = new WidgetConfigStartupMonitor();
@@ -123,18 +128,17 @@
 
         setResult(acceptConfig);
         if (acceptConfig) {
-            assertTrue(Wait.atMost(new WidgetSearchCondition(), DEFAULT_ACTIVITY_TIMEOUT));
+            Wait.atMost(null, new WidgetSearchCondition(), DEFAULT_ACTIVITY_TIMEOUT);
             assertNotNull(mAppWidgetManager.getAppWidgetInfo(mWidgetId));
         } else {
             // Verify that the widget id is deleted.
-            assertTrue(Wait.atMost(() -> mAppWidgetManager.getAppWidgetInfo(mWidgetId) == null,
-                    DEFAULT_ACTIVITY_TIMEOUT));
+            Wait.atMost(null, () -> mAppWidgetManager.getAppWidgetInfo(mWidgetId) == null,
+                    DEFAULT_ACTIVITY_TIMEOUT);
         }
     }
 
     private void setResult(boolean success) {
-
-        TestHelpers.getInstrumentation().getTargetContext().sendBroadcast(
+        getInstrumentation().getTargetContext().sendBroadcast(
                 WidgetConfigActivity.getCommandIntent(WidgetConfigActivity.class,
                         success ? "clickOK" : "clickCancel"));
     }
diff --git a/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
index d9fef81..8a05e2c 100644
--- a/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/AddWidgetTest.java
@@ -70,7 +70,7 @@
 
         // Open widget tray and wait for load complete.
         final UiObject2 widgetContainer = openWidgetsTray();
-        assertTrue(Wait.atMost(Condition.minChildCount(widgetContainer, 2), DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(widgetContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Drag widget to homescreen
         UiObject2 widget = scrollAndFind(widgetContainer, By.clazz(WidgetCell.class)
diff --git a/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java b/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
index c1dc43b..b7342c4 100644
--- a/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/BindWidgetTest.java
@@ -56,6 +56,7 @@
 import org.junit.Ignore;
 import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TestRule;
 import org.junit.runner.RunWith;
 
 import java.util.Set;
@@ -71,8 +72,6 @@
 @RunWith(AndroidJUnit4.class)
 public class BindWidgetTest extends AbstractLauncherUiTest {
 
-    @Rule public ShellCommandRule mGrantWidgetRule = ShellCommandRule.grandWidgetBind();
-
     private ContentResolver mResolver;
     private AppWidgetManagerCompat mWidgetManager;
 
@@ -142,7 +141,6 @@
         // Since there is no widget to verify, just wait until the workspace is ready.
         setupAndVerifyContents(item, Workspace.class, null);
 
-        waitUntilLoaderIdle();
         // Item deleted from db
         mCursor = mResolver.query(LauncherSettings.Favorites.getContentUri(item.id),
                 null, null, null, null, null);
@@ -188,7 +186,6 @@
         item.restoreStatus = LauncherAppWidgetInfo.FLAG_ID_NOT_VALID;
 
         setupAndVerifyContents(item, PendingAppWidgetHostView.class, null);
-        waitUntilLoaderIdle();
         // Item deleted from db
         mCursor = mResolver.query(LauncherSettings.Favorites.getContentUri(item.id),
                 null, null, null, null, null);
@@ -217,7 +214,6 @@
         // The view does not exist
         assertFalse(mDevice.findObject(
                 new UiSelector().className(PendingAppWidgetHostView.class)).exists());
-        waitUntilLoaderIdle();
         // Item deleted from db
         mCursor = mResolver.query(LauncherSettings.Favorites.getContentUri(item.id),
                 null, null, null, null, null);
@@ -235,7 +231,6 @@
 
         setupAndVerifyContents(item, PendingAppWidgetHostView.class, null);
         // Verify item still exists in db
-        waitUntilLoaderIdle();
         mCursor = mResolver.query(LauncherSettings.Favorites.getContentUri(item.id),
                 null, null, null, null, null);
         assertEquals(1, mCursor.getCount());
@@ -262,7 +257,6 @@
 
         setupAndVerifyContents(item, PendingAppWidgetHostView.class, null);
         // Verify item still exists in db
-        waitUntilLoaderIdle();
         mCursor = mResolver.query(LauncherSettings.Favorites.getContentUri(item.id),
                 null, null, null, null, null);
         assertEquals(1, mCursor.getCount());
@@ -282,7 +276,7 @@
      */
     private void setupAndVerifyContents(
             LauncherAppWidgetInfo item, Class<?> widgetClass, String desc) {
-        long screenId = Workspace.FIRST_SCREEN_ID;
+        int screenId = Workspace.FIRST_SCREEN_ID;
         // Update the screen id counter for the provider.
         LauncherSettings.Settings.call(mResolver, LauncherSettings.Settings.METHOD_NEW_SCREEN_ID);
 
@@ -298,7 +292,7 @@
         ContentWriter writer = new ContentWriter(mTargetContext);
         item.id = LauncherSettings.Settings.call(
                 mResolver, LauncherSettings.Settings.METHOD_NEW_ITEM_ID)
-                .getLong(LauncherSettings.Settings.EXTRA_VALUE);
+                .getInt(LauncherSettings.Settings.EXTRA_VALUE);
         item.screenId = screenId;
         item.onAddToDatabase(writer);
         writer.put(LauncherSettings.Favorites._ID, item.id);
@@ -307,6 +301,8 @@
 
         // Launch the home activity
         mActivityMonitor.startLauncher();
+        waitForModelLoaded();
+
         // Verify UI
         UiSelector selector = new UiSelector().packageName(mTargetContext.getPackageName())
                 .className(widgetClass);
@@ -391,15 +387,4 @@
         item.container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
         return item;
     }
-
-    /**
-     * Blocks the current thread until all the jobs in the main worker thread are complete.
-     */
-    private void waitUntilLoaderIdle() throws Exception {
-        new LooperExecutor(LauncherModel.getWorkerLooper())
-                .submit(new Runnable() {
-                    @Override
-                    public void run() { }
-                }).get(DEFAULT_WORKER_TIMEOUT_SECS, TimeUnit.SECONDS);
-    }
 }
diff --git a/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java b/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
index 74f0978..839cfb2 100644
--- a/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
+++ b/tests/src/com/android/launcher3/ui/widget/RequestPinItemTest.java
@@ -60,10 +60,9 @@
  */
 @LargeTest
 @RunWith(AndroidJUnit4.class)
-public class RequestPinItemTest  extends AbstractLauncherUiTest {
+public class RequestPinItemTest extends AbstractLauncherUiTest {
 
     @Rule public ShellCommandRule mGrantWidgetRule = ShellCommandRule.grandWidgetBind();
-    @Rule public ShellCommandRule mDefaultLauncherRule = ShellCommandRule.setDefaultLauncher();
 
     private String mCallbackAction;
     private String mShortcutId;
@@ -153,7 +152,7 @@
 
         // Open all apps and wait for load complete
         final UiObject2 appsContainer = openAllApps();
-        assertTrue(Wait.atMost(Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT));
+        Wait.atMost(null, Condition.minChildCount(appsContainer, 2), DEFAULT_UI_TIMEOUT);
 
         // Open Pin item activity
         BlockingBroadcastReceiver openMonitor = new BlockingBroadcastReceiver(
@@ -192,7 +191,7 @@
 
         // Go back to home
         mActivityMonitor.returnToHome();
-        assertTrue(Wait.atMost(new ItemSearchCondition(itemMatcher), DEFAULT_ACTIVITY_TIMEOUT));
+        Wait.atMost(null, new ItemSearchCondition(itemMatcher), DEFAULT_ACTIVITY_TIMEOUT);
     }
 
     /**
diff --git a/tests/src/com/android/launcher3/util/IntSetTest.java b/tests/src/com/android/launcher3/util/IntSetTest.java
new file mode 100644
index 0000000..934b749
--- /dev/null
+++ b/tests/src/com/android/launcher3/util/IntSetTest.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.launcher3.util;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Unit tests for {@link IntSet}
+ */
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class IntSetTest {
+
+    @Test
+    public void testDuplicateEntries() {
+        IntSet set = new IntSet();
+
+        set.add(2);
+        assertEquals(1, set.size());
+
+        set.add(2);
+        assertEquals(1, set.size());
+        assertTrue(set.contains(2));
+        assertFalse(set.contains(1));
+
+        set.add(1);
+        assertEquals(2, set.size());
+        assertTrue(set.contains(2));
+        assertTrue(set.contains(1));
+
+
+        set.add(10);
+        assertEquals(3, set.size());
+
+        assertEquals("1, 2, 10", set.mArray.toConcatString());
+    }
+}
diff --git a/tests/src/com/android/launcher3/util/Wait.java b/tests/src/com/android/launcher3/util/Wait.java
index f9e53ba..0e41c02 100644
--- a/tests/src/com/android/launcher3/util/Wait.java
+++ b/tests/src/com/android/launcher3/util/Wait.java
@@ -2,6 +2,8 @@
 
 import android.os.SystemClock;
 
+import org.junit.Assert;
+
 /**
  * A utility class for waiting for a condition to be true.
  */
@@ -9,16 +11,16 @@
 
     private static final long DEFAULT_SLEEP_MS = 200;
 
-    public static boolean atMost(Condition condition, long timeout) {
-        return atMost(condition, timeout, DEFAULT_SLEEP_MS);
+    public static void atMost(String message, Condition condition, long timeout) {
+        atMost(message, condition, timeout, DEFAULT_SLEEP_MS);
     }
 
-    public static boolean atMost(Condition condition, long timeout, long sleepMillis) {
+    public static void atMost(String message, Condition condition, long timeout, long sleepMillis) {
         long endTime = SystemClock.uptimeMillis() + timeout;
         while (SystemClock.uptimeMillis() < endTime) {
             try {
                 if (condition.isTrue()) {
-                    return true;
+                    return;
                 }
             } catch (Throwable t) {
                 // Ignore
@@ -29,11 +31,11 @@
         // Check once more before returning false.
         try {
             if (condition.isTrue()) {
-                return true;
+                return;
             }
         } catch (Throwable t) {
             // Ignore
         }
-        return false;
+        Assert.fail(message);
     }
 }
diff --git a/tests/src/com/android/launcher3/util/rule/LauncherActivityRule.java b/tests/src/com/android/launcher3/util/rule/LauncherActivityRule.java
index 1c7160f..145c3c8 100644
--- a/tests/src/com/android/launcher3/util/rule/LauncherActivityRule.java
+++ b/tests/src/com/android/launcher3/util/rule/LauncherActivityRule.java
@@ -15,10 +15,14 @@
  */
 package com.android.launcher3.util.rule;
 
+import static com.android.launcher3.tapl.TestHelpers.getHomeIntentInPackage;
+
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+import static androidx.test.InstrumentationRegistry.getTargetContext;
+
 import android.app.Activity;
 import android.app.Application;
 import android.app.Application.ActivityLifecycleCallbacks;
-import android.content.Intent;
 import android.os.Bundle;
 import androidx.test.InstrumentationRegistry;
 
@@ -65,19 +69,12 @@
      * Starts the launcher activity in the target package.
      */
     public void startLauncher() {
-        InstrumentationRegistry.getInstrumentation().startActivitySync(getHomeIntent());
+        getInstrumentation().startActivitySync(getHomeIntentInPackage(getTargetContext()));
     }
 
     public void returnToHome() {
-        InstrumentationRegistry.getTargetContext().startActivity(getHomeIntent());
-        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
-    }
-
-    public static Intent getHomeIntent() {
-        return new Intent(Intent.ACTION_MAIN)
-                .addCategory(Intent.CATEGORY_HOME)
-                .setPackage(InstrumentationRegistry.getTargetContext().getPackageName())
-                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        getTargetContext().startActivity(getHomeIntentInPackage(getTargetContext()));
+        getInstrumentation().waitForIdleSync();
     }
 
     private class MyStatement extends Statement implements ActivityLifecycleCallbacks {
diff --git a/tests/src/com/android/launcher3/util/rule/ShellCommandRule.java b/tests/src/com/android/launcher3/util/rule/ShellCommandRule.java
index 9f0db2b..4531ab1 100644
--- a/tests/src/com/android/launcher3/util/rule/ShellCommandRule.java
+++ b/tests/src/com/android/launcher3/util/rule/ShellCommandRule.java
@@ -15,17 +15,20 @@
  */
 package com.android.launcher3.util.rule;
 
+import static com.android.launcher3.tapl.TestHelpers.getLauncherInMyProcess;
+
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+
 import android.content.ComponentName;
 import android.content.pm.ActivityInfo;
-import android.os.ParcelFileDescriptor;
-import androidx.test.InstrumentationRegistry;
 
 import org.junit.rules.TestRule;
 import org.junit.runner.Description;
 import org.junit.runners.model.Statement;
 
-import java.io.FileInputStream;
-import java.io.IOException;
+import androidx.annotation.Nullable;
+import androidx.test.InstrumentationRegistry;
+import androidx.test.uiautomator.UiDevice;
 
 /**
  * Test rule which executes a shell command at the start of the test.
@@ -33,40 +36,28 @@
 public class ShellCommandRule implements TestRule {
 
     private final String mCmd;
+    private final String mRevertCommand;
 
-    public ShellCommandRule(String cmd) {
+    public ShellCommandRule(String cmd, @Nullable String revertCommand) {
         mCmd = cmd;
+        mRevertCommand = revertCommand;
     }
 
     @Override
     public Statement apply(Statement base, Description description) {
-        return new MyStatement(base, mCmd);
-    }
-
-    public static void runShellCommand(String command) throws IOException {
-        ParcelFileDescriptor pfd = InstrumentationRegistry.getInstrumentation().getUiAutomation()
-                .executeShellCommand(command);
-
-        // Read the input stream fully.
-        FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
-        while (fis.read() != -1);
-        fis.close();
-    }
-
-    private static class MyStatement extends Statement {
-        private final Statement mBase;
-        private final String mCmd;
-
-        public MyStatement(Statement base, String cmd) {
-            mBase = base;
-            mCmd = cmd;
-        }
-
-        @Override
-        public void evaluate() throws Throwable {
-            runShellCommand(mCmd);
-            mBase.evaluate();
-        }
+        return new Statement() {
+            @Override
+            public void evaluate() throws Throwable {
+                UiDevice.getInstance(getInstrumentation()).executeShellCommand(mCmd);
+                try {
+                    base.evaluate();
+                } finally {
+                    if (mRevertCommand != null) {
+                        UiDevice.getInstance(getInstrumentation()).executeShellCommand(mRevertCommand);
+                    }
+                }
+            }
+        };
     }
 
     /**
@@ -74,17 +65,26 @@
      */
     public static ShellCommandRule grandWidgetBind() {
         return new ShellCommandRule("appwidget grantbind --package "
-                + InstrumentationRegistry.getTargetContext().getPackageName());
+                + InstrumentationRegistry.getTargetContext().getPackageName(), null);
     }
 
     /**
      * Sets the target launcher as default launcher.
      */
     public static ShellCommandRule setDefaultLauncher() {
-        ActivityInfo launcher = InstrumentationRegistry.getTargetContext().getPackageManager()
-                .queryIntentActivities(LauncherActivityRule.getHomeIntent(), 0).get(0)
-                .activityInfo;
-        return new ShellCommandRule("cmd package set-home-activity " +
-                new ComponentName(launcher.packageName, launcher.name).flattenToString());
+        return new ShellCommandRule(getLauncherCommand(getLauncherInMyProcess()), null);
+    }
+
+    public static String getLauncherCommand(ActivityInfo launcher) {
+        return "cmd package set-home-activity " +
+                new ComponentName(launcher.packageName, launcher.name).flattenToString();
+    }
+
+    /**
+     * Disables heads up notification for the duration of the test
+     */
+    public static ShellCommandRule disableHeadsUpNotification() {
+        return new ShellCommandRule("settings put global heads_up_notifications_enabled 0",
+                "settings put global heads_up_notifications_enabled 1");
     }
 }
diff --git a/tests/tapl/com/android/launcher3/tapl/AppIcon.java b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
index a11f6df..b7ae9f1 100644
--- a/tests/tapl/com/android/launcher3/tapl/AppIcon.java
+++ b/tests/tapl/com/android/launcher3/tapl/AppIcon.java
@@ -42,20 +42,8 @@
     /**
      * Clicks the icon to launch its app.
      */
-    @Deprecated
-    public Background launch() {
-        LauncherInstrumentation.log("AppIcon.launch before click");
-        LauncherInstrumentation.assertTrue(
-                "Launching an app didn't open a new window: " + mIcon.getText(),
-                mIcon.clickAndWait(Until.newWindow(), LauncherInstrumentation.WAIT_TIME_MS));
-        return new Background(mLauncher);
-    }
-
-    /**
-     * Clicks the icon to launch its app.
-     */
     public Background launch(String packageName) {
-        LauncherInstrumentation.log("AppIcon.launch before click");
+        LauncherInstrumentation.log("AppIcon.launch before click " + mIcon.getVisibleCenter());
         LauncherInstrumentation.assertTrue(
                 "Launching an app didn't open a new window: " + mIcon.getText(),
                 mIcon.clickAndWait(Until.newWindow(), LauncherInstrumentation.WAIT_TIME_MS));
diff --git a/tests/tapl/com/android/launcher3/tapl/Background.java b/tests/tapl/com/android/launcher3/tapl/Background.java
index 1aef979..27e0954 100644
--- a/tests/tapl/com/android/launcher3/tapl/Background.java
+++ b/tests/tapl/com/android/launcher3/tapl/Background.java
@@ -16,10 +16,21 @@
 
 package com.android.launcher3.tapl;
 
+import static com.android.launcher3.tapl.LauncherInstrumentation.WAIT_TIME_MS;
+import static com.android.launcher3.tapl.TestHelpers.getOverviewPackageName;
+
+import static org.junit.Assert.assertTrue;
+
+import androidx.annotation.NonNull;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
+
 /**
- * Operations on a state when Launcher is inactive because some other app is active.
+ * Indicates the base state with a UI other than Overview running as foreground. It can also
+ * indicate Launcher as long as Launcher is not in Overview state.
  */
-public final class Background extends Home {
+public class Background extends LauncherInstrumentation.VisibleContainer {
 
     Background(LauncherInstrumentation launcher) {
         super(launcher);
@@ -29,4 +40,33 @@
     protected LauncherInstrumentation.ContainerType getContainerType() {
         return LauncherInstrumentation.ContainerType.BACKGROUND;
     }
+
+    /**
+     * Swipes up or presses the square button to switch to Overview.
+     * Returns the base overview, which can be either in Launcher or the fallback recents.
+     *
+     * @return the Overview panel object.
+     */
+    @NonNull
+    public BaseOverview switchToOverview() {
+        verifyActiveContainer();
+        goToOverviewUnchecked();
+        assertTrue("Overview not visible", mLauncher.getDevice().wait(
+                Until.hasObject(By.pkg(getOverviewPackageName())), WAIT_TIME_MS));
+        return new BaseOverview(mLauncher);
+    }
+
+
+    protected void goToOverviewUnchecked() {
+        if (mLauncher.isSwipeUpEnabled()) {
+            final int height = mLauncher.getDevice().getDisplayHeight();
+            final UiObject2 navBar = mLauncher.getSystemUiObject("navigation_bar_frame");
+
+            mLauncher.swipe(
+                    navBar.getVisibleBounds().centerX(), navBar.getVisibleBounds().centerY(),
+                    navBar.getVisibleBounds().centerX(), height - 300);
+        } else {
+            mLauncher.getSystemUiObject("recent_apps").click();
+        }
+    }
 }
diff --git a/tests/tapl/com/android/launcher3/tapl/BaseOverview.java b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
new file mode 100644
index 0000000..4fce211
--- /dev/null
+++ b/tests/tapl/com/android/launcher3/tapl/BaseOverview.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.launcher3.tapl;
+
+import java.util.Collections;
+import java.util.List;
+
+import androidx.annotation.NonNull;
+import androidx.test.uiautomator.Direction;
+import androidx.test.uiautomator.UiObject2;
+
+/**
+ * Common overview pane for both Launcher and fallback recents
+ */
+public class BaseOverview extends LauncherInstrumentation.VisibleContainer {
+    private static final int DEFAULT_FLING_SPEED = 15000;
+
+    BaseOverview(LauncherInstrumentation launcher) {
+        super(launcher);
+    }
+
+    @Override
+    protected LauncherInstrumentation.ContainerType getContainerType() {
+        return LauncherInstrumentation.ContainerType.BASE_OVERVIEW;
+    }
+
+    /**
+     * Flings forward (left) and waits the fling's end.
+     */
+    public void flingForward() {
+        final UiObject2 overview = verifyActiveContainer();
+        LauncherInstrumentation.log("Overview.flingForward before fling");
+        overview.fling(Direction.LEFT, DEFAULT_FLING_SPEED);
+        mLauncher.waitForIdle();
+        verifyActiveContainer();
+    }
+
+    /**
+     * Flings backward (right) and waits the fling's end.
+     */
+    public void flingBackward() {
+        final UiObject2 overview = verifyActiveContainer();
+        LauncherInstrumentation.log("Overview.flingBackward before fling");
+        overview.fling(Direction.RIGHT, DEFAULT_FLING_SPEED);
+        mLauncher.waitForIdle();
+        verifyActiveContainer();
+    }
+
+    /**
+     * Gets the current task in the carousel, or fails if the carousel is empty.
+     *
+     * @return the task in the middle of the visible tasks list.
+     */
+    @NonNull
+    public OverviewTask getCurrentTask() {
+        verifyActiveContainer();
+        final List<UiObject2> taskViews = mLauncher.getDevice().findObjects(
+                LauncherInstrumentation.getLauncherObjectSelector("snapshot"));
+        LauncherInstrumentation.assertNotEquals("Unable to find a task", 0, taskViews.size());
+
+        // taskViews contains up to 3 task views: the 'main' (having the widest visible
+        // part) one in the center, and parts of its right and left siblings. Find the
+        // main task view by its width.
+        final UiObject2 widestTask = Collections.max(taskViews,
+                (t1, t2) -> Integer.compare(t1.getVisibleBounds().width(),
+                        t2.getVisibleBounds().width()));
+
+        return new OverviewTask(mLauncher, widestTask, this);
+    }
+}
\ No newline at end of file
diff --git a/tests/tapl/com/android/launcher3/tapl/Home.java b/tests/tapl/com/android/launcher3/tapl/Home.java
index 815a63e..522ce14 100644
--- a/tests/tapl/com/android/launcher3/tapl/Home.java
+++ b/tests/tapl/com/android/launcher3/tapl/Home.java
@@ -16,8 +16,6 @@
 
 package com.android.launcher3.tapl;
 
-import androidx.test.uiautomator.UiObject2;
-
 import androidx.annotation.NonNull;
 
 /**
@@ -28,33 +26,28 @@
  * that essentially represents these two activity states. Any gestures (e.g., switchToOverview) that
  * can be performed in both of these states can be defined here.
  */
-public abstract class Home extends LauncherInstrumentation.VisibleContainer {
+public abstract class Home extends Background {
 
     protected Home(LauncherInstrumentation launcher) {
         super(launcher);
         verifyActiveContainer();
     }
 
+    @Override
+    protected LauncherInstrumentation.ContainerType getContainerType() {
+        return LauncherInstrumentation.ContainerType.WORKSPACE;
+    }
+
     /**
      * Swipes up or presses the square button to switch to Overview.
      *
      * @return the Overview panel object.
      */
     @NonNull
+    @Override
     public Overview switchToOverview() {
         verifyActiveContainer();
-        if (mLauncher.isSwipeUpEnabled()) {
-            final int height = mLauncher.getDevice().getDisplayHeight();
-            final UiObject2 navBar = mLauncher.getSystemUiObject("navigation_bar_frame");
-
-            mLauncher.swipe(
-                    navBar.getVisibleBounds().centerX(), navBar.getVisibleBounds().centerY(),
-                    navBar.getVisibleBounds().centerX(), height - 300
-            );
-        } else {
-            mLauncher.getSystemUiObject("recent_apps").click();
-        }
-
+        goToOverviewUnchecked();
         return new Overview(mLauncher);
     }
 }
\ No newline at end of file
diff --git a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
index 66dfe41..31abc53 100644
--- a/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
+++ b/tests/tapl/com/android/launcher3/tapl/LauncherInstrumentation.java
@@ -28,13 +28,6 @@
 import android.view.Surface;
 import android.view.accessibility.AccessibilityEvent;
 
-import androidx.annotation.NonNull;
-import androidx.test.uiautomator.By;
-import androidx.test.uiautomator.BySelector;
-import androidx.test.uiautomator.UiDevice;
-import androidx.test.uiautomator.UiObject2;
-import androidx.test.uiautomator.Until;
-
 import com.android.launcher3.TestProtocol;
 import com.android.quickstep.SwipeUpSetting;
 
@@ -43,6 +36,13 @@
 import java.lang.ref.WeakReference;
 import java.util.concurrent.TimeoutException;
 
+import androidx.annotation.NonNull;
+import androidx.test.uiautomator.By;
+import androidx.test.uiautomator.BySelector;
+import androidx.test.uiautomator.UiDevice;
+import androidx.test.uiautomator.UiObject2;
+import androidx.test.uiautomator.Until;
+
 /**
  * The main tapl object. The only object that can be explicitly constructed by the using code. It
  * produces all other objects.
@@ -54,7 +54,7 @@
     // Types for launcher containers that the user is interacting with. "Background" is a
     // pseudo-container corresponding to inactive launcher covered by another app.
     enum ContainerType {
-        WORKSPACE, ALL_APPS, OVERVIEW, WIDGETS, BACKGROUND
+        WORKSPACE, ALL_APPS, OVERVIEW, WIDGETS, BACKGROUND, BASE_OVERVIEW
     }
 
     // Base class for launcher containers.
@@ -84,7 +84,7 @@
     private static final String OVERVIEW_RES_ID = "overview_panel";
     private static final String WIDGETS_RES_ID = "widgets_list_view";
     static final String LAUNCHER_PKG = "com.google.android.apps.nexuslauncher";
-    static final int WAIT_TIME_MS = 60000;
+    public static final int WAIT_TIME_MS = 60000;
     private static final String SYSTEMUI_PACKAGE = "com.android.systemui";
 
     private static WeakReference<VisibleContainer> sActiveContainer = new WeakReference<>(null);
@@ -112,11 +112,8 @@
         // Launcher should run in test harness so that custom accessibility protocol between
         // Launcher and TAPL is enabled. In-process tests enable this protocol with a direct call
         // into Launcher.
-        final boolean isInLauncherProcess =
-                instrumentation.getTargetContext().getPackageName().equals(
-                        UiDevice.getInstance(instrumentation).getLauncherPackageName());
         assertTrue("Device must run in a test harness",
-                isInLauncherProcess || ActivityManager.isRunningInTestHarness());
+                TestHelpers.isInLauncherProcess() || ActivityManager.isRunningInTestHarness());
     }
 
     // Used only by TaplTests.
@@ -203,8 +200,12 @@
                 } else {
                     waitUntilGone(APPS_RES_ID);
                 }
+                // Fall through
+            }
+            case BASE_OVERVIEW: {
                 waitUntilGone(WORKSPACE_RES_ID);
                 waitUntilGone(WIDGETS_RES_ID);
+
                 return waitForLauncherObject(OVERVIEW_RES_ID);
             }
             case BACKGROUND: {
@@ -310,6 +311,17 @@
     }
 
     /**
+     * Gets the Base overview object if either Launcher is in overview state or the fallback
+     * overview activity is showing. Fails otherwise.
+     *
+     * @return BaseOverview object.
+     */
+    @NonNull
+    public BaseOverview getBaseOverview() {
+        return new BaseOverview(this);
+    }
+
+    /**
      * Gets the All Apps object if the current state is showing the all apps panel opened by swiping
      * from workspace. Fails if the launcher is not in that state. Please don't call this method if
      * App Apps was opened by swiping up from Overview, as it won't fail and will return an
diff --git a/tests/tapl/com/android/launcher3/tapl/Overview.java b/tests/tapl/com/android/launcher3/tapl/Overview.java
index 9841274..9e0c07f 100644
--- a/tests/tapl/com/android/launcher3/tapl/Overview.java
+++ b/tests/tapl/com/android/launcher3/tapl/Overview.java
@@ -18,18 +18,15 @@
 
 import android.graphics.Point;
 
-import androidx.annotation.NonNull;
-import androidx.test.uiautomator.Direction;
-import androidx.test.uiautomator.UiObject2;
+import com.android.launcher3.tapl.LauncherInstrumentation.ContainerType;
 
-import java.util.Collections;
-import java.util.List;
+import androidx.annotation.NonNull;
+import androidx.test.uiautomator.UiObject2;
 
 /**
  * Overview pane.
  */
-public final class Overview extends LauncherInstrumentation.VisibleContainer {
-    private static final int DEFAULT_FLING_SPEED = 15000;
+public final class Overview extends BaseOverview {
 
     Overview(LauncherInstrumentation launcher) {
         super(launcher);
@@ -37,55 +34,11 @@
     }
 
     @Override
-    protected LauncherInstrumentation.ContainerType getContainerType() {
+    protected ContainerType getContainerType() {
         return LauncherInstrumentation.ContainerType.OVERVIEW;
     }
 
     /**
-     * Flings forward (left) and waits the fling's end.
-     */
-    public void flingForward() {
-        final UiObject2 overview = verifyActiveContainer();
-        LauncherInstrumentation.log("Overview.flingForward before fling");
-        overview.fling(Direction.LEFT, DEFAULT_FLING_SPEED);
-        mLauncher.waitForIdle();
-        verifyActiveContainer();
-    }
-
-    /**
-     * Flings backward (right) and waits the fling's end.
-     */
-    public void flingBackward() {
-        final UiObject2 overview = verifyActiveContainer();
-        LauncherInstrumentation.log("Overview.flingBackward before fling");
-        overview.fling(Direction.RIGHT, DEFAULT_FLING_SPEED);
-        mLauncher.waitForIdle();
-        verifyActiveContainer();
-    }
-
-    /**
-     * Gets the current task in the carousel, or fails if the carousel is empty.
-     *
-     * @return the task in the middle of the visible tasks list.
-     */
-    @NonNull
-    public OverviewTask getCurrentTask() {
-        verifyActiveContainer();
-        final List<UiObject2> taskViews = mLauncher.getDevice().findObjects(
-                LauncherInstrumentation.getLauncherObjectSelector("snapshot"));
-        LauncherInstrumentation.assertNotEquals("Unable to find a task", 0, taskViews.size());
-
-        // taskViews contains up to 3 task views: the 'main' (having the widest visible
-        // part) one in the center, and parts of its right and left siblings. Find the
-        // main task view by its width.
-        final UiObject2 widestTask = Collections.max(taskViews,
-                (t1, t2) -> Integer.compare(t1.getVisibleBounds().width(),
-                        t2.getVisibleBounds().width()));
-
-        return new OverviewTask(mLauncher, widestTask, this);
-    }
-
-    /**
      * Swipes up to All Apps.
      *
      * @return the App Apps object.
diff --git a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
index 2b67cc0..48686c4 100644
--- a/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
+++ b/tests/tapl/com/android/launcher3/tapl/OverviewTask.java
@@ -26,9 +26,9 @@
 public final class OverviewTask {
     private final LauncherInstrumentation mLauncher;
     private final UiObject2 mTask;
-    private final Overview mOverview;
+    private final BaseOverview mOverview;
 
-    OverviewTask(LauncherInstrumentation launcher, UiObject2 task, Overview overview) {
+    OverviewTask(LauncherInstrumentation launcher, UiObject2 task, BaseOverview overview) {
         mLauncher = launcher;
         mTask = task;
         mOverview = overview;
diff --git a/tests/tapl/com/android/launcher3/tapl/TestHelpers.java b/tests/tapl/com/android/launcher3/tapl/TestHelpers.java
new file mode 100644
index 0000000..93554d2
--- /dev/null
+++ b/tests/tapl/com/android/launcher3/tapl/TestHelpers.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License. You may obtain a copy of
+ * the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations under
+ * the License.
+ */
+
+package com.android.launcher3.tapl;
+
+import static androidx.test.InstrumentationRegistry.getInstrumentation;
+import static androidx.test.InstrumentationRegistry.getTargetContext;
+
+import android.app.Instrumentation;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ResolveInfo;
+import android.content.res.Resources;
+
+import java.util.List;
+
+public class TestHelpers {
+
+    private static Boolean sIsInLauncherProcess;
+
+    public static boolean isInLauncherProcess() {
+        if (sIsInLauncherProcess == null) {
+            sIsInLauncherProcess = initIsInLauncherProcess();
+        }
+        return sIsInLauncherProcess;
+    }
+
+    private static boolean initIsInLauncherProcess() {
+        ActivityInfo info = getLauncherInMyProcess();
+
+        // If we are in the same process, we can instantiate the class name.
+        try {
+            Class launcherClazz = Class.forName("com.android.launcher3.Launcher");
+            return launcherClazz.isAssignableFrom(Class.forName(info.name));
+        } catch (Exception e) {
+            return false;
+        }
+    }
+
+    public static Intent getHomeIntentInPackage(Context context) {
+        return new Intent(Intent.ACTION_MAIN)
+                .addCategory(Intent.CATEGORY_HOME)
+                .setPackage(context.getPackageName())
+                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+    }
+
+    public static ActivityInfo getLauncherInMyProcess() {
+        Instrumentation instrumentation = getInstrumentation();
+        if (instrumentation.getTargetContext() == null) {
+            return null;
+        }
+
+        List<ResolveInfo> launchers = getTargetContext().getPackageManager()
+                .queryIntentActivities(getHomeIntentInPackage(getTargetContext()), 0);
+        if (launchers.size() != 1) {
+            return null;
+        }
+        return launchers.get(0).activityInfo;
+    }
+
+    public static String getOverviewPackageName() {
+        Resources res = Resources.getSystem();
+        int id = res.getIdentifier("config_recentsComponentName", "string", "android");
+        if (id != 0) {
+            return ComponentName.unflattenFromString(res.getString(id)).getPackageName();
+        }
+        return "com.android.systemui";
+    }
+}
diff --git a/tests/tapl/com/android/launcher3/tapl/Workspace.java b/tests/tapl/com/android/launcher3/tapl/Workspace.java
index f5b01ee..493f26a 100644
--- a/tests/tapl/com/android/launcher3/tapl/Workspace.java
+++ b/tests/tapl/com/android/launcher3/tapl/Workspace.java
@@ -38,11 +38,6 @@
         mHotseat = launcher.waitForLauncherObject("hotseat");
     }
 
-    @Override
-    protected LauncherInstrumentation.ContainerType getContainerType() {
-        return LauncherInstrumentation.ContainerType.WORKSPACE;
-    }
-
     /**
      * Swipes up to All Apps.
      *