Merge "Move device admin viewer/adder to specialaccess package."
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 8bd2581..7094d8e 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -2362,7 +2362,6 @@
             android:name="Settings$DataUsageSummaryActivity"
             android:label="@string/data_usage_summary_title"
             android:icon="@drawable/ic_settings_data_usage"
-            android:enabled="false"
             android:taskAffinity="com.android.settings"
             android:parentActivityName="Settings">
             <intent-filter android:priority="1">
diff --git a/res/layout/screen_zoom_preview_2.xml b/res/layout/screen_zoom_preview_2.xml
index b61f92a..2cfd9b7 100644
--- a/res/layout/screen_zoom_preview_2.xml
+++ b/res/layout/screen_zoom_preview_2.xml
@@ -17,4 +17,7 @@
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
+    android:padding="32dp"
+    android:numColumns="3"
+    android:gravity="center"
     android:importantForAccessibility="noHideDescendants" />
diff --git a/res/layout/screen_zoom_preview_app_icon.xml b/res/layout/screen_zoom_preview_app_icon.xml
index 7d7d983..087afb8 100644
--- a/res/layout/screen_zoom_preview_app_icon.xml
+++ b/res/layout/screen_zoom_preview_app_icon.xml
@@ -14,33 +14,28 @@
      limitations under the License.
 -->
 
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
-             android:layout_width="match_parent"
-             android:layout_height="wrap_content"
-             android:importantForAccessibility="noHideDescendants">
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:layout_gravity="center_horizontal|top"
+    android:gravity="center_horizontal"
+    android:orientation="vertical"
+    android:paddingTop="8dp">
 
-    <LinearLayout
-        android:layout_width="@dimen/screen_zoom_preview_app_icon_width"
+    <ImageView
+        android:id="@android:id/icon1"
+        android:layout_width="64dp"
+        android:layout_height="64dp"
+        android:layout_marginBottom="4dp"
+        android:scaleType="fitCenter" />
+
+    <TextView
+        android:id="@android:id/text1"
+        android:layout_width="match_parent"
         android:layout_height="wrap_content"
-        android:layout_gravity="center_horizontal|top"
-        android:gravity="center_horizontal"
-        android:orientation="vertical"
-        android:padding="8dp">
-
-        <ImageView
-            android:id="@android:id/icon1"
-            android:layout_width="64dp"
-            android:layout_height="64dp"
-            android:layout_marginBottom="4dp"
-            android:scaleType="fitCenter" />
-
-        <TextView
-            android:id="@android:id/text1"
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:ellipsize="end"
-            android:gravity="center_horizontal|top"
-            android:singleLine="true"
-            android:textAppearance="@android:style/TextAppearance.Material.Caption" />
-    </LinearLayout>
-</FrameLayout>
\ No newline at end of file
+        android:ellipsize="end"
+        android:gravity="center_horizontal|top"
+        android:singleLine="true"
+        android:textAppearance="@android:style/TextAppearance.Material.Caption" />
+</LinearLayout>
\ No newline at end of file
diff --git a/res/layout/usage_view.xml b/res/layout/usage_view.xml
index 16b4916..c24f289 100644
--- a/res/layout/usage_view.xml
+++ b/res/layout/usage_view.xml
@@ -80,8 +80,7 @@
             android:layout_width="0dp"
             android:layout_height="wrap_content"
             android:layout_weight="1"
-            android:orientation="horizontal"
-            android:layoutDirection="ltr">
+            android:orientation="horizontal">
             <include android:id="@+id/label_start"
                      layout="@layout/usage_side_label" />
 
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index 08160ba..30d1e6c 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -251,7 +251,6 @@
     <dimen name="unmount_button_padding">8dp</dimen>
 
     <!-- Display, Screen zoom -->
-    <dimen name="screen_zoom_preview_app_icon_width">88dp</dimen>
     <dimen name="conversation_message_list_padding">10dp</dimen>
     <dimen name="conversation_message_contact_icon_text_size">32sp</dimen>
     <dimen name="conversation_message_text_size">16sp</dimen>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 51ec590..f0394c9 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -289,7 +289,7 @@
     <string name="bluetooth_notif_message">Tap to pair with <xliff:g id="device_name">%1$s</xliff:g>.</string>
     <!-- Item in bluetooth settings screen, used to show the list of received files [CHAR LIMIT=30] -->
     <string name="bluetooth_show_received_files">Received files</string>
-    <!-- Item in bluetooth settings screen, used to show the list of Files received via Bluetooth [CHAR LIMIT=30] -->
+    <!-- Item in bluetooth settings screen, used to show the list of Files received via Bluetooth [CHAR LIMIT=NONE] -->
     <string name="bluetooth_show_files_received_via_bluetooth">Files received via Bluetooth</string>
 
     <!-- Strings for BluetoothDevicePicker [CHAR LIMIT=40]-->
@@ -6999,6 +6999,9 @@
     <string name="keywords_model_and_hardware">serial number, hardware version</string>
     <string name="keywords_android_version">android security patch level, baseband version, kernel version</string>
 
+    <!-- Search keyword for Device Theme Settings [CHAR LIMIT=NONE] -->
+    <string name="keywords_systemui_theme">dark theme</string>
+
     <!-- Search keyword for Send Device Feedback Setting [CHAR LIMIT=NONE] -->
     <string name="keywords_device_feedback">bug</string>
 
diff --git a/res/xml/battery_saver_settings.xml b/res/xml/battery_saver_settings.xml
index 0460459..eb4954f 100644
--- a/res/xml/battery_saver_settings.xml
+++ b/res/xml/battery_saver_settings.xml
@@ -29,8 +29,8 @@
     <com.android.settings.widget.SeekBarPreference
         android:key="battery_saver_seek_bar"
         android:title="@string/battery_saver_seekbar_title_placeholder"
-        android:max="75"
-        android:min="5" />
+        android:max="15"
+        android:min="1" />
 
     <com.android.settings.widget.TwoStateButtonPreference
         android:key="battery_saver"
diff --git a/res/xml/display_settings.xml b/res/xml/display_settings.xml
index 683abd3..87d422f 100644
--- a/res/xml/display_settings.xml
+++ b/res/xml/display_settings.xml
@@ -141,7 +141,8 @@
         android:title="@string/device_theme"
         android:entries="@array/systemui_theme_entries"
         android:entryValues="@array/systemui_theme_values"
-        settings:controller="com.android.settings.display.SystemUiThemePreferenceController" />
+        settings:controller="com.android.settings.display.SystemUiThemePreferenceController"
+        settings:keywords="@string/keywords_systemui_theme" />
 
     <Preference
         android:key="vr_display_pref"
diff --git a/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java b/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
index 7107ff7..4498225 100755
--- a/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
+++ b/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
@@ -19,9 +19,6 @@
 import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
 
 import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.DialogFragment;
 import android.app.admin.DevicePolicyManager;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -95,10 +92,6 @@
     static final int LOADER_STORAGE = 3;
     static final int LOADER_BATTERY = 4;
 
-    // Dialog identifiers used in showDialog
-    private static final int DLG_BASE = 0;
-    static final int DLG_CLEAR_INSTANT_APP = DLG_BASE + 1;
-
     public static final String ARG_PACKAGE_NAME = "package";
     public static final String ARG_PACKAGE_UID = "uid";
 
@@ -419,7 +412,9 @@
         for (Callback callback : mCallbacks) {
             callback.refreshUi();
         }
-        mAppButtonsPreferenceController.refreshUi();
+        if (mAppButtonsPreferenceController.isAvailable()) {
+            mAppButtonsPreferenceController.refreshUi();
+        }
 
         if (!mInitialized) {
             // First time init: are we displaying an uninstalled app?
@@ -447,11 +442,6 @@
         return true;
     }
 
-    @VisibleForTesting
-    AlertDialog createDialog(int id, int errorCode) {
-        return mInstantAppButtonPreferenceController.createDialog(id);
-    }
-
     private void uninstallPkg(String packageName, boolean allUsers, boolean andDisable) {
         stopListeningToPackageRemove();
         // Create new intent to launch Uninstaller activity
@@ -561,12 +551,6 @@
         mFinishing = true;
     }
 
-    void showDialogInner(int id, int moveErrorCode) {
-        final DialogFragment newFragment = MyAlertDialogFragment.newInstance(id, moveErrorCode);
-        newFragment.setTargetFragment(this, 0);
-        newFragment.show(getFragmentManager(), "dialog " + id);
-    }
-
     @Override
     public void onRunningStateChanged(boolean running) {
         // No op.
@@ -604,37 +588,6 @@
         }
     }
 
-    public static class MyAlertDialogFragment extends InstrumentedDialogFragment {
-
-        private static final String ARG_ID = "id";
-
-        @Override
-        public int getMetricsCategory() {
-            return MetricsEvent.DIALOG_APP_INFO_ACTION;
-        }
-
-        @Override
-        public Dialog onCreateDialog(Bundle savedInstanceState) {
-            final int id = getArguments().getInt(ARG_ID);
-            final int errorCode = getArguments().getInt("moveError");
-            final Dialog dialog =
-                    ((AppInfoDashboardFragment) getTargetFragment()).createDialog(id, errorCode);
-            if (dialog == null) {
-                throw new IllegalArgumentException("unknown id " + id);
-            }
-            return dialog;
-        }
-
-        public static MyAlertDialogFragment newInstance(int id, int errorCode) {
-            final MyAlertDialogFragment dialogFragment = new MyAlertDialogFragment();
-            final Bundle args = new Bundle();
-            args.putInt(ARG_ID, id);
-            args.putInt("moveError", errorCode);
-            dialogFragment.setArguments(args);
-            return dialogFragment;
-        }
-    }
-
     @VisibleForTesting
     void startListeningToPackageRemove() {
         if (mListeningToPackageRemove) {
diff --git a/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java b/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
index a3f1bab..7198a54 100644
--- a/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
+++ b/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
@@ -1,3 +1,18 @@
+/*
+ * 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.settings.applications.appinfo;
 
 import android.app.AlertDialog;
diff --git a/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragment.java b/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragment.java
new file mode 100644
index 0000000..d010918
--- /dev/null
+++ b/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragment.java
@@ -0,0 +1,80 @@
+/*
+ * 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.settings.applications.appinfo;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.pm.PackageManager;
+import android.os.Bundle;
+import android.os.UserHandle;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
+import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
+import com.android.settings.overlay.FeatureFactory;
+
+/**
+ * Fragment to show the dialog for clearing the instant app.
+ */
+public class InstantAppButtonDialogFragment extends InstrumentedDialogFragment implements
+        DialogInterface.OnClickListener {
+
+    private static final String ARG_PACKAGE_NAME = "packageName";
+
+    private String mPackageName;
+
+    public static InstantAppButtonDialogFragment newInstance(String packageName) {
+        final InstantAppButtonDialogFragment dialogFragment = new InstantAppButtonDialogFragment();
+        final Bundle args = new Bundle(1);
+        args.putString(ARG_PACKAGE_NAME, packageName);
+        dialogFragment.setArguments(args);
+        return dialogFragment;
+    }
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsEvent.DIALOG_APP_INFO_ACTION;
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        final Bundle arguments = getArguments();
+        mPackageName = arguments.getString(ARG_PACKAGE_NAME);
+        return createDialog();
+    }
+
+    @Override
+    public void onClick(DialogInterface dialog, int which) {
+        final Context context = getContext();
+        final PackageManager packageManager = context.getPackageManager();
+        FeatureFactory.getFactory(context).getMetricsFeatureProvider()
+            .action(context, MetricsEvent.ACTION_SETTINGS_CLEAR_INSTANT_APP, mPackageName);
+        packageManager.deletePackageAsUser(mPackageName, null, 0, UserHandle.myUserId());
+    }
+
+    private AlertDialog createDialog() {
+        AlertDialog confirmDialog = new AlertDialog.Builder(getContext())
+            .setPositiveButton(R.string.clear_instant_app_data, this)
+            .setNegativeButton(R.string.cancel, null)
+            .setTitle(R.string.clear_instant_app_data)
+            .setMessage(R.string.clear_instant_app_confirmation)
+            .create();
+        return confirmDialog;
+    }
+
+}
+
diff --git a/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceController.java b/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceController.java
index 4d1dfd9..8498669 100644
--- a/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceController.java
+++ b/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceController.java
@@ -16,15 +16,13 @@
 
 package com.android.settings.applications.appinfo;
 
-import android.app.AlertDialog;
+import android.app.DialogFragment;
 import android.content.Context;
-import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
 import android.os.Bundle;
-import android.os.UserHandle;
 
 import androidx.preference.PreferenceScreen;
 import android.text.TextUtils;
@@ -34,12 +32,10 @@
 import android.view.View;
 import android.widget.Button;
 
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
 import com.android.settings.R;
 import com.android.settings.applications.AppStoreUtil;
 import com.android.settings.applications.LayoutPreference;
 import com.android.settings.core.BasePreferenceController;
-import com.android.settings.overlay.FeatureFactory;
 import com.android.settingslib.applications.AppUtils;
 import com.android.settingslib.core.lifecycle.Lifecycle;
 import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -50,15 +46,13 @@
 import java.util.List;
 
 public class InstantAppButtonsPreferenceController extends BasePreferenceController implements
-        LifecycleObserver, OnCreateOptionsMenu, OnPrepareOptionsMenu, OnOptionsItemSelected,
-        DialogInterface.OnClickListener {
+        LifecycleObserver, OnCreateOptionsMenu, OnPrepareOptionsMenu, OnOptionsItemSelected {
 
     private static final String KEY_INSTANT_APP_BUTTONS = "instant_app_buttons";
     private static final String META_DATA_DEFAULT_URI = "default-url";
 
     private final AppInfoDashboardFragment mParent;
     private final String mPackageName;
-    private final PackageManager mPackageManager;
     private String mLaunchUri;
     private LayoutPreference mPreference;
     private MenuItem mInstallMenu;
@@ -68,7 +62,6 @@
         super(context, KEY_INSTANT_APP_BUTTONS);
         mParent = parent;
         mPackageName = packageName;
-        mPackageManager = context.getPackageManager();
         mLaunchUri = getDefaultLaunchUri();
         if (lifecycle != null) {
             lifecycle.addObserver(this);
@@ -118,27 +111,6 @@
         }
     }
 
-    @Override
-    public void onClick(DialogInterface dialog, int which) {
-        FeatureFactory.getFactory(mContext).getMetricsFeatureProvider()
-            .action(mContext, MetricsEvent.ACTION_SETTINGS_CLEAR_INSTANT_APP, mPackageName);
-        mPackageManager.deletePackageAsUser(
-            mPackageName, null, 0, UserHandle.myUserId());
-    }
-
-    AlertDialog createDialog(int id) {
-        if (id == AppInfoDashboardFragment.DLG_CLEAR_INSTANT_APP) {
-            AlertDialog confirmDialog = new AlertDialog.Builder(mContext)
-                .setPositiveButton(R.string.clear_instant_app_data, this)
-                .setNegativeButton(R.string.cancel, null)
-                .setTitle(R.string.clear_instant_app_data)
-                .setMessage(mContext.getString(R.string.clear_instant_app_confirmation))
-                .create();
-            return confirmDialog;
-        }
-        return null;
-    }
-
     private void initButtons(View view) {
         final Button installButton = view.findViewById(R.id.install);
         final Button clearDataButton = view.findViewById(R.id.clear_data);
@@ -160,8 +132,14 @@
                 installButton.setEnabled(false);
             }
         }
-        clearDataButton.setOnClickListener(
-            v -> mParent.showDialogInner(mParent.DLG_CLEAR_INSTANT_APP, 0));
+        clearDataButton.setOnClickListener(v -> showDialog());
+    }
+
+    private void showDialog() {
+        final DialogFragment newFragment =
+            InstantAppButtonDialogFragment.newInstance(mPackageName);
+        newFragment.setTargetFragment(mParent, 0);
+        newFragment.show(mParent.getFragmentManager(), KEY_INSTANT_APP_BUTTONS);
     }
 
     private String getDefaultLaunchUri() {
diff --git a/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java b/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
index c243970..1cb7985 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
@@ -17,11 +17,9 @@
 package com.android.settings.applications.defaultapps;
 
 import android.content.Context;
-import android.content.pm.ComponentInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 
-import android.util.ArraySet;
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.R;
 
@@ -29,7 +27,6 @@
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Set;
 
 /**
  * Fragment for choosing default browser.
@@ -61,24 +58,13 @@
         final List<DefaultAppInfo> candidates = new ArrayList<>();
         final Context context = getContext();
         // Resolve that intent and check that the handleAllWebDataURI boolean is set
-        final List<ResolveInfo> list = mPm.queryIntentActivitiesAsUser(
-                DefaultBrowserPreferenceController.BROWSE_PROBE, PackageManager.MATCH_ALL, mUserId);
+        final List<ResolveInfo> list =
+            DefaultBrowserPreferenceController.getCandidates(mPm, mUserId);
 
-        final int count = list.size();
-        final Set<String> addedPackages = new ArraySet<>();
-        for (int i = 0; i < count; i++) {
-            ResolveInfo info = list.get(i);
-            if (info.activityInfo == null || !info.handleAllWebDataURI) {
-                continue;
-            }
-            final String packageName = info.activityInfo.packageName;
-            if (addedPackages.contains(packageName)) {
-                continue;
-            }
+        for (ResolveInfo info : list) {
             try {
                 candidates.add(new DefaultAppInfo(context, mPm,
-                        mPm.getApplicationInfoAsUser(packageName, 0, mUserId)));
-                addedPackages.add(packageName);
+                        mPm.getApplicationInfoAsUser(info.activityInfo.packageName, 0, mUserId)));
             } catch (PackageManager.NameNotFoundException e) {
                 // Skip unknown packages.
             }
diff --git a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
index 5395be9..d4e86ff 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
@@ -26,12 +26,15 @@
 import android.net.Uri;
 import androidx.preference.Preference;
 import android.text.TextUtils;
+import android.util.ArraySet;
 import android.util.IconDrawableFactory;
 import android.util.Log;
 
 import com.android.settingslib.applications.DefaultAppInfo;
 
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Set;
 
 public class DefaultBrowserPreferenceController extends DefaultAppPreferenceController {
 
@@ -48,7 +51,7 @@
 
     @Override
     public boolean isAvailable() {
-        final List<ResolveInfo> candidates = getCandidates();
+        final List<ResolveInfo> candidates = getCandidates(mPackageManager, mUserId);
         return candidates != null && !candidates.isEmpty();
     }
 
@@ -103,14 +106,31 @@
         return getOnlyAppIcon();
     }
 
-    private List<ResolveInfo> getCandidates() {
-        return mPackageManager.queryIntentActivitiesAsUser(BROWSE_PROBE, PackageManager.MATCH_ALL,
-                mUserId);
+    static List<ResolveInfo> getCandidates(PackageManager packageManager, int userId) {
+        final List<ResolveInfo> candidates = new ArrayList<>();
+        // Resolve that intent and check that the handleAllWebDataURI boolean is set
+        final List<ResolveInfo> list = packageManager.queryIntentActivitiesAsUser(
+            BROWSE_PROBE, PackageManager.MATCH_ALL, userId);
+        if (list != null) {
+            final Set<String> addedPackages = new ArraySet<>();
+            for (ResolveInfo info : list) {
+                if (info.activityInfo == null || !info.handleAllWebDataURI) {
+                    continue;
+                }
+                final String packageName = info.activityInfo.packageName;
+                if (addedPackages.contains(packageName)) {
+                    continue;
+                }
+                candidates.add(info);
+                addedPackages.add(packageName);
+            }
+        }
+        return candidates;
     }
 
     private String getOnlyAppLabel() {
         // Resolve that intent and check that the handleAllWebDataURI boolean is set
-        final List<ResolveInfo> list = getCandidates();
+        final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
         if (list != null && list.size() == 1) {
             final ResolveInfo info = list.get(0);
             final String label = info.loadLabel(mPackageManager).toString();
@@ -123,7 +143,7 @@
     }
 
     private Drawable getOnlyAppIcon() {
-        final List<ResolveInfo> list = getCandidates();
+        final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
         if (list != null && list.size() == 1) {
             final ResolveInfo info = list.get(0);
             final ComponentInfo cn = info.getComponentInfo();
diff --git a/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java b/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
index aa0b6cd..654ea72 100644
--- a/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
+++ b/src/com/android/settings/connecteddevice/ConnectedDeviceGroupController.java
@@ -76,9 +76,11 @@
             mPreferenceGroup = (PreferenceGroup) screen.findPreference(KEY);
             mPreferenceGroup.setVisible(false);
 
-            mBluetoothDeviceUpdater.setPrefContext(screen.getContext());
+            final Context context = screen.getContext();
+            mBluetoothDeviceUpdater.setPrefContext(context);
             mBluetoothDeviceUpdater.forceUpdate();
-            mConnectedUsbDeviceUpdater.initUsbPreference(screen.getContext());
+            mConnectedUsbDeviceUpdater.initUsbPreference(context);
+            mConnectedDockUpdater.setPreferenceContext(context);
             mConnectedDockUpdater.forceUpdate();
         }
     }
diff --git a/src/com/android/settings/connecteddevice/SavedDeviceGroupController.java b/src/com/android/settings/connecteddevice/SavedDeviceGroupController.java
index 4bc9cdd..6f9b7ac 100644
--- a/src/com/android/settings/connecteddevice/SavedDeviceGroupController.java
+++ b/src/com/android/settings/connecteddevice/SavedDeviceGroupController.java
@@ -75,8 +75,11 @@
         if (isAvailable()) {
             mPreferenceGroup = (PreferenceGroup) screen.findPreference(KEY);
             mPreferenceGroup.setVisible(false);
-            mBluetoothDeviceUpdater.setPrefContext(screen.getContext());
+
+            final Context context = screen.getContext();
+            mBluetoothDeviceUpdater.setPrefContext(context);
             mBluetoothDeviceUpdater.forceUpdate();
+            mSavedDockUpdater.setPreferenceContext(context);
             mSavedDockUpdater.forceUpdate();
         }
     }
diff --git a/src/com/android/settings/connecteddevice/dock/DockUpdater.java b/src/com/android/settings/connecteddevice/dock/DockUpdater.java
index 19ee732..99ac124 100644
--- a/src/com/android/settings/connecteddevice/dock/DockUpdater.java
+++ b/src/com/android/settings/connecteddevice/dock/DockUpdater.java
@@ -15,6 +15,7 @@
  */
 package com.android.settings.connecteddevice.dock;
 
+import android.annotation.NonNull;
 import android.content.Context;
 
 /**
@@ -40,4 +41,10 @@
      */
     default void forceUpdate() {
     }
+
+    /**
+     * Set the context to generate the {@link Preference}, so it could get the correct theme.
+     */
+    default void setPreferenceContext(@NonNull Context preferenceContext) {
+    }
 }
diff --git a/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java b/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
index 1a868b8..253bd2f 100644
--- a/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
+++ b/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
@@ -78,7 +78,7 @@
         LayoutInflater inflater = LayoutInflater.from(parent.getContext());
         switch(viewType) {
             case TYPE_HEADER: {
-                final View view = inflater.inflate(R.layout.preference_category_material_settings,
+                final View view = inflater.inflate(R.layout.preference_category_material,
                         parent, false);
                 return new HeaderViewHolder(view);
             }
diff --git a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
index 9604f74..0272b5c 100644
--- a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
+++ b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
@@ -402,10 +402,14 @@
         try {
             final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
 
+            // b/33117269: Note that launchIntent may launch activity in different task which set
+            // different launchMode (e.g. Files), using startActivityForesult to set task as
+            // source task, and set requestCode as 0 means don't care about returnCode currently.
             if (userId == -1) {
-                mFragment.startActivity(intent);
+                mFragment.startActivityForResult(intent, 0 /* requestCode not used */);
             } else {
-                mFragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
+                mFragment.getActivity().startActivityForResultAsUser(intent,
+                        0 /* requestCode not used */, new UserHandle(userId));
             }
         } catch (ActivityNotFoundException e) {
             Log.w(TAG, "No activity found for " + intent);
diff --git a/src/com/android/settings/display/AppGridView.java b/src/com/android/settings/display/AppGridView.java
index 0027537..d48eb09 100644
--- a/src/com/android/settings/display/AppGridView.java
+++ b/src/com/android/settings/display/AppGridView.java
@@ -22,7 +22,6 @@
 import android.content.pm.ResolveInfo;
 import android.graphics.drawable.Drawable;
 import android.os.UserHandle;
-import androidx.annotation.VisibleForTesting;
 import android.util.AttributeSet;
 import android.util.IconDrawableFactory;
 import android.view.View;
@@ -37,28 +36,32 @@
 import java.util.Collections;
 import java.util.List;
 
+import androidx.annotation.VisibleForTesting;
+
 public class AppGridView extends GridView {
     public AppGridView(Context context) {
-        this(context, null);
+        super(context);
+        init(context);
     }
 
     public AppGridView(Context context, AttributeSet attrs) {
-        this(context, attrs, 0);
+        super(context, attrs);
+        init(context);
     }
 
     public AppGridView(Context context, AttributeSet attrs, int defStyleAttr) {
-        this(context, attrs, defStyleAttr, 0);
+        super(context, attrs, defStyleAttr);
+        init(context);
     }
 
     public AppGridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleResId) {
         super(context, attrs, defStyleAttr, defStyleResId);
 
-        setNumColumns(AUTO_FIT);
+        init(context);
 
-        final int columnWidth = getResources().getDimensionPixelSize(
-                R.dimen.screen_zoom_preview_app_icon_width);
-        setColumnWidth(columnWidth);
+    }
 
+    private void init(Context context) {
         setAdapter(new AppsAdapter(context, R.layout.screen_zoom_preview_app_icon,
                 android.R.id.text1, android.R.id.icon1));
     }
@@ -105,6 +108,7 @@
         }
 
         private void loadAllApps() {
+            final int needAppCount = 6;
             final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
             mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
 
@@ -117,6 +121,9 @@
                 if (label != null) {
                     results.add(new ActivityEntry(info, label.toString(), iconFactory));
                 }
+                if (results.size() >= needAppCount) {
+                    break;
+                }
             }
 
             Collections.sort(results);
diff --git a/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java b/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
index b082eeb..379b995 100644
--- a/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
+++ b/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
@@ -43,6 +43,7 @@
 public class AutoBatterySeekBarPreferenceController extends BasePreferenceController implements
         LifecycleObserver, OnStart, OnStop, SeekBarPreference.OnPreferenceChangeListener {
     private static final String TAG = "AutoBatterySeekBarPreferenceController";
+    private static final int INTERVAL = 5;
     @VisibleForTesting
     static final String KEY_AUTO_BATTERY_SEEK_BAR = "battery_saver_seek_bar";
     private SeekBarPreference mPreference;
@@ -92,7 +93,7 @@
     public boolean onPreferenceChange(Preference preference, Object newValue) {
         final int progress = (int) newValue;
         Settings.Global.putInt(mContext.getContentResolver(),
-                Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, progress);
+                Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, progress * INTERVAL);
         return true;
     }
 
@@ -102,7 +103,7 @@
 
         // Override the max value with LOW_POWER_MODE_TRIGGER_LEVEL_MAX, if set.
         final int maxLevel = Settings.Global.getInt(contentResolver,
-                Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL_MAX, 0);
+                Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL_MAX, 0) / INTERVAL;
         if (maxLevel > 0) {
             if (!(preference instanceof SeekBarPreference)) {
                 Log.e(TAG, "Unexpected preference class: " + preference.getClass());
@@ -127,7 +128,7 @@
             preference.setTitle(mContext.getString(R.string.battery_saver_seekbar_title,
                     Utils.formatPercentage(level)));
             SeekBarPreference seekBarPreference = (SeekBarPreference) preference;
-            seekBarPreference.setProgress(level);
+            seekBarPreference.setProgress(level / INTERVAL);
             seekBarPreference.setSeekBarContentDescription(
                     mContext.getString(R.string.battery_saver_turn_on_automatically_title));
         }
diff --git a/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java b/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
index f7793aa..2dc35f1 100644
--- a/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
+++ b/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
@@ -157,7 +157,7 @@
                 metricsFeatureProvider.action(context,
                         MetricsProto.MetricsEvent.ACTION_ANOMALY_IGNORED,
                         packageName,
-                        Pair.create(MetricsProto.MetricsEvent.FIELD_CONTEXT,
+                        Pair.create(MetricsProto.MetricsEvent.FIELD_ANOMALY_TYPE,
                                 anomalyInfo.anomalyType),
                         Pair.create(MetricsProto.MetricsEvent.FIELD_APP_VERSION_CODE,
                                 versionCode));
diff --git a/src/com/android/settings/nfc/AndroidBeamPreferenceController.java b/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
index 12ab1b7..f99c47c 100644
--- a/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
+++ b/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
@@ -17,7 +17,6 @@
 
 import android.content.Context;
 import android.nfc.NfcAdapter;
-import androidx.preference.Preference;
 import androidx.preference.PreferenceScreen;
 
 import com.android.settings.core.BasePreferenceController;
@@ -26,15 +25,12 @@
 import com.android.settingslib.core.lifecycle.events.OnPause;
 import com.android.settingslib.core.lifecycle.events.OnResume;
 
-import java.util.List;
-
 public class AndroidBeamPreferenceController extends BasePreferenceController
         implements LifecycleObserver, OnResume, OnPause {
 
     public static final String KEY_ANDROID_BEAM_SETTINGS = "android_beam_settings";
     private final NfcAdapter mNfcAdapter;
     private AndroidBeamEnabler mAndroidBeamEnabler;
-    private NfcAirplaneModeObserver mAirplaneModeObserver;
 
     public AndroidBeamPreferenceController(Context context, String key) {
         super(context, key);
@@ -52,12 +48,6 @@
         final RestrictedPreference restrictedPreference =
                 (RestrictedPreference) screen.findPreference(getPreferenceKey());
         mAndroidBeamEnabler = new AndroidBeamEnabler(mContext, restrictedPreference);
-
-        // Manually set dependencies for NFC when not toggleable.
-        if (!NfcPreferenceController.isToggleableInAirplaneMode(mContext)) {
-            mAirplaneModeObserver = new NfcAirplaneModeObserver(mContext, mNfcAdapter,
-                    (Preference) restrictedPreference);
-        }
     }
 
     @Override
@@ -70,9 +60,6 @@
 
     @Override
     public void onResume() {
-        if (mAirplaneModeObserver != null) {
-            mAirplaneModeObserver.register();
-        }
         if (mAndroidBeamEnabler != null) {
             mAndroidBeamEnabler.resume();
         }
@@ -80,9 +67,6 @@
 
     @Override
     public void onPause() {
-        if (mAirplaneModeObserver != null) {
-            mAirplaneModeObserver.unregister();
-        }
         if (mAndroidBeamEnabler != null) {
             mAndroidBeamEnabler.pause();
         }
diff --git a/src/com/android/settings/nfc/BaseNfcEnabler.java b/src/com/android/settings/nfc/BaseNfcEnabler.java
index 88bafb9..64c6d15 100644
--- a/src/com/android/settings/nfc/BaseNfcEnabler.java
+++ b/src/com/android/settings/nfc/BaseNfcEnabler.java
@@ -28,7 +28,7 @@
  * preference. It will receive intent and update state to ensure preference show correct state.
  */
 public abstract class BaseNfcEnabler {
-    private final Context mContext;
+    protected final Context mContext;
     protected final NfcAdapter mNfcAdapter;
     private final IntentFilter mIntentFilter;
 
diff --git a/src/com/android/settings/nfc/NfcAirplaneModeObserver.java b/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
index d0ce045..65ac655 100644
--- a/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
+++ b/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
@@ -70,12 +70,13 @@
         }
 
         mAirplaneMode = airplaneMode;
-        boolean toggleable = mAirplaneMode != 1;
-        if (toggleable) {
-            mNfcAdapter.enable();
-        } else {
+        if (mAirplaneMode == 1) {
+            // airplane mode is on, need to turn off NFC, and check if user can toggle it
             mNfcAdapter.disable();
+            mPreference.setEnabled(NfcPreferenceController.isToggleableInAirplaneMode(mContext));
+        } else {
+            // airplane mode is off, no restriction
+            mPreference.setEnabled(true);
         }
-        mPreference.setEnabled(toggleable);
     }
 }
diff --git a/src/com/android/settings/nfc/NfcEnabler.java b/src/com/android/settings/nfc/NfcEnabler.java
index 507a053..777e7d1 100644
--- a/src/com/android/settings/nfc/NfcEnabler.java
+++ b/src/com/android/settings/nfc/NfcEnabler.java
@@ -18,8 +18,10 @@
 
 import android.content.Context;
 import android.nfc.NfcAdapter;
-import androidx.preference.SwitchPreference;
+import android.provider.Settings;
 
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.SwitchPreference;
 
 /**
  * NfcEnabler is a helper to manage the Nfc on/off checkbox preference. It turns on/off Nfc
@@ -38,7 +40,7 @@
         switch (newState) {
             case NfcAdapter.STATE_OFF:
                 mPreference.setChecked(false);
-                mPreference.setEnabled(true);
+                mPreference.setEnabled(isToggleable());
                 break;
             case NfcAdapter.STATE_ON:
                 mPreference.setChecked(true);
@@ -54,4 +56,15 @@
                 break;
         }
     }
+
+    @VisibleForTesting
+    boolean isToggleable() {
+        if (NfcPreferenceController.isToggleableInAirplaneMode(mContext)
+                || !NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)) {
+            return true;
+        }
+        final int airplaneMode = Settings.Global.getInt(
+                mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
+        return airplaneMode != 1;
+    }
 }
diff --git a/src/com/android/settings/nfc/NfcPreferenceController.java b/src/com/android/settings/nfc/NfcPreferenceController.java
index e1fa1b3..0f68a9c 100644
--- a/src/com/android/settings/nfc/NfcPreferenceController.java
+++ b/src/com/android/settings/nfc/NfcPreferenceController.java
@@ -20,7 +20,7 @@
 import android.nfc.NfcAdapter;
 import android.provider.Settings;
 
-import androidx.preference.Preference;
+import androidx.annotation.VisibleForTesting;
 import androidx.preference.PreferenceScreen;
 import androidx.preference.SwitchPreference;
 
@@ -37,7 +37,8 @@
     public static final String KEY_TOGGLE_NFC = "toggle_nfc";
     private final NfcAdapter mNfcAdapter;
     private NfcEnabler mNfcEnabler;
-    private NfcAirplaneModeObserver mAirplaneModeObserver;
+    @VisibleForTesting
+    NfcAirplaneModeObserver mAirplaneModeObserver;
 
     public NfcPreferenceController(Context context, String key) {
         super(context, key);
@@ -57,10 +58,10 @@
 
         mNfcEnabler = new NfcEnabler(mContext, switchPreference);
 
-        // Manually set dependencies for NFC when not toggleable.
-        if (!isToggleableInAirplaneMode(mContext)) {
-            mAirplaneModeObserver = new NfcAirplaneModeObserver(mContext,
-                    mNfcAdapter, (Preference) switchPreference);
+        // Listen to airplane mode updates if NFC should be turned off when airplane mode is on
+        if (shouldTurnOffNFCInAirplaneMode(mContext) || isToggleableInAirplaneMode(mContext)) {
+            mAirplaneModeObserver =
+                    new NfcAirplaneModeObserver(mContext, mNfcAdapter, switchPreference);
         }
     }
 
@@ -125,6 +126,12 @@
         }
     }
 
+    public static boolean shouldTurnOffNFCInAirplaneMode(Context context) {
+        final String airplaneModeRadios = Settings.Global.getString(context.getContentResolver(),
+                Settings.Global.AIRPLANE_MODE_RADIOS);
+        return airplaneModeRadios != null && airplaneModeRadios.contains(Settings.Global.RADIO_NFC);
+    }
+
     public static boolean isToggleableInAirplaneMode(Context context) {
         final String toggleable = Settings.Global.getString(context.getContentResolver(),
                 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
diff --git a/src/com/android/settings/password/ChooseLockGeneric.java b/src/com/android/settings/password/ChooseLockGeneric.java
index a2d4a3a..39380ea 100644
--- a/src/com/android/settings/password/ChooseLockGeneric.java
+++ b/src/com/android/settings/password/ChooseLockGeneric.java
@@ -39,6 +39,7 @@
 import android.os.UserManager;
 import android.os.storage.StorageManager;
 import androidx.annotation.StringRes;
+import androidx.annotation.VisibleForTesting;
 import androidx.preference.Preference;
 import androidx.preference.PreferenceScreen;
 import android.text.TextUtils;
@@ -124,7 +125,8 @@
          */
         public static final String EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS = "choose_lock_generic_extras";
 
-        private static final int CONFIRM_EXISTING_REQUEST = 100;
+        @VisibleForTesting
+        static final int CONFIRM_EXISTING_REQUEST = 100;
         private static final int ENABLE_ENCRYPTION_REQUEST = 101;
         private static final int CHOOSE_LOCK_REQUEST = 102;
         private static final int CHOOSE_LOCK_BEFORE_FINGERPRINT_REQUEST = 103;
@@ -329,7 +331,9 @@
             mWaitingForConfirmation = false;
             if (requestCode == CONFIRM_EXISTING_REQUEST && resultCode == Activity.RESULT_OK) {
                 mPasswordConfirmed = true;
-                mUserPassword = data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
+                mUserPassword = data != null
+                    ? data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD)
+                    : null;
                 updatePreferencesOrFinish(false /* isRecreatingActivity */);
                 if (mForChangeCredRequiredForBoot) {
                     if (!TextUtils.isEmpty(mUserPassword)) {
@@ -394,7 +398,8 @@
             }
         }
 
-        private void updatePreferencesOrFinish(boolean isRecreatingActivity) {
+        @VisibleForTesting
+        void updatePreferencesOrFinish(boolean isRecreatingActivity) {
             Intent intent = getActivity().getIntent();
             int quality = intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, -1);
             if (quality == -1) {
diff --git a/src/com/android/settings/widget/UsageGraph.java b/src/com/android/settings/widget/UsageGraph.java
index da61607..7238e5d 100644
--- a/src/com/android/settings/widget/UsageGraph.java
+++ b/src/com/android/settings/widget/UsageGraph.java
@@ -255,9 +255,15 @@
             return;
         }
 
+        canvas.save();
+        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
+            // Flip the canvas along the y-axis of the center of itself before drawing paths.
+            canvas.scale(-1, 1, canvas.getWidth() * 0.5f, 0);
+        }
         drawLinePath(canvas, mLocalProjectedPaths, mDottedPaint);
         drawFilledPath(canvas, mLocalPaths, mFillPaint);
         drawLinePath(canvas, mLocalPaths, mLinePaint);
+        canvas.restore();
         BatteryUtils.logRuntime(LOG_TAG, "onDraw", startTime);
     }
 
diff --git a/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragmentTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragmentTest.java
new file mode 100644
index 0000000..c353b1b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonDialogFragmentTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.settings.applications.appinfo;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.robolectric.Shadows.shadowOf;
+
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.pm.PackageManager;
+import com.android.settings.R;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.shadows.ShadowAlertDialog;
+import org.robolectric.shadows.ShadowDialog;
+import org.robolectric.util.FragmentTestUtil;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class InstantAppButtonDialogFragmentTest {
+
+    private static final String TEST_PACKAGE = "testPackage";
+
+    private InstantAppButtonDialogFragment mFragment;
+    private Context mContext;
+
+    @Before
+    public void setUp() {
+        mContext = spy(RuntimeEnvironment.application);
+        mFragment = spy(InstantAppButtonDialogFragment.newInstance(TEST_PACKAGE));
+        doReturn(mContext).when(mFragment).getContext();
+    }
+
+    @Test
+    public void onClick_shouldDeleteApp() {
+        final PackageManager packageManager = mock(PackageManager.class);
+        when(mContext.getPackageManager()).thenReturn(packageManager);
+        FragmentTestUtil.startFragment(mFragment);
+
+        mFragment.onClick(null /* dialog */, 0  /* which */);
+
+        verify(packageManager)
+            .deletePackageAsUser(eq(TEST_PACKAGE), any(), anyInt(), anyInt());
+    }
+
+    @Test
+    public void onCreateDialog_clearAppDialog_shouldShowClearAppDataConfirmation() {
+        FragmentTestUtil.startFragment(mFragment);
+
+        final AlertDialog dialog = (AlertDialog) ShadowDialog.getLatestDialog();
+        assertThat(dialog).isNotNull();
+        final ShadowAlertDialog shadowDialog = shadowOf(dialog);
+
+        assertThat(shadowDialog.getMessage()).isEqualTo(
+                mContext.getString(R.string.clear_instant_app_confirmation));
+        assertThat(shadowDialog.getTitle()).isEqualTo(
+                mContext.getString(R.string.clear_instant_app_data));
+        assertThat(dialog.getButton(DialogInterface.BUTTON_POSITIVE).getText()).isEqualTo(
+                mContext.getString(R.string.clear_instant_app_data));
+        assertThat(dialog.getButton(DialogInterface.BUTTON_NEGATIVE).getText()).isEqualTo(
+                mContext.getString(R.string.cancel));
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceControllerTest.java
index 425b9f0..32cafeb 100644
--- a/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/InstantAppButtonsPreferenceControllerTest.java
@@ -27,9 +27,10 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import android.app.FragmentManager;
+import android.app.FragmentTransaction;
 import android.content.ComponentName;
 import android.content.Context;
-import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
@@ -287,13 +288,16 @@
     }
 
     @Test
-    public void onClick_shouldDeleteApp() {
-        PackageManager packageManager = mock(PackageManager.class);
-        ReflectionHelpers.setField(mController, "mPackageManager", packageManager);
+    public void clickClearAppButton_shouldLaunchInstantAppButtonDialogFragment() {
+        final FragmentManager fragmentManager = mock(FragmentManager.class);
+        final FragmentTransaction fragmentTransaction = mock(FragmentTransaction.class);
+        when(mFragment.getFragmentManager()).thenReturn(fragmentManager);
+        when(fragmentManager.beginTransaction()).thenReturn(fragmentTransaction);
+        mController.displayPreference(mScreen);
 
-        mController.onClick(mock(DialogInterface.class), DialogInterface.BUTTON_POSITIVE);
+        mClearAppButton.callOnClick();
 
-        verify(packageManager)
-            .deletePackageAsUser(eq(TEST_AIA_PACKAGE_NAME), any(), anyInt(),anyInt());
+        verify(fragmentTransaction).add(any(InstantAppButtonDialogFragment.class),
+            eq("instant_app_buttons"));
     }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
index bdf249d..3aa83a8 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
@@ -16,8 +16,6 @@
 
 package com.android.settings.applications.defaultapps;
 
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.verify;
@@ -25,20 +23,11 @@
 
 import android.app.Activity;
 import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ResolveInfo;
 import android.os.UserManager;
 
 import com.android.settings.testutils.FakeFeatureFactory;
 import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settingslib.applications.DefaultAppInfo;
-
-import java.util.ArrayList;
-import java.util.List;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -85,39 +74,4 @@
         mPicker.getDefaultKey();
         verify(mPackageManager).getDefaultBrowserPackageNameAsUser(anyInt());
     }
-
-    @Test
-    public void getCandidates_shouldNotIncludeDuplicatePackageName() throws NameNotFoundException {
-        final List<ResolveInfo> resolveInfos = new ArrayList<>();
-        final String PACKAGE_ONE = "com.first.package";
-        final String PACKAGE_TWO = "com.second.package";
-        resolveInfos.add(createResolveInfo(PACKAGE_ONE));
-        resolveInfos.add(createResolveInfo(PACKAGE_TWO));
-        resolveInfos.add(createResolveInfo(PACKAGE_ONE));
-        resolveInfos.add(createResolveInfo(PACKAGE_TWO));
-        when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
-            .thenReturn(resolveInfos);
-        when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_ONE), anyInt(), anyInt()))
-            .thenReturn(createApplicationInfo(PACKAGE_ONE));
-        when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_TWO), anyInt(), anyInt()))
-            .thenReturn(createApplicationInfo(PACKAGE_TWO));
-
-        final List<DefaultAppInfo> defaultBrowserInfo = mPicker.getCandidates();
-
-        assertThat(defaultBrowserInfo.size()).isEqualTo(2);
-    }
-
-    private ResolveInfo createResolveInfo(String packageName) {
-        final ResolveInfo info = new ResolveInfo();
-        info.handleAllWebDataURI = true;
-        info.activityInfo = new ActivityInfo();
-        info.activityInfo.packageName = packageName;
-        return info;
-    }
-
-    private ApplicationInfo createApplicationInfo(String packageName) {
-        final ApplicationInfo info = new ApplicationInfo();
-        info.packageName = packageName;
-        return info;
-    }
 }
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
index 6bf6ac4..d4c4115 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
@@ -17,15 +17,21 @@
 package com.android.settings.applications.defaultapps;
 
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
 import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ResolveInfo;
 import android.os.UserManager;
 import androidx.preference.Preference;
@@ -33,6 +39,8 @@
 import com.android.settings.R;
 import com.android.settings.testutils.SettingsRobolectricTestRunner;
 
+import java.util.ArrayList;
+import java.util.List;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -73,8 +81,11 @@
 
     @Test
     public void isAvailable_hasBrowser_shouldReturnTrue() {
+        final ResolveInfo info = new ResolveInfo();
+        info.activityInfo = new ActivityInfo();
+        info.handleAllWebDataURI = true;
         when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
-            .thenReturn(Collections.singletonList(new ResolveInfo()));
+            .thenReturn(Collections.singletonList(info));
         assertThat(mController.isAvailable()).isTrue();
     }
 
@@ -89,6 +100,28 @@
     }
 
     @Test
+    public void getDefaultAppLabel_hasAppWithMultipleResolvedInfo_shouldReturnLabel()
+            throws NameNotFoundException {
+        DefaultBrowserPreferenceController spyController = spy(mController);
+        doReturn(null).when(spyController).getDefaultAppIcon();
+        final List<ResolveInfo> resolveInfos = new ArrayList<>();
+        final CharSequence PACKAGE_NAME = "com.test.package";
+        final ResolveInfo info1 = spy(createResolveInfo(PACKAGE_NAME.toString()));
+        when(info1.loadLabel(mPackageManager)).thenReturn(PACKAGE_NAME);
+        resolveInfos.add(info1);
+        resolveInfos.add(createResolveInfo(PACKAGE_NAME.toString()));
+        when(mPackageManager.getDefaultBrowserPackageNameAsUser(anyInt())).thenReturn(null);
+        when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
+            .thenReturn(resolveInfos);
+        when(mPackageManager.getApplicationInfoAsUser(
+            eq(PACKAGE_NAME.toString()), anyInt(), anyInt()))
+            .thenReturn(createApplicationInfo(PACKAGE_NAME.toString()));
+        final Preference pref = mock(Preference.class);
+
+        assertThat(spyController.getDefaultAppLabel()).isEqualTo(PACKAGE_NAME);
+    }
+
+    @Test
     public void getDefaultApp_shouldGetDefaultBrowserPackage() {
         mController.getDefaultAppInfo();
 
@@ -103,4 +136,40 @@
 
         assertThat(mController.isBrowserDefault("pkg", 0)).isTrue();
     }
+
+    @Test
+    public void getCandidates_shouldNotIncludeDuplicatePackageName() throws NameNotFoundException {
+        final List<ResolveInfo> resolveInfos = new ArrayList<>();
+        final String PACKAGE_ONE = "com.first.package";
+        final String PACKAGE_TWO = "com.second.package";
+        resolveInfos.add(createResolveInfo(PACKAGE_ONE));
+        resolveInfos.add(createResolveInfo(PACKAGE_TWO));
+        resolveInfos.add(createResolveInfo(PACKAGE_ONE));
+        resolveInfos.add(createResolveInfo(PACKAGE_TWO));
+        when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
+            .thenReturn(resolveInfos);
+        when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_ONE), anyInt(), anyInt()))
+            .thenReturn(createApplicationInfo(PACKAGE_ONE));
+        when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_TWO), anyInt(), anyInt()))
+            .thenReturn(createApplicationInfo(PACKAGE_TWO));
+
+        final List<ResolveInfo> defaultBrowserInfo =
+            mController.getCandidates(mPackageManager, 0 /* userId */);
+
+        assertThat(defaultBrowserInfo.size()).isEqualTo(2);
+    }
+
+    private ResolveInfo createResolveInfo(String packageName) {
+        final ResolveInfo info = new ResolveInfo();
+        info.handleAllWebDataURI = true;
+        info.activityInfo = new ActivityInfo();
+        info.activityInfo.packageName = packageName;
+        return info;
+    }
+
+    private ApplicationInfo createApplicationInfo(String packageName) {
+        final ApplicationInfo info = new ApplicationInfo();
+        info.packageName = packageName;
+        return info;
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/development/MockLocationAppPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/development/MockLocationAppPreferenceControllerTest.java
index 24d46dd..e247485 100644
--- a/tests/robotests/src/com/android/settings/development/MockLocationAppPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/development/MockLocationAppPreferenceControllerTest.java
@@ -23,6 +23,7 @@
 import com.android.settings.testutils.SettingsRobolectricTestRunner;
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
@@ -33,6 +34,7 @@
 import java.util.Collections;
 
 @RunWith(SettingsRobolectricTestRunner.class)
+@Ignore
 public class MockLocationAppPreferenceControllerTest {
 
     @Mock
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
index a4107f5..c8ed42e 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
@@ -19,6 +19,7 @@
 import static com.android.settings.applications.manageapplications.ManageApplications.EXTRA_WORK_ONLY;
 import static com.android.settings.utils.FileSizeFormatter.MEGABYTE_IN_BYTES;
 import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
 import static org.mockito.ArgumentMatchers.nullable;
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
@@ -123,7 +124,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mActivity).startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+        verify(mActivity).startActivityForResultAsUser(argumentCaptor.capture(), anyInt(),
+                nullable(UserHandle.class));
 
         final Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -140,8 +142,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity())
-            .startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
         final Intent intent = argumentCaptor.getValue();
 
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -167,8 +169,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
 
         final Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -186,8 +188,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity())
-                .startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -223,8 +225,8 @@
             .isTrue();
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         Intent browseIntent = mVolume.buildBrowseIntent();
@@ -240,8 +242,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -258,8 +260,8 @@
         mController.handlePreferenceTreeClick(mPreference);
 
         final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
-        verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
-                nullable(UserHandle.class));
+        verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+                anyInt(), nullable(UserHandle.class));
 
         Intent intent = argumentCaptor.getValue();
         assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/RestrictAppPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/RestrictAppPreferenceControllerTest.java
index c6f885c..a377c16 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/RestrictAppPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/RestrictAppPreferenceControllerTest.java
@@ -39,6 +39,7 @@
 import com.android.settings.fuelgauge.batterytip.AppInfo;
 
 import org.junit.Before;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.ArgumentCaptor;
@@ -51,6 +52,7 @@
 import java.util.List;
 
 @RunWith(RobolectricTestRunner.class)
+@Ignore
 public class RestrictAppPreferenceControllerTest {
     private static final int ALLOWED_UID = 111;
     private static final String ALLOWED_PACKAGE_NAME = "com.android.allowed.package";
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
index 9457f09..e1cf196 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
@@ -18,6 +18,7 @@
 import static com.google.common.truth.Truth.assertThat;
 
 import androidx.lifecycle.LifecycleOwner;
+
 import android.content.Context;
 import android.provider.Settings;
 
@@ -39,6 +40,7 @@
 
     private static final int TRIGGER_LEVEL = 20;
     private static final int DEFAULT_LEVEL = 15;
+    private static final int INTERVAL = 5;
 
     private AutoBatterySeekBarPreferenceController mController;
     private Context mContext;
@@ -85,15 +87,16 @@
 
         assertThat(mPreference.isVisible()).isTrue();
         assertThat(mPreference.getTitle()).isEqualTo("At 20%");
-        assertThat(mPreference.getProgress()).isEqualTo(TRIGGER_LEVEL);
+        assertThat(mPreference.getProgress()).isEqualTo(TRIGGER_LEVEL / INTERVAL);
     }
 
+
     @Test
     public void testOnPreferenceChange_updateValue() {
         Settings.Global.putInt(mContext.getContentResolver(),
                 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0);
 
-        mController.onPreferenceChange(mPreference, TRIGGER_LEVEL);
+        mController.onPreferenceChange(mPreference, TRIGGER_LEVEL / INTERVAL);
 
         assertThat(Settings.Global.getInt(mContext.getContentResolver(),
                 Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0)).isEqualTo(TRIGGER_LEVEL);
@@ -106,7 +109,7 @@
 
         mController.updateState(mPreference);
 
-        assertThat(mPreference.getMax()).isEqualTo(50);
+        assertThat(mPreference.getMax()).isEqualTo(50 / INTERVAL);
     }
 
     @Test
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java b/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
index b55bf6b..adee433 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
@@ -178,7 +178,7 @@
         verify(mFeatureFactory.metricsFeatureProvider).action(mContext,
                 MetricsProto.MetricsEvent.ACTION_ANOMALY_IGNORED,
                 SYSTEM_PACKAGE,
-                Pair.create(MetricsProto.MetricsEvent.FIELD_CONTEXT, ANOMALY_TYPE),
+                Pair.create(MetricsProto.MetricsEvent.FIELD_ANOMALY_TYPE, ANOMALY_TYPE),
                 Pair.create(MetricsProto.MetricsEvent.FIELD_APP_VERSION_CODE, VERSION_CODE));
     }
 
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java b/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
index 5efa94a..c5e38a6 100644
--- a/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
+++ b/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
@@ -18,11 +18,12 @@
 
 import static com.google.common.truth.Truth.assertThat;
 
+import android.content.ContentResolver;
 import android.content.Context;
 import android.nfc.NfcAdapter;
 import android.provider.Settings;
 
-import androidx.preference.Preference;
+import android.provider.Settings.Global;
 import androidx.preference.SwitchPreference;
 
 import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -52,8 +53,8 @@
 
         mNfcPreference = new SwitchPreference(RuntimeEnvironment.application);
 
-        mNfcAirplaneModeObserver = new NfcAirplaneModeObserver(mContext, mNfcAdapter,
-                (Preference) mNfcPreference);
+        mNfcAirplaneModeObserver =
+                new NfcAirplaneModeObserver(mContext, mNfcAdapter, mNfcPreference);
     }
 
     @Test
@@ -67,20 +68,51 @@
                 NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
 
         assertThat(mNfcAdapter.isEnabled()).isFalse();
+    }
+
+    @Test
+    public void NfcAirplaneModeObserver_airplaneModeOnNfcToggleable_shouldEnablePreference() {
+        ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 0);
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+        mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
+        assertThat(mNfcPreference.isEnabled()).isTrue();
+    }
+
+    @Test
+    public void NfcAirplaneModeObserver_airplaneModeOnNfcNotToggleable_shouldDisablePreference() {
+        ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 0);
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Global.RADIO_WIFI);
+
+        mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
         assertThat(mNfcPreference.isEnabled()).isFalse();
     }
 
     @Test
-    public void NfcAirplaneModeObserver_airplaneOff_shouldEnableNfc() {
-        ReflectionHelpers.setField(mNfcAirplaneModeObserver,
-                "mAirplaneMode", 1);
-        Settings.Global.putInt(mContext.getContentResolver(),
-                Settings.Global.AIRPLANE_MODE_ON, 0);
+    public void NfcAirplaneModeObserver_airplaneModeOff_shouldEnablePreference() {
+        ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 1);
+        Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
 
-        mNfcAirplaneModeObserver.onChange(false,
-                NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+        mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
 
-        assertThat(mNfcAdapter.isEnabled()).isTrue();
         assertThat(mNfcPreference.isEnabled()).isTrue();
     }
+
+    @Test
+    public void NfcAirplaneModeObserver_airplaneModeOff_shouldNotEnableNfcAutomatically() {
+        ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 1);
+        Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
+
+        mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
+        assertThat(mNfcAdapter.isEnabled()).isFalse();
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java b/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java
new file mode 100644
index 0000000..a10c27a
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.nfc;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.nfc.NfcAdapter;
+import android.provider.Settings;
+import androidx.preference.SwitchPreference;
+
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class NfcEnablerTest {
+
+    @Mock
+    private SwitchPreference mNfcPreference;
+
+    private Context mContext;
+    private NfcEnabler mNfcEnabler;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mContext = RuntimeEnvironment.application;
+        mNfcEnabler = spy(new NfcEnabler(mContext, mNfcPreference));
+    }
+
+    @Test
+    public void isToggleable_AirplaneModeOff_shouldReturnTrue() {
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+        assertThat(mNfcEnabler.isToggleable()).isTrue();
+    }
+
+    @Test
+    public void isToggleable_AirplaneModeOnNfcNotInAirplaneModeRadio_shouldReturnTrue() {
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+        Settings.Global.putString(contentResolver, Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+        assertThat(mNfcEnabler.isToggleable()).isTrue();
+    }
+
+    @Test
+    public void isToggleable_AirplaneModeOnNfcToggleable_shouldReturnTrue() {
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+        assertThat(mNfcEnabler.isToggleable()).isTrue();
+    }
+
+    @Test
+    public void isToggleable_AirplaneModeOnNfcNotToggleable_shouldReturnFalse() {
+        final ContentResolver contentResolver = mContext.getContentResolver();
+        Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+        Settings.Global.putString(contentResolver,
+            Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+        Settings.Global.putString(contentResolver,
+                Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, "");
+
+        assertThat(mNfcEnabler.isToggleable()).isFalse();
+    }
+
+    @Test
+    public void handleNfcStateChanged_stateOff_shouldCheckIfPreferenceEnableState() {
+        mNfcEnabler.handleNfcStateChanged(NfcAdapter.STATE_OFF);
+
+        verify(mNfcEnabler).isToggleable();
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
index eaf6425..758f72c 100644
--- a/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
@@ -75,15 +75,6 @@
         mNfcPreference = new SwitchPreference(RuntimeEnvironment.application);
 
         when(mScreen.findPreference(mNfcController.getPreferenceKey())).thenReturn(mNfcPreference);
-
-        Settings.Global.putString(mContext.getContentResolver(),
-                Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
-                Settings.Global.RADIO_NFC);
-
-        Settings.Global.putInt(mContext.getContentResolver(),
-                Settings.Global.AIRPLANE_MODE_ON,
-                0);
-        mNfcController.displayPreference(mScreen);
     }
 
     @Test
@@ -102,6 +93,7 @@
 
     @Test
     public void isNfcEnable_nfcStateNotTurning_shouldReturnTrue() {
+        mNfcController.displayPreference(mScreen);
         when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_ON);
         mNfcController.onResume();
         assertThat(mNfcPreference.isEnabled()).isTrue();
@@ -113,6 +105,7 @@
 
     @Test
     public void isNfcEnable_nfcStateTurning_shouldReturnFalse() {
+        mNfcController.displayPreference(mScreen);
         when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_TURNING_ON);
         mNfcController.onResume();
         assertThat(mNfcPreference.isEnabled()).isFalse();
@@ -124,6 +117,7 @@
 
     @Test
     public void isNfcChecked_nfcStateOn_shouldReturnTrue() {
+        mNfcController.displayPreference(mScreen);
         when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_ON);
         mNfcController.onResume();
         assertThat(mNfcPreference.isChecked()).isTrue();
@@ -205,4 +199,52 @@
 
         assertThat(NfcPreferenceController.isToggleableInAirplaneMode(mContext)).isFalse();
     }
+
+    @Test
+    public void shouldTurnOffNFCInAirplaneMode_airplaneModeRadiosContainsNfc_shouldReturnTrue() {
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+
+        assertThat(NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)).isTrue();
+    }
+
+    @Test
+    public void shouldTurnOffNFCInAirplaneMode_airplaneModeRadiosWithoutNfc_shouldReturnFalse() {
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+        assertThat(NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)).isFalse();
+    }
+
+    @Test
+    public void displayPreference_airplaneModeRadiosContainsNfc_shouldCreateAirplaneModeObserver() {
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+
+        mNfcController.displayPreference(mScreen);
+
+        assertThat(mNfcController.mAirplaneModeObserver).isNotNull();
+    }
+
+    @Test
+    public void displayPreference_nfcToggleableInAirplaneMode_shouldCreateAirplaneModeObserver() {
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+        mNfcController.displayPreference(mScreen);
+
+        assertThat(mNfcController.mAirplaneModeObserver).isNotNull();
+    }
+
+    @Test
+    public void displayPreference_nfcNotAffectByAirplaneMode_shouldNotCreateAirplaneModeObserver() {
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, "");
+        Settings.Global.putString(mContext.getContentResolver(),
+            Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+        mNfcController.displayPreference(mScreen);
+
+        assertThat(mNfcController.mAirplaneModeObserver).isNull();
+    }
 }
diff --git a/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
new file mode 100644
index 0000000..c66373b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
@@ -0,0 +1,42 @@
+/*
+ * 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.settings.password;
+
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.spy;
+
+import android.app.Activity;
+import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class ChooseLockGenericTest {
+
+    @Test
+    public void onActivityResult_nullIntentData_shouldNotCrash() {
+        ChooseLockGenericFragment fragment = spy(new ChooseLockGenericFragment());
+        doNothing().when(fragment).updatePreferencesOrFinish(anyBoolean());
+
+        fragment.onActivityResult(
+                fragment.CONFIRM_EXISTING_REQUEST, Activity.RESULT_OK, null /* data */);
+        // no crash
+    }
+
+}