Merge "Audio attributes"
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 0de7a4e..a854eef 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1373,11 +1373,6 @@
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.VOICE_LAUNCH" />
             </intent-filter>
-            <intent-filter android:priority="-2">
-                <action android:name="com.android.settings.action.SETTINGS" />
-            </intent-filter>
-            <meta-data android:name="com.android.settings.category"
-                android:value="com.android.settings.category.personal" />
             <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
                 android:value="com.android.settings.PrivacySettings" />
             <meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
@@ -2029,15 +2024,6 @@
         </activity>
 
         <receiver
-            android:name=".bluetooth.BluetoothDiscoveryReceiver">
-            <intent-filter>
-                <action android:name="android.bluetooth.adapter.action.DISCOVERY_STARTED" />
-                <action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED" />
-                <category android:name="android.intent.category.DEFAULT" />
-            </intent-filter>
-        </receiver>
-
-        <receiver
             android:name=".bluetooth.DockEventReceiver">
             <intent-filter>
                 <action android:name="android.intent.action.DOCK_EVENT" />
@@ -3007,10 +2993,9 @@
                        android:resource="@string/gesture_preference_summary" />
         </activity>
 
-        <activity android:name="BackupSettingsActivity"
+        <activity android:name=".backup.BackupSettingsActivity"
                   android:label="@string/privacy_settings_title"
                   android:icon="@drawable/ic_settings_backup"
-                  android:theme="@android:style/Theme.NoDisplay"
                   android:taskAffinity="com.android.settings"
                   android:parentActivityName="Settings">
             <intent-filter android:priority="1">
@@ -3268,21 +3253,8 @@
                        android:value="true" />
         </activity-alias>
 
-        <activity-alias android:name="PrivacyDashboardAlias"
-            android:targetActivity="Settings$PrivacySettingsActivity">
-            <intent-filter android:priority="60">
-                <action android:name="com.android.settings.action.SETTINGS" />
-            </intent-filter>
-            <meta-data android:name="com.android.settings.category"
-                       android:value="com.android.settings.category.ia.system" />
-            <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
-                       android:value="com.android.settings.PrivacySettings" />
-            <meta-data android:name="com.android.settings.PRIMARY_PROFILE_CONTROLLED"
-                       android:value="true" />
-        </activity-alias>
-
         <activity-alias android:name="BackupResetDashboardAlias"
-                        android:targetActivity=".BackupSettingsActivity">
+                        android:targetActivity=".backup.BackupSettingsActivity">
             <intent-filter android:priority="60">
                 <action android:name="com.android.settings.action.SETTINGS" />
             </intent-filter>
diff --git a/res/layout/device_admin_add.xml b/res/layout/device_admin_add.xml
index 8b79eaf..29d7b53 100644
--- a/res/layout/device_admin_add.xml
+++ b/res/layout/device_admin_add.xml
@@ -129,14 +129,25 @@
                 android:orientation="vertical"
                 android:divider="?android:attr/dividerHorizontal"
                 android:showDividers="beginning|middle|end">
-                <Button android:id="@+id/action_button"
-                    android:layout_width="match_parent"
-                    android:layout_gravity="start"
-                    android:gravity="start|center_vertical"
-                    android:maxLines="2"
-                    style="?android:attr/buttonBarButtonStyle"
-                    android:textAllCaps="false"
-                    android:layout_height="wrap_content" />
+                <LinearLayout
+                    android:id="@+id/restricted_action"
+                    android:layout_width="wrap_content"
+                    android:layout_height="wrap_content"
+                    android:orientation="horizontal"
+                    android:gravity="center_vertical">
+                    <Button android:id="@+id/action_button"
+                        android:layout_width="match_parent"
+                        android:layout_height="wrap_content"
+                        android:layout_gravity="start"
+                        android:gravity="start|center_vertical"
+                        android:maxLines="2"
+                        style="?android:attr/buttonBarButtonStyle"
+                        android:clickable="false"
+                        android:focusable="false"
+                        android:textAllCaps="false"
+                        />
+                    <include layout="@layout/restricted_icon" />
+                </LinearLayout>
                 <Button android:id="@+id/cancel_button"
                     android:layout_width="match_parent"
                     android:layout_gravity="end"
diff --git a/res/layout/preference_footer.xml b/res/layout/preference_footer.xml
index 64fad74..e336ac1 100644
--- a/res/layout/preference_footer.xml
+++ b/res/layout/preference_footer.xml
@@ -42,7 +42,7 @@
             android:layout_height="wrap_content"/>
     </LinearLayout>
 
-    <com.android.settings.widget.LinkTextView
+    <com.android.settingslib.widget.LinkTextView
         android:id="@android:id/title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
diff --git a/res/layout/support_disclaimer_content.xml b/res/layout/support_disclaimer_content.xml
index 196bef2..1e81f1a 100644
--- a/res/layout/support_disclaimer_content.xml
+++ b/res/layout/support_disclaimer_content.xml
@@ -23,7 +23,7 @@
         android:orientation="vertical"
         android:padding="24dp">
 
-        <com.android.settings.widget.LinkTextView
+        <com.android.settingslib.widget.LinkTextView
             android:id="@+id/support_disclaimer_text"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
diff --git a/res/values/config.xml b/res/values/config.xml
index 75d8697..fae38fc 100755
--- a/res/values/config.xml
+++ b/res/values/config.xml
@@ -45,9 +45,12 @@
     <string name="config_wallpaper_picker_package" translatable="false">com.android.settings</string>
     <string name="config_wallpaper_picker_class" translatable="false">com.android.settings.Settings$WallpaperSettingsActivity</string>
 
-    <!-- Backup settings to launch -->
+    <!-- Manufacturer backup settings to launch -->
     <string name="config_backup_settings_intent" translatable="false"></string>
 
+    <!-- Manufacturer backup settings label -->
+    <string name="config_backup_settings_label" translatable="true"></string>
+
     <!-- Double twist sensor name and vendor used by gesture setting -->
     <string name="gesture_double_twist_sensor_name" translatable="false"></string>
     <string name="gesture_double_twist_sensor_vendor" translatable="false"></string>
diff --git a/res/xml/backup_settings.xml b/res/xml/backup_settings.xml
new file mode 100644
index 0000000..30792bc
--- /dev/null
+++ b/res/xml/backup_settings.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ~ Copyright (C) 2017 The Android Open Source Project
+  ~
+  ~ Licensed under the Apache License, Version 2.0 (the "License");
+  ~ you may not use this file except in compliance with the License.
+  ~ You may obtain a copy of the License at
+  ~
+  ~      http://www.apache.org/licenses/LICENSE-2.0
+  ~
+  ~ Unless required by applicable law or agreed to in writing, software
+  ~ distributed under the License is distributed on an "AS IS" BASIS,
+  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  ~ See the License for the specific language governing permissions and
+  ~ limitations under the License
+  -->
+
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:settings="http://schemas.android.com/apk/res/com.android.settings"
+    android:title="@string/privacy_settings_title">
+
+    <!-- Backup settings provided by the backup transport or the default settings -->
+    <Preference
+        android:key="backup_settings" />
+
+    <!-- Backup settings provided by the manufacturer -->
+    <Preference
+        android:key="manufacturer_backup" />
+
+</PreferenceScreen>
diff --git a/res/xml/location_settings.xml b/res/xml/location_settings.xml
index ecce221..adfff63 100644
--- a/res/xml/location_settings.xml
+++ b/res/xml/location_settings.xml
@@ -37,7 +37,12 @@
         <!-- This preference category gets removed if new_recent_location_ui is disabled -->
         <Preference
             android:key="app_level_permissions"
-            android:title="@string/location_app_level_permissions" />
+            android:title="@string/location_app_level_permissions">
+            <intent android:action="android.intent.action.MANAGE_PERMISSION_APPS">
+                <extra android:name="android.intent.extra.PERMISSION_NAME"
+                       android:value="android.permission-group.LOCATION" />
+            </intent>
+        </Preference>
 
         <com.android.settings.DividedCategory
             android:key="recent_location_requests"
diff --git a/src/com/android/settings/AllowBindAppWidgetActivity.java b/src/com/android/settings/AllowBindAppWidgetActivity.java
index c3bf78a..2f98ab3 100644
--- a/src/com/android/settings/AllowBindAppWidgetActivity.java
+++ b/src/com/android/settings/AllowBindAppWidgetActivity.java
@@ -42,6 +42,7 @@
 
     private CheckBox mAlwaysUse;
     private int mAppWidgetId;
+    private Bundle mBindOptions;
     private UserHandle mProfile;
     private ComponentName mComponentName;
     private String mCallingPackage;
@@ -57,7 +58,7 @@
             if (mAppWidgetId != -1 && mComponentName != null && mCallingPackage != null) {
                 try {
                     final boolean bound = mAppWidgetManager.bindAppWidgetIdIfAllowed(mAppWidgetId,
-                            mProfile, mComponentName, null);
+                            mProfile, mComponentName, mBindOptions);
                     if (bound) {
                         Intent result = new Intent();
                         result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
@@ -100,6 +101,8 @@
                 }
                 mComponentName =
                         intent.getParcelableExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER);
+                mBindOptions =
+                        intent.getParcelableExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS);
                 mCallingPackage = getCallingPackage();
                 PackageManager pm = getPackageManager();
                 ApplicationInfo ai = pm.getApplicationInfo(mCallingPackage, 0);
diff --git a/src/com/android/settings/BackupSettingsActivity.java b/src/com/android/settings/BackupSettingsActivity.java
deleted file mode 100644
index a4cc4b7..0000000
--- a/src/com/android/settings/BackupSettingsActivity.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.settings;
-
-import android.app.Activity;
-import android.app.backup.BackupManager;
-import android.app.backup.IBackupManager;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.ServiceManager;
-import android.os.UserHandle;
-import android.text.TextUtils;
-import android.util.Log;
-
-import com.android.settings.R;
-
-import java.net.URISyntaxException;
-
-/**
- * A trampoline activity used to launch the configured Backup activity.
- * This activity used the theme NoDisplay to minimize the flicker that might be seen for the launch-
- * finsih transition.
- */
-public class BackupSettingsActivity extends Activity {
-    private static final String TAG = "BackupSettingsActivity";
-
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        String backup = getResources().getString(R.string.config_backup_settings_intent);
-        if (!TextUtils.isEmpty(backup)) {
-            try {
-                Intent intent = Intent.parseUri(backup, 0);
-                if (intent.resolveActivity(getPackageManager()) != null) {
-                    // use startActivityForResult to let the activity check the caller signature
-                    IBackupManager bmgr = IBackupManager.Stub.asInterface(
-                            ServiceManager.getService(Context.BACKUP_SERVICE));
-                    boolean backupOkay;
-                    try {
-                        backupOkay = bmgr.isBackupServiceActive(UserHandle.myUserId());
-                    } catch (Exception e) {
-                        // things go wrong talking to the backup system => ignore and
-                        // pass the default 'false' as the "backup is a thing?" state.
-                        backupOkay = false;
-                    }
-                    intent.putExtra(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE, backupOkay);
-                    startActivityForResult(intent, -1);
-                } else {
-                    Log.e(TAG, "Backup component not found!");
-                }
-            } catch (URISyntaxException e) {
-                Log.e(TAG, "Invalid backup component URI!", e);
-            }
-        }
-        finish();
-    }
-}
\ No newline at end of file
diff --git a/src/com/android/settings/DefaultRingtonePreference.java b/src/com/android/settings/DefaultRingtonePreference.java
index 6893a21..09f5af4 100644
--- a/src/com/android/settings/DefaultRingtonePreference.java
+++ b/src/com/android/settings/DefaultRingtonePreference.java
@@ -30,7 +30,7 @@
 public class DefaultRingtonePreference extends RingtonePreference {
     private static final String TAG = "DefaultRingtonePreference";
 
-    private int mUserId;
+    private int mUserId = UserHandle.USER_CURRENT;
     protected Context mUserContext;
 
     public DefaultRingtonePreference(Context context, AttributeSet attrs) {
@@ -40,21 +40,19 @@
 
     public void setUserId(int userId) {
         mUserId = userId;
-        Context context = getContext();
-        mUserContext = Utils.createPackageContextAsUser(context, mUserId);
+        mUserContext = Utils.createPackageContextAsUser(getContext(), mUserId);
     }
 
     @Override
     public void performClick() {
-        if (!Utils.startQuietModeDialogIfNecessary(getContext(), UserManager.get(getContext()),
-                mUserId)) {
-            super.performClick();
+        if (mUserId != UserHandle.USER_CURRENT) {
+            if (Utils.unlockWorkProfileIfNecessary(getContext(), mUserId) ||
+                    Utils.startQuietModeDialogIfNecessary(getContext(),
+                            UserManager.get(getContext()), mUserId)) {
+                return;
+            }
         }
-    }
-
-    public void clearUserId(int userId) {
-        mUserId = UserHandle.USER_CURRENT;
-        mUserContext = getContext();
+        super.performClick();
     }
 
     @Override
diff --git a/src/com/android/settings/DeviceAdminAdd.java b/src/com/android/settings/DeviceAdminAdd.java
index d6a072c..fb2f29f 100644
--- a/src/com/android/settings/DeviceAdminAdd.java
+++ b/src/com/android/settings/DeviceAdminAdd.java
@@ -61,8 +61,10 @@
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
 import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.R;
 import com.android.settings.users.UserDialogs;
-
+import com.android.settingslib.RestrictedLockUtils;
+import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
 import org.xmlpull.v1.XmlPullParserException;
 
 import java.io.IOException;
@@ -345,13 +347,26 @@
         });
 
         mActionButton = (Button) findViewById(R.id.action_button);
-        mActionButton.setFilterTouchesWhenObscured(true);
-        mActionButton.setOnClickListener(new View.OnClickListener() {
+
+        final View restrictedAction = findViewById(R.id.restricted_action);
+        restrictedAction.setFilterTouchesWhenObscured(true);
+        restrictedAction.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 if (mAdding) {
                     addAndFinish();
                 } else if (isManagedProfile(mDeviceAdmin)
                         && mDeviceAdmin.getComponent().equals(mDPM.getProfileOwner())) {
+                    if (hasBaseCantRemoveProfileRestriction()) {
+                        // If DISALLOW_REMOVE_MANAGED_PROFILE is set by the system, there's no
+                        // point showing a dialog saying it's disabled by an admin.
+                        return;
+                    }
+                    EnforcedAdmin enforcedAdmin = getAdminEnforcingCantRemoveProfile();
+                    if (enforcedAdmin != null) {
+                        RestrictedLockUtils.sendShowAdminSupportDetailsIntent(DeviceAdminAdd.this,
+                                enforcedAdmin);
+                        return;
+                    }
                     final int userId = UserHandle.myUserId();
                     UserDialogs.createRemoveDialog(DeviceAdminAdd.this, userId,
                             new DialogInterface.OnClickListener() {
@@ -522,6 +537,7 @@
     }
 
     void updateInterface() {
+        findViewById(R.id.restricted_icon).setVisibility(View.GONE);
         mAdminIcon.setImageDrawable(mDeviceAdmin.loadIcon(getPackageManager()));
         mAdminName.setText(mDeviceAdmin.loadLabel(getPackageManager()));
         try {
@@ -551,6 +567,13 @@
                 // Profile owner in a managed profile, user can remove profile to disable admin.
                 mAdminWarning.setText(R.string.admin_profile_owner_message);
                 mActionButton.setText(R.string.remove_managed_profile_label);
+
+                final EnforcedAdmin admin = getAdminEnforcingCantRemoveProfile();
+                final boolean hasBaseRestriction = hasBaseCantRemoveProfileRestriction();
+                if (admin != null && !hasBaseRestriction) {
+                    findViewById(R.id.restricted_icon).setVisibility(View.VISIBLE);
+                }
+                mActionButton.setEnabled(admin == null && !hasBaseRestriction);
             } else if (isProfileOwner || mDeviceAdmin.getComponent().equals(
                             mDPM.getDeviceOwnerComponentOnCallingUser())) {
                 // Profile owner in a user or device owner, user can't disable admin.
@@ -601,6 +624,22 @@
         }
     }
 
+    private EnforcedAdmin getAdminEnforcingCantRemoveProfile() {
+        // Removing a managed profile is disallowed if DISALLOW_REMOVE_MANAGED_PROFILE
+        // is set in the parent rather than the user itself.
+        return RestrictedLockUtils.checkIfRestrictionEnforced(this,
+                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, getParentUserId());
+    }
+
+    private boolean hasBaseCantRemoveProfileRestriction() {
+        return RestrictedLockUtils.hasBaseUserRestriction(this,
+                UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, getParentUserId());
+    }
+
+    private int getParentUserId() {
+        return UserManager.get(this).getProfileParent(UserHandle.myUserId()).id;
+    }
+
     private void addDeviceAdminPolicies(boolean showDescription) {
         if (!mAdminPoliciesInitialized) {
             boolean isAdminUser = UserManager.get(this).isAdminUser();
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index c01e4c4..c2060ce 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -54,6 +54,7 @@
 
 import com.android.internal.util.ArrayUtils;
 import com.android.settings.Settings.WifiSettingsActivity;
+import com.android.settings.backup.BackupSettingsActivity;
 import com.android.settings.core.gateway.SettingsGateway;
 import com.android.settings.core.instrumentation.SharedPreferencesLogger;
 import com.android.settings.dashboard.DashboardContainerFragment;
@@ -965,29 +966,11 @@
             }
         }
 
-        String backupIntent = getResources().getString(R.string.config_backup_settings_intent);
-        boolean useDefaultBackup = TextUtils.isEmpty(backupIntent);
+        // Enable/disable backup settings depending on whether the user is admin.
         setTileEnabled(new ComponentName(packageName,
-                Settings.PrivacySettingsActivity.class.getName()), useDefaultBackup, isAdmin);
+                BackupSettingsActivity.class.getName()), true, isAdmin);
         setTileEnabled(new ComponentName(packageName,
-                        "com.android.settings.PrivacyDashboardAlias"),
-                useDefaultBackup, isAdmin);
-
-        boolean hasBackupActivity = false;
-        if (!useDefaultBackup) {
-            try {
-                Intent intent = Intent.parseUri(backupIntent, 0);
-                hasBackupActivity = !getPackageManager().queryIntentActivities(intent, 0).isEmpty();
-            } catch (URISyntaxException e) {
-                Log.e(LOG_TAG, "Invalid backup intent URI!", e);
-            }
-        }
-
-        // Enable/disable BackupSettingsActivity and its alias.
-        setTileEnabled(new ComponentName(packageName,
-                BackupSettingsActivity.class.getName()), hasBackupActivity, isAdmin);
-        setTileEnabled(new ComponentName(packageName,
-                "com.android.settings.BackupResetDashboardAlias"), hasBackupActivity, isAdmin);
+                "com.android.settings.BackupResetDashboardAlias"), true, isAdmin);
 
         setTileEnabled(new ComponentName(packageName,
                 Settings.EnterprisePrivacySettingsActivity.class.getName()),
diff --git a/src/com/android/settings/backup/BackupSettingsActivity.java b/src/com/android/settings/backup/BackupSettingsActivity.java
new file mode 100644
index 0000000..b195384
--- /dev/null
+++ b/src/com/android/settings/backup/BackupSettingsActivity.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+
+
+/**
+ * The activity used to launch the configured Backup activity or the preference screen
+ * if the manufacturer provided their backup settings.
+ */
+public class BackupSettingsActivity extends Activity {
+    private static final String TAG = "BackupSettingsActivity";
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        BackupSettingsHelper backupHelper = new BackupSettingsHelper(this);
+
+        if (!backupHelper.isBackupProvidedByManufacturer()) {
+            // If manufacturer specific backup settings are not provided then launch
+            // the backup settings provided by backup transport or the default one directly.
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG,
+                        "No manufacturer settings found, launching the backup settings directly");
+            }
+            // use startActivityForResult to let the activity check the caller signature
+            startActivityForResult(backupHelper.getIntentForBackupSettings(), 1);
+            finish();
+        } else {
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, "Manufacturer provided backup settings, showing the preference screen");
+            }
+            getFragmentManager().beginTransaction()
+                    .replace(android.R.id.content, new BackupSettingsFragment())
+                    .commit();
+        }
+    }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/backup/BackupSettingsFragment.java b/src/com/android/settings/backup/BackupSettingsFragment.java
new file mode 100644
index 0000000..dcc1608
--- /dev/null
+++ b/src/com/android/settings/backup/BackupSettingsFragment.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.provider.SearchIndexableResource;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.util.Log;
+
+
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Fragment showing the items to launch different backup settings screens.
+ */
+public class BackupSettingsFragment extends DashboardFragment {
+    private static final String TAG = "BackupSettings";
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+    }
+
+    /**
+     * Get the tag string for logging.
+     */
+    @Override
+    protected String getLogTag() {
+        return TAG;
+    }
+
+    /**
+     * Get the res id for static preference xml for this fragment.
+     */
+    @Override
+    protected int getPreferenceScreenResId() {
+        return R.xml.backup_settings;
+    }
+
+    /**
+     * Get a list of {@link PreferenceController} for this fragment.
+     */
+    @Override
+    protected List<PreferenceController> getPreferenceControllers(Context context) {
+        final List<PreferenceController> controllers = new ArrayList<>();
+        controllers.add(new BackupSettingsPreferenceController(context));
+        return controllers;
+    }
+
+    public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+            new BaseSearchIndexProvider() {
+                @Override
+                public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
+                        boolean enabled) {
+                    final SearchIndexableResource sir = new SearchIndexableResource(context);
+                    sir.xmlResId = R.xml.backup_settings;
+                    return Arrays.asList(sir);
+                }
+            };
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsEvent.BACKUP_SETTINGS;
+    }
+}
diff --git a/src/com/android/settings/backup/BackupSettingsHelper.java b/src/com/android/settings/backup/BackupSettingsHelper.java
new file mode 100644
index 0000000..b0d6cf8
--- /dev/null
+++ b/src/com/android/settings/backup/BackupSettingsHelper.java
@@ -0,0 +1,237 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+
+import android.app.backup.BackupManager;
+import android.app.backup.IBackupManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.UserHandle;
+import android.util.Log;
+
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.R;
+import com.android.settings.Settings.PrivacySettingsActivity;
+import com.android.settingslib.drawer.SettingsDrawerActivity;
+import java.net.URISyntaxException;
+
+/**
+ * Helper class for {@link BackupSettingsActivity} that interacts with {@link IBackupManager}.
+ */
+public class BackupSettingsHelper {
+    private static final String TAG = "BackupSettingsHelper";
+
+    private IBackupManager mBackupManager = IBackupManager.Stub.asInterface(
+            ServiceManager.getService(Context.BACKUP_SERVICE));
+
+    private Context mContext;
+
+    public BackupSettingsHelper(Context context) {
+        mContext = context;
+    }
+
+    /**
+     * Returns an intent to launch backup settings from backup transport if the intent was provided
+     * by the transport. Otherwise returns the intent to launch the default backup settings screen.
+     *
+     * @return Intent for launching backup settings
+     */
+    public Intent getIntentForBackupSettings() {
+        Intent intent;
+        if (isIntentProvidedByTransport()) {
+            intent = getIntentForBackupSettingsFromTransport();
+        } else {
+            Log.e(TAG, "Backup transport has not provided an intent"
+                    + " or the component for the intent is not found!");
+            intent = getIntentForDefaultBackupSettings();
+        }
+        return intent;
+    }
+
+    /**
+     * Returns a label for the settings item that will point to the backup settings provided by
+     * the transport. If no label was provided by transport, returns the default string.
+     *
+     * @return Label for the backup settings item.
+     */
+    public String getLabelForBackupSettings() {
+        String label = getLabelFromBackupTransport();
+        if (label == null || label.isEmpty()) {
+            label = mContext.getString(R.string.privacy_settings_title);
+        }
+        return label;
+    }
+
+    /**
+     * Returns a summary string for the settings item that will point to the backup settings
+     * provided by the transport. If no summary was provided by transport, returns the default
+     * string.
+     *
+     * @return Summary for the backup settings item.
+     */
+    public String getSummaryForBackupSettings() {
+        String summary = getSummaryFromBackupTransport();
+        if (summary == null) {
+            summary = mContext.getString(R.string.backup_configure_account_default_summary);
+        }
+        return summary;
+    }
+
+
+    /**
+     * Checks if the manufacturer provided an intent to launch its backup settings screen
+     * in the config file.
+     */
+    public boolean isBackupProvidedByManufacturer() {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "Checking if intent provided by manufacturer");
+        }
+        String intentString =
+                mContext.getResources().getString(R.string.config_backup_settings_intent);
+
+        return intentString != null && !intentString.isEmpty();
+    }
+
+    /**
+     * Returns the label for the backup settings item provided by the manufacturer.
+     */
+    public String getLabelProvidedByManufacturer() {
+        return mContext.getResources().getString(R.string.config_backup_settings_label);
+    }
+
+    /**
+     * Returns the intent to the backup settings screen provided by the manufacturer.
+     */
+    public Intent getIntentProvidedByManufacturer() {
+        if (Log.isLoggable(TAG, Log.DEBUG)) {
+            Log.d(TAG, "Getting a backup settings intent provided by manufacturer");
+        }
+        String intentString =
+                mContext.getResources().getString(R.string.config_backup_settings_intent);
+        if (intentString != null && !intentString.isEmpty()) {
+            try {
+                return Intent.parseUri(intentString, 0);
+            } catch (URISyntaxException e) {
+                Log.e(TAG, "Invalid intent provided by the manufacturer.", e);
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Gets the intent from Backup transport and adds the extra depending on whether the user has
+     * rights to see backup settings.
+     *
+     * @return Intent to launch Backup settings provided by the Backup transport.
+     */
+    @VisibleForTesting
+    Intent getIntentForBackupSettingsFromTransport() {
+        Intent intent = getIntentFromBackupTransport();
+        if (intent != null) {
+            intent.putExtra(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE, isBackupServiceActive());
+        }
+        return intent;
+    }
+
+    private Intent getIntentForDefaultBackupSettings() {
+        // Extra needed by {@link SettingsDrawerActivity} to show the back button navigation.
+        return new Intent(mContext, PrivacySettingsActivity.class)
+                .putExtra(SettingsDrawerActivity.EXTRA_SHOW_MENU, true);
+    }
+
+    /**
+     * Checks if the transport provided the intent to launch the backup settings and if that
+     * intent resolves to an activity.
+     */
+    @VisibleForTesting
+    boolean isIntentProvidedByTransport() {
+        Intent intent = getIntentFromBackupTransport();
+        return intent != null && intent.resolveActivity(mContext.getPackageManager()) != null;
+    }
+
+    /**
+     * Gets an intent to launch the backup settings from the current transport using
+     * {@link com.android.internal.backup.IBackupTransport#dataManagementIntent()} API.
+     *
+     * @return intent provided by transport or null if no intent was provided.
+     */
+    private Intent getIntentFromBackupTransport() {
+        try {
+            Intent intent =
+                    mBackupManager.getDataManagementIntent(mBackupManager.getCurrentTransport());
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                if (intent != null) {
+                    Log.d(TAG, "Parsed intent from backup transport: " + intent.toString());
+                } else {
+                    Log.d(TAG, "Received a null intent from backup transport");
+                }
+            }
+            return intent;
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error getting data management intent", e);
+        }
+        return null;
+    }
+
+    /** Checks if backup service is enabled for this user. */
+    private boolean isBackupServiceActive() {
+        boolean backupOkay;
+        try {
+            backupOkay = mBackupManager.isBackupServiceActive(UserHandle.myUserId());
+        } catch (Exception e) {
+            // things go wrong talking to the backup system => ignore and
+            // pass the default 'false' as the "backup is a thing?" state.
+            backupOkay = false;
+        }
+        return backupOkay;
+    }
+
+    @VisibleForTesting
+    String getLabelFromBackupTransport() {
+        try {
+            String label =
+                    mBackupManager.getDataManagementLabel(mBackupManager.getCurrentTransport());
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG, "Received the backup settings label from backup transport: " + label);
+            }
+            return label;
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error getting data management label", e);
+        }
+        return null;
+    }
+
+    @VisibleForTesting
+    String getSummaryFromBackupTransport() {
+        try {
+            String summary =
+                    mBackupManager.getDestinationString(mBackupManager.getCurrentTransport());
+            if (Log.isLoggable(TAG, Log.DEBUG)) {
+                Log.d(TAG,
+                        "Received the backup settings summary from backup transport: " + summary);
+            }
+            return summary;
+        } catch (RemoteException e) {
+            Log.e(TAG, "Error getting data management summary", e);
+        }
+        return null;
+    }
+}
diff --git a/src/com/android/settings/backup/BackupSettingsPreferenceController.java b/src/com/android/settings/backup/BackupSettingsPreferenceController.java
new file mode 100644
index 0000000..2c4605a
--- /dev/null
+++ b/src/com/android/settings/backup/BackupSettingsPreferenceController.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+
+import android.content.Context;
+import android.content.Intent;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.settings.core.PreferenceController;
+
+public class BackupSettingsPreferenceController extends PreferenceController {
+    private static final String BACKUP_SETTINGS = "backup_settings";
+    private static final  String MANUFACTURER_SETTINGS = "manufacturer_backup";
+    private Intent mBackupSettingsIntent;
+    private String mBackupSettingsTitle;
+    private String mBackupSettingsSummary;
+    private Intent mManufacturerIntent;
+    private String mManufacturerLabel;
+
+    public BackupSettingsPreferenceController(Context context) {
+        super(context);
+        BackupSettingsHelper settingsHelper = new BackupSettingsHelper(context);
+        mBackupSettingsIntent = settingsHelper.getIntentForBackupSettings();
+        mBackupSettingsTitle = settingsHelper.getLabelForBackupSettings();
+        mBackupSettingsSummary = settingsHelper.getSummaryForBackupSettings();
+        mManufacturerIntent = settingsHelper.getIntentProvidedByManufacturer();
+        mManufacturerLabel = settingsHelper.getLabelProvidedByManufacturer();
+    }
+
+    @Override
+    public void displayPreference(PreferenceScreen screen) {
+        Preference backupSettings = screen.findPreference(BACKUP_SETTINGS);
+        Preference manufacturerSettings = screen.findPreference(MANUFACTURER_SETTINGS);
+        backupSettings.setIntent(mBackupSettingsIntent);
+        backupSettings.setTitle(mBackupSettingsTitle);
+        backupSettings.setSummary(mBackupSettingsSummary);
+        manufacturerSettings.setIntent(mManufacturerIntent);
+        manufacturerSettings.setTitle(mManufacturerLabel);
+    }
+
+    /**
+     * Returns true if preference is available (should be displayed)
+     */
+    @Override
+    public boolean isAvailable() {
+        return true;
+    }
+
+    /**
+     * Returns the key for this preference.
+     */
+    @Override
+    public String getPreferenceKey() {
+        return null;
+    }
+}
diff --git a/src/com/android/settings/bluetooth/BluetoothDiscoveryReceiver.java b/src/com/android/settings/bluetooth/BluetoothDiscoveryReceiver.java
deleted file mode 100644
index 1ba9f85..0000000
--- a/src/com/android/settings/bluetooth/BluetoothDiscoveryReceiver.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2011 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.bluetooth;
-
-import android.bluetooth.BluetoothAdapter;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.util.Log;
-
-import com.android.settingslib.bluetooth.BluetoothEventManager;
-
-/**
- * BluetoothDiscoveryReceiver updates a timestamp when the
- * Bluetooth adapter starts or finishes discovery mode. This
- * is used to decide whether to open an alert dialog or
- * create a notification when we receive a pairing request.
- *
- * <p>Note that the discovery start/finish intents are also handled
- * by {@link BluetoothEventManager} to update the UI, if visible.
- */
-public final class BluetoothDiscoveryReceiver extends BroadcastReceiver {
-    private static final String TAG = "BluetoothDiscoveryReceiver";
-
-    @Override
-    public void onReceive(Context context, Intent intent) {
-        String action = intent.getAction();
-        Log.v(TAG, "Received: " + action);
-
-        if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED) ||
-                action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
-            LocalBluetoothPreferences.persistDiscoveringTimestamp(context);
-        }
-    }
-}
diff --git a/src/com/android/settings/bluetooth/DockService.java b/src/com/android/settings/bluetooth/DockService.java
index 020ca0c..52a015e 100644
--- a/src/com/android/settings/bluetooth/DockService.java
+++ b/src/com/android/settings/bluetooth/DockService.java
@@ -938,13 +938,7 @@
         public void onDeviceAdded(CachedBluetoothDevice cachedDevice) { }
         public void onDeviceDeleted(CachedBluetoothDevice cachedDevice) { }
         public void onConnectionStateChanged(CachedBluetoothDevice cachedDevice, int state) { }
-
-        @Override
-        public void onScanningStateChanged(boolean started) {
-            // TODO: Find a more unified place for a persistent BluetoothCallback to live
-            // as this is not exactly dock related.
-            LocalBluetoothPreferences.persistDiscoveringTimestamp(mContext);
-        }
+        public void onScanningStateChanged(boolean started) { }
 
         @Override
         public void onDeviceBondStateChanged(CachedBluetoothDevice cachedDevice, int bondState) {
diff --git a/src/com/android/settings/bluetooth/LocalBluetoothPreferences.java b/src/com/android/settings/bluetooth/LocalBluetoothPreferences.java
index 6150920..6a0bdcf 100644
--- a/src/com/android/settings/bluetooth/LocalBluetoothPreferences.java
+++ b/src/com/android/settings/bluetooth/LocalBluetoothPreferences.java
@@ -40,8 +40,6 @@
     // of raising notifications
     private static final int GRACE_PERIOD_TO_SHOW_DIALOGS_IN_FOREGROUND = 60 * 1000;
 
-    private static final String KEY_DISCOVERING_TIMESTAMP = "last_discovering_time";
-
     private static final String KEY_LAST_SELECTED_DEVICE = "last_selected_device";
 
     private static final String KEY_LAST_SELECTED_DEVICE_TIME = "last_selected_device_time";
@@ -95,11 +93,14 @@
 
         // If the device was discoverING recently
         LocalBluetoothAdapter adapter = manager.getBluetoothAdapter();
-        if (adapter != null && adapter.isDiscovering()) {
-            return true;
-        } else if ((sharedPreferences.getLong(KEY_DISCOVERING_TIMESTAMP, 0) +
+        if (adapter != null) {
+            if (adapter.isDiscovering()) {
+                return true;
+            }
+            if ((adapter.getDiscoveryEndMillis() +
                 GRACE_PERIOD_TO_SHOW_DIALOGS_IN_FOREGROUND) > currentTimeMillis) {
-            return true;
+                return true;
+            }
         }
 
         // If the device was picked in the device picker recently
@@ -147,20 +148,6 @@
         editor.apply();
     }
 
-    static void persistDiscoveringTimestamp(final Context context) {
-        // Load the shared preferences and edit it on a background
-        // thread (but serialized!).
-        QueuedWork.queue(new Runnable() {
-                public void run() {
-                    SharedPreferences.Editor editor = getSharedPreferences(context).edit();
-                    editor.putLong(
-                            KEY_DISCOVERING_TIMESTAMP,
-                        System.currentTimeMillis());
-                    editor.apply();
-                }
-            }, false);
-    }
-
     static boolean hasDockAutoConnectSetting(Context context, String addr) {
         return getSharedPreferences(context).contains(KEY_DOCK_AUTO_CONNECT + addr);
     }
diff --git a/src/com/android/settings/core/instrumentation/MetricsFeatureProviderImpl.java b/src/com/android/settings/core/instrumentation/MetricsFeatureProviderImpl.java
index b74c886..091eb54 100644
--- a/src/com/android/settings/core/instrumentation/MetricsFeatureProviderImpl.java
+++ b/src/com/android/settings/core/instrumentation/MetricsFeatureProviderImpl.java
@@ -34,6 +34,7 @@
 
     protected void installLogWriters() {
         mLoggerWriters.add(new EventLogWriter());
+        mLoggerWriters.add(new SettingSuggestionsLogWriter());
     }
 
     @Override
diff --git a/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java b/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java
new file mode 100644
index 0000000..4c277fb
--- /dev/null
+++ b/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.core.instrumentation;
+
+import android.content.Context;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.internal.logging.MetricsLogger;
+import com.android.settings.suggestions.EventStore;
+
+/**
+ * {@link LogWriter} that writes setting suggestion related logs.
+ */
+public class SettingSuggestionsLogWriter implements LogWriter {
+
+    private EventStore mEventStore;
+
+    @Override
+    public void visible(Context context, int category) {
+    }
+
+    @Override
+    public void hidden(Context context, int category) {
+    }
+
+    @Override
+    public void action(Context context, int category) {
+    }
+
+    @Override
+    public void action(Context context, int category, int value) {
+    }
+
+    @Override
+    public void action(Context context, int category, boolean value) {
+    }
+
+    @Override
+    public void action(Context context, int category, String pkg) {
+        if (mEventStore == null) {
+            mEventStore = new EventStore(context);
+        }
+        switch (category) {
+            case MetricsEvent.ACTION_SHOW_SETTINGS_SUGGESTION:
+                mEventStore.writeEvent(pkg, EventStore.EVENT_SHOWN);
+                break;
+            case MetricsEvent.ACTION_SETTINGS_DISMISS_SUGGESTION:
+                mEventStore.writeEvent(pkg, EventStore.EVENT_DISMISSED);
+                break;
+            case MetricsEvent.ACTION_SETTINGS_SUGGESTION:
+                mEventStore.writeEvent(pkg, EventStore.EVENT_CLICKED);
+                break;
+        }
+    }
+
+    @Override
+    public void count(Context context, String name, int value) {
+    }
+
+    @Override
+    public void histogram(Context context, String name, int bucket) {
+    }
+
+}
diff --git a/src/com/android/settings/dashboard/DashboardSummary.java b/src/com/android/settings/dashboard/DashboardSummary.java
index 9d64d4c..fddf2d7 100644
--- a/src/com/android/settings/dashboard/DashboardSummary.java
+++ b/src/com/android/settings/dashboard/DashboardSummary.java
@@ -36,6 +36,9 @@
 import com.android.settings.dashboard.conditional.ConditionManager;
 import com.android.settings.dashboard.conditional.FocusRecyclerView;
 import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.suggestions.EventStore;
+import com.android.settings.suggestions.SuggestionFeaturizer;
+import com.android.settings.suggestions.SuggestionRanker;
 import com.android.settingslib.SuggestionParser;
 import com.android.settingslib.drawer.CategoryKey;
 import com.android.settingslib.drawer.DashboardCategory;
@@ -66,11 +69,13 @@
     private SummaryLoader mSummaryLoader;
     private ConditionManager mConditionManager;
     private SuggestionParser mSuggestionParser;
+    private SuggestionRanker mSuggestionRanker;
     private LinearLayoutManager mLayoutManager;
     private SuggestionsChecks mSuggestionsChecks;
     private ArrayList<String> mSuggestionsShownLogged;
     private ArrayList<String> mSuggestionsHiddenLogged;
     private DashboardFeatureProvider mDashboardFeatureProvider;
+    private SuggestionFeatureProvider mSuggestionFeatureProvider;
 
     @Override
     public int getMetricsCategory() {
@@ -84,6 +89,8 @@
         final Activity activity = getActivity();
         mDashboardFeatureProvider = FeatureFactory.getFactory(activity)
                 .getDashboardFeatureProvider(activity);
+        mSuggestionFeatureProvider = FeatureFactory.getFactory(activity)
+                .getSuggestionFeatureProvider();
 
         if (mDashboardFeatureProvider.isEnabled()) {
             mSummaryLoader = new SummaryLoader(activity, CategoryKey.CATEGORY_HOMEPAGE);
@@ -95,6 +102,8 @@
         mConditionManager = ConditionManager.get(activity, false);
         mSuggestionParser = new SuggestionParser(activity,
                 activity.getSharedPreferences(SUGGESTIONS, 0), R.xml.suggestion_ordering);
+        mSuggestionRanker = new SuggestionRanker(
+                new SuggestionFeaturizer(new EventStore(activity)));
         mSuggestionsChecks = new SuggestionsChecks(getContext());
         if (savedInstanceState == null) {
             mSuggestionsShownLogged = new ArrayList<>();
@@ -260,6 +269,16 @@
         protected List<Tile> doInBackground(Void... params) {
             final Context context = getContext();
             List<Tile> suggestions = mSuggestionParser.getSuggestions();
+            if (mSuggestionFeatureProvider.isSmartSuggestionEnabled(context)) {
+                List<String> suggestionIds = new ArrayList<>(suggestions.size());
+                for (Tile suggestion : suggestions) {
+                    suggestionIds.add(
+                        DashboardAdapter.getSuggestionIdentifier(context, suggestion));
+                }
+                // TODO: create a Suggestion class to maintain the id and other info
+                mSuggestionRanker.rank(suggestions, suggestionIds);
+                // TODO: consider showing only top-k (e.g., top-3)
+            }
             for (int i = 0; i < suggestions.size(); i++) {
                 Tile suggestion = suggestions.get(i);
                 if (mSuggestionsChecks.isSuggestionComplete(suggestion)) {
diff --git a/src/com/android/settings/deviceinfo/StorageSettings.java b/src/com/android/settings/deviceinfo/StorageSettings.java
index 53d4c85..b79560a 100644
--- a/src/com/android/settings/deviceinfo/StorageSettings.java
+++ b/src/com/android/settings/deviceinfo/StorageSettings.java
@@ -279,8 +279,19 @@
             if (vol.getType() == VolumeInfo.TYPE_PRIVATE) {
                 final Bundle args = new Bundle();
                 args.putString(VolumeInfo.EXTRA_VOLUME_ID, vol.getId());
-                startFragment(this, StorageDashboardFragment.class.getCanonicalName(),
-                        -1, 0, args);
+
+                if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
+                    startFragment(this, StorageDashboardFragment.class.getCanonicalName(),
+                            -1, 0, args);
+                } else {
+                    // TODO: Go to the StorageDashboardFragment once it fully handles all of the
+                    //       SD card cases and other private internal storage cases.
+                    PrivateVolumeSettings.setVolumeSize(args, PrivateStorageInfo.getTotalSize(vol,
+                            sTotalInternalStorage));
+                    startFragment(this, PrivateVolumeSettings.class.getCanonicalName(),
+                            -1, 0, args);
+                }
+
                 return true;
 
             } else if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
diff --git a/src/com/android/settings/location/LocationSettings.java b/src/com/android/settings/location/LocationSettings.java
index d6ff4dc..4177afb 100644
--- a/src/com/android/settings/location/LocationSettings.java
+++ b/src/com/android/settings/location/LocationSettings.java
@@ -18,7 +18,6 @@
 
 import android.app.Activity;
 import android.app.admin.DevicePolicyManager;
-import android.content.ActivityNotFoundException;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -96,14 +95,11 @@
     private static final String KEY_LOCATION_MODE = "location_mode";
     /** Key for preference category "Recent location requests" */
     private static final String KEY_RECENT_LOCATION_REQUESTS = "recent_location_requests";
-    /** Key for preference "App-level permissions" */
-    private static final String KEY_APP_LEVEL_PERMISSIONS = "app_level_permissions";
     /** Key for preference category "Location services" */
     private static final String KEY_LOCATION_SERVICES = "location_services";
 
     private static final int MENU_SCANNING = Menu.FIRST;
 
-    private static final String KEY_LOCATION_PERMISSION = "android.permission-group.LOCATION";
     private SwitchBar mSwitchBar;
     private Switch mSwitch;
     private boolean mValidListener = false;
@@ -211,11 +207,6 @@
         final AppLocationPermissionPreferenceController preferenceController =
                 new AppLocationPermissionPreferenceController(activity);
         preferenceController.displayPreference(root);
-        if (preferenceController.isAvailable()) {
-            Preference preferenceAppLevelPermissions =
-                    root.findPreference(KEY_APP_LEVEL_PERMISSIONS);
-            setupAppLevelPermissionsPreference(preferenceAppLevelPermissions);
-        }
 
         mCategoryRecentLocationRequests =
                 (PreferenceCategory) root.findPreference(KEY_RECENT_LOCATION_REQUESTS);
@@ -276,23 +267,6 @@
         }
     }
 
-    private void setupAppLevelPermissionsPreference(Preference preference) {
-        preference.setOnPreferenceClickListener(
-                new Preference.OnPreferenceClickListener() {
-                    @Override
-                    public boolean onPreferenceClick(Preference preference) {
-                        Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSION_APPS)
-                                .putExtra(Intent.EXTRA_PERMISSION_NAME, KEY_LOCATION_PERMISSION);
-                        try {
-                            getActivity().startActivity(intent);
-                        } catch (ActivityNotFoundException e) {
-                            Log.w("Permission", "No app to handle " + intent);
-                        }
-                        return true;
-                    }
-                });
-    }
-
     private void changeManagedProfileLocationAccessStatus(boolean mainSwitchOn) {
         if (mManagedProfileSwitch == null) {
             return;
diff --git a/src/com/android/settings/notification/WorkSoundPreferenceController.java b/src/com/android/settings/notification/WorkSoundPreferenceController.java
index 96d88c9..c94991c 100644
--- a/src/com/android/settings/notification/WorkSoundPreferenceController.java
+++ b/src/com/android/settings/notification/WorkSoundPreferenceController.java
@@ -160,9 +160,8 @@
     }
 
     private CharSequence updateRingtoneName(Context context, int type) {
-        if (context == null) {
-            Log.e(TAG, "Unable to update ringtone name, no context provided");
-            return null;
+        if (context == null || !UserManager.get(context).isUserUnlocked(context.getUserId())) {
+            return context.getString(R.string.managed_profile_not_available_label);
         }
         Uri ringtoneUri = RingtoneManager.getActualDefaultRingtoneUri(context, type);
         return Ringtone.getTitle(context, ringtoneUri, false /* followSettingsUri */,
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index aa3c257..4a73469 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -37,6 +37,7 @@
 import com.android.settings.applications.AdvancedAppSettings;
 import com.android.settings.applications.AppAndNotificationDashboardFragment;
 import com.android.settings.applications.SpecialAccessSettings;
+import com.android.settings.backup.BackupSettingsFragment;
 import com.android.settings.bluetooth.BluetoothSettings;
 import com.android.settings.connecteddevice.ConnectedDeviceDashboardFragment;
 import com.android.settings.datausage.DataUsageMeteredSettings;
@@ -156,6 +157,7 @@
                 NO_DATA_RES_ID, R.drawable.ic_settings_language);
         addIndex(PhysicalKeyboardFragment.class, NO_DATA_RES_ID, R.drawable.ic_settings_language);
         addIndex(PrivacySettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_backup);
+        addIndex(BackupSettingsFragment.class, NO_DATA_RES_ID, R.drawable.ic_settings_backup);
         addIndex(DateTimeSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_date_time);
         addIndex(AccessibilitySettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_accessibility);
         addIndex(PrintSettingsFragment.class, NO_DATA_RES_ID, R.drawable.ic_settings_print);
diff --git a/src/com/android/settings/suggestions/EventStore.java b/src/com/android/settings/suggestions/EventStore.java
new file mode 100644
index 0000000..bf94f48
--- /dev/null
+++ b/src/com/android/settings/suggestions/EventStore.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package com.android.settings.suggestions;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * Stores suggestion related statistics.
+ */
+public class EventStore {
+
+    public static final String TAG = "SuggestionEventStore";
+
+    public static final String EVENT_SHOWN = "shown";
+    public static final String EVENT_DISMISSED = "dismissed";
+    public static final String EVENT_CLICKED = "clicked";
+    public static final String METRIC_LAST_EVENT_TIME = "last_event_time";
+    public static final String METRIC_COUNT = "count";
+
+    private static final Set<String> EVENTS = new HashSet<String>(
+            Arrays.asList(new String[] {EVENT_SHOWN, EVENT_DISMISSED, EVENT_CLICKED}));
+    private static final Set<String> METRICS = new HashSet<String>(
+            Arrays.asList(new String[] {METRIC_LAST_EVENT_TIME, METRIC_COUNT}));
+
+    private final SharedPreferences mSharedPrefs;
+
+    public EventStore(Context context) {
+        mSharedPrefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
+    }
+
+    /**
+     * Writes individual log events.
+     * @param pkgName: Package for which this event is reported.
+     * @param eventType: Type of event (one of {@link #EVENTS}).
+     */
+    public void writeEvent(String pkgName, String eventType) {
+        if (!EVENTS.contains(eventType)) {
+            Log.w(TAG, "Reported event type " + eventType + " is not a valid type!");
+            return;
+        }
+        final String lastTimePrefKey = getPrefKey(pkgName, eventType, METRIC_LAST_EVENT_TIME);
+        final String countPrefKey = getPrefKey(pkgName, eventType, METRIC_COUNT);
+        writePref(lastTimePrefKey, System.currentTimeMillis());
+        writePref(countPrefKey, readPref(countPrefKey, (long) 0) + 1);
+    }
+
+    /**
+     * Reads metric of the the reported events (e.g., counts).
+     * @param pkgName: Package for which this metric is queried.
+     * @param eventType: Type of event (one of {@link #EVENTS}).
+     * @param metricType: Type of the queried metric (one of {@link #METRICS}).
+     * @return the corresponding metric.
+     */
+    public long readMetric(String pkgName, String eventType, String metricType) {
+        if (!EVENTS.contains(eventType)) {
+            Log.w(TAG, "Reported event type " + eventType + " is not a valid event!");
+            return 0;
+        } else if (!METRICS.contains(metricType)) {
+            Log.w(TAG, "Required stat type + " + metricType + " is not a valid stat!");
+            return 0;
+        }
+        return readPref(getPrefKey(pkgName, eventType, metricType), (long) 0);
+    }
+
+    private void writePref(String prefKey, long value) {
+        mSharedPrefs.edit().putLong(prefKey, value).commit();
+    }
+
+    private long readPref(String prefKey, Long defaultValue) {
+        return mSharedPrefs.getLong(prefKey, defaultValue);
+    }
+
+    private String getPrefKey(String pkgName, String eventType, String statType) {
+        return new StringBuilder()
+                .append("setting_suggestion_")
+                .append(pkgName)
+                .append("_")
+                .append(eventType)
+                .append("_")
+                .append(statType)
+                .toString();
+    }
+}
diff --git a/src/com/android/settings/suggestions/SuggestionFeaturizer.java b/src/com/android/settings/suggestions/SuggestionFeaturizer.java
new file mode 100644
index 0000000..eb43272
--- /dev/null
+++ b/src/com/android/settings/suggestions/SuggestionFeaturizer.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package com.android.settings.suggestions;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Creates a set of interaction features (i.e., metrics) to represent each setting suggestion. These
+ * features currently include normalized time from previous events (shown, dismissed and clicked)
+ * for any particular suggestion and also counts of these events. These features are used as signals
+ * to find the best ranking for suggestion items.
+ */
+public class SuggestionFeaturizer {
+
+    // Key of the features used for ranking.
+    public static final String FEATURE_IS_SHOWN = "is_shown";
+    public static final String FEATURE_IS_DISMISSED = "is_dismissed";
+    public static final String FEATURE_IS_CLICKED = "is_clicked";
+    public static final String FEATURE_TIME_FROM_LAST_SHOWN = "time_from_last_shown";
+    public static final String FEATURE_TIME_FROM_LAST_DISMISSED = "time_from_last_dismissed";
+    public static final String FEATURE_TIME_FROM_LAST_CLICKED = "time_from_last_clicked";
+    public static final String FEATURE_SHOWN_COUNT = "shown_count";
+    public static final String FEATURE_DISMISSED_COUNT = "dismissed_count";
+    public static final String FEATURE_CLICKED_COUNT = "clicked_count";
+
+    // The following numbers are estimated from histograms.
+    public static final double TIME_NORMALIZATION_FACTOR = 2e10;
+    public static final double COUNT_NORMALIZATION_FACTOR = 500;
+
+    private final EventStore mEventStore;
+
+    /**
+     * Constructor
+     *
+     * @param eventStore An instance of {@code EventStore} which maintains the recorded suggestion
+     * events.
+     */
+    public SuggestionFeaturizer(EventStore eventStore) {
+        mEventStore = eventStore;
+    }
+
+    /**
+     * Extracts the features for each package name.
+     *
+     * @param pkgNames: List of package names for which features are queried.
+     * @return A Map containing the features, keyed by the package names. Each map value contains
+     * another map with key-value pairs of the features.
+     */
+    public Map<String, Map<String, Double>> featurize(List<String> pkgNames) {
+        Map<String, Map<String, Double>> features = new HashMap<>();
+        Long curTimeMs = System.currentTimeMillis();
+        for (String pkgName : pkgNames) {
+            Map<String, Double> featureMap = new HashMap<>();
+            features.put(pkgName, featureMap);
+            Long lastShownTime = mEventStore
+                    .readMetric(pkgName, EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME);
+            Long lastDismissedTime = mEventStore.readMetric(pkgName, EventStore.EVENT_DISMISSED,
+                    EventStore.METRIC_LAST_EVENT_TIME);
+            Long lastClickedTime = mEventStore.readMetric(pkgName, EventStore.EVENT_CLICKED,
+                    EventStore.METRIC_LAST_EVENT_TIME);
+            featureMap.put(FEATURE_IS_SHOWN, booleanToDouble(lastShownTime > 0));
+            featureMap.put(FEATURE_IS_DISMISSED, booleanToDouble(lastDismissedTime > 0));
+            featureMap.put(FEATURE_IS_CLICKED, booleanToDouble(lastClickedTime > 0));
+            featureMap.put(FEATURE_TIME_FROM_LAST_SHOWN,
+                    normalizedTimeDiff(curTimeMs, lastShownTime));
+            featureMap.put(FEATURE_TIME_FROM_LAST_DISMISSED,
+                    normalizedTimeDiff(curTimeMs, lastDismissedTime));
+            featureMap.put(FEATURE_TIME_FROM_LAST_CLICKED,
+                    normalizedTimeDiff(curTimeMs, lastClickedTime));
+            featureMap.put(FEATURE_SHOWN_COUNT, normalizedCount(mEventStore
+                    .readMetric(pkgName, EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT)));
+            featureMap.put(FEATURE_DISMISSED_COUNT, normalizedCount(mEventStore
+                    .readMetric(pkgName, EventStore.EVENT_DISMISSED, EventStore.METRIC_COUNT)));
+            featureMap.put(FEATURE_CLICKED_COUNT, normalizedCount(mEventStore
+                    .readMetric(pkgName, EventStore.EVENT_CLICKED, EventStore.METRIC_COUNT)));
+        }
+        return features;
+    }
+
+    private static double booleanToDouble(boolean bool) {
+        return bool ? 1 : 0;
+    }
+
+    private static double normalizedTimeDiff(long curTimeMs, long preTimeMs) {
+        return Math.min(1, (curTimeMs - preTimeMs) / TIME_NORMALIZATION_FACTOR);
+    }
+
+    private static double normalizedCount(long count) {
+        return Math.min(1, count / COUNT_NORMALIZATION_FACTOR);
+    }
+}
diff --git a/src/com/android/settings/suggestions/SuggestionRanker.java b/src/com/android/settings/suggestions/SuggestionRanker.java
new file mode 100644
index 0000000..d0b9140
--- /dev/null
+++ b/src/com/android/settings/suggestions/SuggestionRanker.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+package com.android.settings.suggestions;
+
+import com.android.settingslib.drawer.Tile;
+
+import android.support.annotation.VisibleForTesting;
+
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class SuggestionRanker {
+
+    private static final String TAG = "SuggestionRanker";
+
+    // The following coefficients form a linear model, which mixes the features to obtain a
+    // relevance metric for ranking the suggestion items. This model is learned with off-line data
+    // by training a binary classifier to detect the clicked items. The higher the obtained
+    // relevance metric, the higher chance of getting clicked.
+    private static final Map<String, Double> WEIGHTS = new HashMap<String, Double>() {{
+        put(SuggestionFeaturizer.FEATURE_IS_SHOWN, 4.07506758256);
+        put(SuggestionFeaturizer.FEATURE_IS_DISMISSED, 2.11535473578);
+        put(SuggestionFeaturizer.FEATURE_IS_CLICKED, 1.21885461304);
+        put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN, 3.18832024515);
+        put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED, 1.09902706645);
+        put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED, 0.262631082877);
+        put(SuggestionFeaturizer.FEATURE_SHOWN_COUNT, -0.918484103748 * 240);
+    }};
+
+    private final SuggestionFeaturizer mSuggestionFeaturizer;
+
+    private final Map<Tile, Double> relevanceMetrics;
+
+    Comparator<Tile> suggestionComparator = new Comparator<Tile>() {
+        @Override
+        public int compare(Tile suggestion1, Tile suggestion2) {
+            return relevanceMetrics.get(suggestion1) < relevanceMetrics.get(suggestion2) ? 1 : -1;
+        }
+    };
+
+    public SuggestionRanker(SuggestionFeaturizer suggestionFeaturizer) {
+        mSuggestionFeaturizer = suggestionFeaturizer;
+        relevanceMetrics = new HashMap<Tile, Double>();
+    }
+
+    public void rank(final List<Tile> suggestions, List<String> suggestionIds) {
+        relevanceMetrics.clear();
+        Map<String, Map<String, Double>> features = mSuggestionFeaturizer.featurize(suggestionIds);
+        for (int i = 0; i < suggestionIds.size(); i++) {
+            relevanceMetrics.put(suggestions.get(i),
+                    getRelevanceMetric(features.get(suggestionIds.get(i))));
+        }
+        Collections.sort(suggestions, suggestionComparator);
+    }
+
+    @VisibleForTesting
+    double getRelevanceMetric(Map<String, Double> features) {
+        double sum = 0;
+        if (features == null) {
+            return sum;
+        }
+        for (String feature : WEIGHTS.keySet()) {
+            sum += WEIGHTS.get(feature) * features.get(feature);
+        }
+        return sum;
+    }
+}
diff --git a/src/com/android/settings/widget/LinkTextView.java b/src/com/android/settings/widget/LinkTextView.java
deleted file mode 100644
index e0fa723..0000000
--- a/src/com/android/settings/widget/LinkTextView.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2014 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.widget;
-
-import android.content.Context;
-import android.support.annotation.NonNull;
-import android.support.v13.view.ViewCompat;
-import android.text.Spanned;
-import android.text.method.LinkMovementMethod;
-import android.text.style.ClickableSpan;
-import android.util.AttributeSet;
-import android.view.MotionEvent;
-import android.widget.TextView;
-import com.android.setupwizardlib.util.LinkAccessibilityHelper;
-
-/**
- * Copied from setup wizard.
- */
-public class LinkTextView extends TextView {
-
-    private LinkAccessibilityHelper mAccessibilityHelper;
-
-    public LinkTextView(Context context) {
-        this(context, null);
-    }
-
-    public LinkTextView(Context context, AttributeSet attrs) {
-        super(context, attrs);
-        mAccessibilityHelper = new LinkAccessibilityHelper(this);
-        ViewCompat.setAccessibilityDelegate(this, mAccessibilityHelper);
-    }
-
-    @Override
-    public void setText(CharSequence text, BufferType type) {
-        super.setText(text, type);
-        if (text instanceof Spanned) {
-            final ClickableSpan[] spans =
-                    ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
-            if (spans.length > 0) {
-                setMovementMethod(LinkMovementMethod.getInstance());
-            }
-        }
-    }
-
-    @Override
-    protected boolean dispatchHoverEvent(@NonNull MotionEvent event) {
-        if (mAccessibilityHelper.dispatchHoverEvent(event)) {
-            return true;
-        }
-        return super.dispatchHoverEvent(event);
-    }
-}
diff --git a/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java b/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java
new file mode 100644
index 0000000..0205124
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/backup/BackupSettingsHelperTest.java
@@ -0,0 +1,388 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+import android.app.backup.BackupManager;
+import android.app.backup.IBackupManager;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.content.res.Resources;
+import android.os.IBinder;
+import android.os.RemoteException;
+
+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;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.anyString;
+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 com.android.settings.R;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settingslib.drawer.SettingsDrawerActivity;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
+        shadows = {BackupSettingsHelperTest.ShadowBackupManagerStub.class})
+public class BackupSettingsHelperTest {
+
+    private static final String DEFAULT_SETTINGS_CLASSNAME =
+            "com.android.settings.Settings$PrivacySettingsActivity";
+
+    private static final int DEFAULT_SUMMARY_RESOURCE =
+            R.string.backup_configure_account_default_summary;
+
+    private static final int DEFAULT_LABEL_RESOURCE =
+            R.string.privacy_settings_title;
+
+    private static final int MANUFACTURER_INTENT_RESOURCE = R.string.config_backup_settings_intent;
+
+    private static final int MANUFACTURER_LABEL_RESOURCE = R.string.config_backup_settings_label;
+
+    private Context mContext;
+
+    private BackupSettingsHelper mBackupSettingsHelper;
+
+    @Mock
+    private static IBackupManager mBackupManager;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+        when(mBackupManager.getCurrentTransport()).thenReturn("test_transport");
+        mBackupSettingsHelper = new BackupSettingsHelper(mContext);
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport() throws Exception {
+        Intent intent = new Intent();
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        verify(mBackupManager).getDataManagementIntent(anyString());
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_WithIntent() throws Exception {
+        Intent intent = mock(Intent.class);
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent).isEqualTo(intent);
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_WithNullIntent() throws Exception {
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(null);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent).isNull();
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_RemoteException() throws Exception {
+        when(mBackupManager.getDataManagementIntent(anyString())).thenThrow(new RemoteException());
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent).isNull();
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_BackupEnabled() throws Exception {
+        Intent intent = new Intent("test_intent");
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+        when(mBackupManager.isBackupServiceActive(anyInt())).thenReturn(true);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
+                .isEqualTo(true);
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_BackupDisabled() throws Exception {
+        Intent intent = new Intent("test_intent");
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+        when(mBackupManager.isBackupServiceActive(anyInt())).thenReturn(false);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
+                .isEqualTo(false);
+    }
+
+    @Test
+    public void testGetIntentFromBackupTransport_BackupStatusException() throws Exception {
+        Intent intent = new Intent("test_intent");
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+        when(mBackupManager.isBackupServiceActive(anyInt())).thenThrow(new RemoteException());
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettingsFromTransport();
+
+        assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
+                .isEqualTo(false);
+    }
+
+    @Test
+    public void testIsIntentProvidedByTransport_WithNullIntent() throws Exception {
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(null);
+
+        boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport();
+
+        assertThat(isIntentProvided).isFalse();
+    }
+
+    @Test
+    public void testIsIntentProvidedByTransport_WithInvalidIntent() throws Exception {
+        Intent intent = mock(Intent.class);
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+
+        PackageManager packageManager = mock(PackageManager.class);
+        when(mContext.getPackageManager()).thenReturn(packageManager);
+        when(intent.resolveActivity(packageManager)).thenReturn(null);
+
+        boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport();
+
+        assertThat(isIntentProvided).isFalse();
+    }
+
+    @Test
+    public void testIsIntentProvidedByTransport_WithIntent() throws Exception {
+        Intent intent = mock(Intent.class);
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+
+        PackageManager packageManager = mock(PackageManager.class);
+        when(mContext.getPackageManager()).thenReturn(packageManager);
+        when(intent.resolveActivity(packageManager)).thenReturn(mock(ComponentName.class));
+
+        boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport();
+
+        assertThat(isIntentProvided).isTrue();
+    }
+
+    @Test
+    public void testGetSummaryFromBackupTransport() throws Exception {
+        String summary = "test_summary";
+
+        when(mBackupManager.getDestinationString(anyString())).thenReturn(summary);
+
+        String backupSummary = mBackupSettingsHelper.getSummaryFromBackupTransport();
+
+        assertThat(backupSummary).isEqualTo(summary);
+    }
+
+    @Test
+    public void testGetSummaryFromBackupTransport_RemoteException() throws Exception {
+        when(mBackupManager.getDestinationString(anyString())).thenThrow(new RemoteException());
+
+        String backupSummary = mBackupSettingsHelper.getSummaryFromBackupTransport();
+
+        assertThat(backupSummary).isNull();
+    }
+
+    @Test
+    public void testGetLabelBackupTransport() throws Exception {
+        String label = "test_label";
+
+        when(mBackupManager.getDataManagementLabel(anyString())).thenReturn(label);
+
+        String backupLabel = mBackupSettingsHelper.getLabelFromBackupTransport();
+
+        assertThat(backupLabel).isEqualTo(label);
+    }
+
+    @Test
+    public void testGetLabelBackupTransport_RemoteException() throws Exception {
+        when(mBackupManager.getDataManagementLabel(anyString())).thenThrow(new RemoteException());
+
+        String backupLabel = mBackupSettingsHelper.getLabelFromBackupTransport();
+
+        assertThat(backupLabel).isNull();
+    }
+
+    @Test
+    public void testGetIntentForBackupSettings_WithIntentFromTransport() throws Exception {
+        Intent intent = mock(Intent.class);
+
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
+
+        PackageManager packageManager = mock(PackageManager.class);
+        when(mContext.getPackageManager()).thenReturn(packageManager);
+        when(intent.resolveActivity(packageManager)).thenReturn(mock(ComponentName.class));
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
+
+        assertThat(backupIntent).isEqualTo(intent);
+    }
+
+    @Test
+    public void testGetIntentForBackupSettings_WithoutIntentFromTransport() throws Exception {
+        when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(null);
+
+        Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
+
+        assertThat(backupIntent.getComponent().getClassName()).isEqualTo(
+                DEFAULT_SETTINGS_CLASSNAME);
+        assertThat(backupIntent.getExtras().getBoolean(
+                SettingsDrawerActivity.EXTRA_SHOW_MENU)).isTrue();
+    }
+
+    @Test
+    public void testGetLabelForBackupSettings_WithLabelFromTransport() throws Exception {
+        String label = "test_label";
+
+        when(mBackupManager.getDataManagementLabel(anyString())).thenReturn(label);
+
+        String backupLabel = mBackupSettingsHelper.getLabelForBackupSettings();
+
+        assertThat(backupLabel).isEqualTo(label);
+    }
+
+    @Test
+    public void testGetLabelForBackupSettings_WithEmptyLabelFromTransport() throws Exception {
+        String label = "";
+
+        when(mBackupManager.getDataManagementLabel(anyString())).thenReturn(label);
+
+        String backupLabel = mBackupSettingsHelper.getLabelForBackupSettings();
+
+        assertThat(backupLabel).isEqualTo(mContext.getString(DEFAULT_LABEL_RESOURCE));
+    }
+
+    @Test
+    public void testGetLabelForBackupSettings_WithoutLabelFromTransport() throws Exception {
+        when(mBackupManager.getDataManagementLabel(anyString())).thenReturn(null);
+
+        String backupLabel = mBackupSettingsHelper.getLabelForBackupSettings();
+
+        assertThat(backupLabel).isEqualTo(mContext.getString(DEFAULT_LABEL_RESOURCE));
+    }
+
+    @Test
+    public void testGetSummaryForBackupSettings_WithSummaryFromTransport() throws Exception {
+        String summary = "test_summary";
+
+        when(mBackupManager.getDestinationString(anyString())).thenReturn(summary);
+
+        String backupSummary = mBackupSettingsHelper.getSummaryForBackupSettings();
+
+        assertThat(backupSummary).isEqualTo(summary);
+    }
+
+    @Test
+    public void testGetSummaryForBackupSettings_WithoutSummaryFromTransport() throws Exception {
+        when(mBackupManager.getDestinationString(anyString())).thenReturn(null);
+
+        String backupSummary = mBackupSettingsHelper.getSummaryForBackupSettings();
+
+        assertThat(backupSummary).isEqualTo(mContext.getString(DEFAULT_SUMMARY_RESOURCE));
+    }
+
+    @Test
+    public void testIsBackupProvidedByManufacturer_WithIntent() throws Exception {
+        String intent = "test_intent";
+
+        when(mContext.getApplicationContext()).thenReturn(mContext);
+        Resources spiedResources = spy(mContext.getResources());
+        when(mContext.getResources()).thenReturn(spiedResources);
+        when(spiedResources.getString(MANUFACTURER_INTENT_RESOURCE)).thenReturn(intent);
+        mBackupSettingsHelper = new BackupSettingsHelper(mContext);
+
+        boolean hasManufacturerIntent = mBackupSettingsHelper.isBackupProvidedByManufacturer();
+
+        assertThat(hasManufacturerIntent).isTrue();
+    }
+
+    @Test
+    public void testIsBackupProvidedByManufacturer_WithoutIntent() throws Exception {
+        String intent = "";
+
+        when(mContext.getApplicationContext()).thenReturn(mContext);
+        Resources spiedResources = spy(mContext.getResources());
+        when(mContext.getResources()).thenReturn(spiedResources);
+        when(spiedResources.getString(MANUFACTURER_INTENT_RESOURCE)).thenReturn(intent);
+        mBackupSettingsHelper = new BackupSettingsHelper(mContext);
+
+        boolean hasManufacturerIntent = mBackupSettingsHelper.isBackupProvidedByManufacturer();
+
+        assertThat(hasManufacturerIntent).isFalse();
+    }
+
+    @Test
+    public void testGetLabelProvidedByManufacturer() throws Exception {
+        String label = "test_label";
+
+        when(mContext.getApplicationContext()).thenReturn(mContext);
+        Resources spiedResources = spy(mContext.getResources());
+        when(mContext.getResources()).thenReturn(spiedResources);
+        when(spiedResources.getString(MANUFACTURER_LABEL_RESOURCE)).thenReturn(label);
+        mBackupSettingsHelper = new BackupSettingsHelper(mContext);
+
+        String manufacturerLabel = mBackupSettingsHelper.getLabelProvidedByManufacturer();
+
+        assertThat(manufacturerLabel).isEqualTo(label);
+    }
+
+    @Test
+    public void testGetIntentProvidedByManufacturer() throws Exception {
+        String intent = "test_intent";
+
+        when(mContext.getApplicationContext()).thenReturn(mContext);
+        Resources spiedResources = spy(mContext.getResources());
+        when(mContext.getResources()).thenReturn(spiedResources);
+        when(spiedResources.getString(MANUFACTURER_INTENT_RESOURCE)).thenReturn(intent);
+        mBackupSettingsHelper = new BackupSettingsHelper(mContext);
+
+        Intent manufacturerIntent = mBackupSettingsHelper.getIntentProvidedByManufacturer();
+
+        assertThat(manufacturerIntent).isNotNull();
+    }
+
+    @Implements(IBackupManager.Stub.class)
+    public static class ShadowBackupManagerStub {
+        @Implementation
+        public static IBackupManager asInterface(IBinder iBinder) {
+            return mBackupManager;
+        }
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/backup/BackupSettingsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/backup/BackupSettingsPreferenceControllerTest.java
new file mode 100644
index 0000000..7157862
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/backup/BackupSettingsPreferenceControllerTest.java
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.backup;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+
+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;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
+
+import static com.google.common.truth.Truth.assertThat;
+
+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.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
+        shadows = {BackupSettingsPreferenceControllerTest.ShadowBackupSettingsHelper.class})
+public class BackupSettingsPreferenceControllerTest {
+    private static final String BACKUP_SETTINGS = "backup_settings";
+    private static final String MANUFACTURER_SETTINGS = "manufacturer_backup";
+
+    private Context mContext;
+
+    @Mock
+    private BackupSettingsHelper mBackupHelper;
+    @Mock
+    private PreferenceScreen mScreen;
+    @Mock
+    private Preference mBackupPreference;
+    @Mock
+    private Preference mManufacturerPreference;
+
+    @Mock
+    private static Intent mBackupIntent;
+
+    private static String mBackupLabel = "Test Backup Label";
+    private static String mBackupSummary = "Test Backup Summary";
+    private static String mManufacturerLabel = "Test Manufacturer Label";
+
+    @Mock
+    private static Intent mManufacturerIntent;
+
+    private BackupSettingsPreferenceController mController;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+        mController = new BackupSettingsPreferenceController(mContext);
+    }
+
+    @Test
+    public void testDisplayPreference() {
+        when(mScreen.findPreference(BACKUP_SETTINGS)).thenReturn(mBackupPreference);
+        when(mScreen.findPreference(MANUFACTURER_SETTINGS)).thenReturn(mManufacturerPreference);
+
+        mController.displayPreference(mScreen);
+
+        verify(mBackupPreference).setIntent(mBackupIntent);
+        verify(mBackupPreference).setTitle(mBackupLabel);
+        verify(mBackupPreference).setSummary(mBackupSummary);
+        verify(mManufacturerPreference).setIntent(mManufacturerIntent);
+        verify(mManufacturerPreference).setTitle(mManufacturerLabel);
+    }
+
+    @Test
+    public void testIsAvailable_shouldAlwaysReturnTrue() {
+        assertThat(mController.isAvailable()).isTrue();
+    }
+
+    @Test
+    public void getPreferenceKey_shouldReturnNull() {
+        assertThat(mController.getPreferenceKey()).isNull();
+    }
+
+    @Implements(BackupSettingsHelper.class)
+    public static class ShadowBackupSettingsHelper {
+
+        @Implementation
+        public Intent getIntentForBackupSettings() {
+            return mBackupIntent;
+        }
+
+        @Implementation
+        public String getLabelForBackupSettings() {
+            return mBackupLabel;
+        }
+
+        @Implementation
+        public String getSummaryForBackupSettings() {
+            return mBackupSummary;
+        }
+
+        @Implementation
+        public Intent getIntentProvidedByManufacturer() {
+            return mManufacturerIntent;
+        }
+
+        @Implementation
+        public String getLabelProvidedByManufacturer() {
+            return mManufacturerLabel;
+        }
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/suggestions/EventStoreTest.java b/tests/robotests/src/com/android/settings/suggestions/EventStoreTest.java
new file mode 100644
index 0000000..9db11b8
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/suggestions/EventStoreTest.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.suggestions;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.annotation.Config;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class EventStoreTest {
+
+    private EventStore mEventStore;
+
+    @Before
+    public void setUp() {
+        mEventStore = new EventStore(RuntimeEnvironment.application);
+    }
+
+    @Test
+    public void testWriteRead() {
+        mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
+        long timeMs = System.currentTimeMillis();
+        assertThat(mEventStore.readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT))
+            .isEqualTo(1);
+        assertThat(Math.abs(timeMs - mEventStore
+            .readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME)) < 10000)
+            .isTrue();
+    }
+
+    @Test
+    public void testWriteRead_shouldHaveLatestValues() {
+        mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
+        mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
+        assertThat(
+            mEventStore.readMetric("pkg", EventStore.EVENT_DISMISSED, EventStore.METRIC_COUNT))
+            .isEqualTo(2);
+    }
+
+    @Test
+    public void testWriteRead_shouldReturnDefaultIfNotAvailable() {
+        assertThat(mEventStore.readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT))
+            .isEqualTo(0);
+        assertThat(
+            mEventStore
+                .readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME))
+            .isEqualTo(0);
+    }
+
+}
diff --git a/tests/robotests/src/com/android/settings/suggestions/SuggestionFeaturizerTest.java b/tests/robotests/src/com/android/settings/suggestions/SuggestionFeaturizerTest.java
new file mode 100644
index 0000000..3c5bd4f
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/suggestions/SuggestionFeaturizerTest.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.suggestions;
+
+import java.util.Arrays;
+import java.util.Map;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.annotation.Config;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SuggestionFeaturizerTest {
+
+    private EventStore mEventStore;
+    private SuggestionFeaturizer mSuggestionFeaturizer;
+
+    @Before
+    public void setUp() {
+        mEventStore = new EventStore(RuntimeEnvironment.application);
+        mSuggestionFeaturizer = new SuggestionFeaturizer(mEventStore);
+    }
+
+    @Test
+    public void testFeaturize_singlePackage() {
+        mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
+        mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
+        mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
+        Map<String, Double> features = mSuggestionFeaturizer.featurize(Arrays.asList("pkg"))
+                .get("pkg");
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(1.0);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
+
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN)).isLessThan(1.0);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
+                .isLessThan(1.0);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
+                .isEqualTo(1.0);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
+                .isEqualTo(2.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT))
+                .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
+        assertThat(features.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
+    }
+
+    @Test
+    public void testFeaturize_multiplePackages() {
+        mEventStore.writeEvent("pkg1", EventStore.EVENT_DISMISSED);
+        mEventStore.writeEvent("pkg2", EventStore.EVENT_SHOWN);
+        mEventStore.writeEvent("pkg1", EventStore.EVENT_SHOWN);
+        Map<String, Map<String, Double>> features = mSuggestionFeaturizer
+                .featurize(Arrays.asList("pkg1", "pkg2"));
+        Map<String, Double> features1 = features.get("pkg1");
+        Map<String, Double> features2 = features.get("pkg2");
+
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(1.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN))
+                .isLessThan(1.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
+                .isLessThan(1.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
+                .isEqualTo(1.0);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
+                .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT))
+                .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
+        assertThat(features1.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
+
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(0.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN))
+                .isLessThan(1.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
+                .isEqualTo(1.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
+                .isEqualTo(1.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
+                .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT)).isEqualTo(0.0);
+        assertThat(features2.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
+    }
+}
diff --git a/tests/robotests/src/com/android/settings/suggestions/SuggestionRankerTest.java b/tests/robotests/src/com/android/settings/suggestions/SuggestionRankerTest.java
new file mode 100644
index 0000000..e1807a8
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/suggestions/SuggestionRankerTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.settings.suggestions;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settingslib.drawer.Tile;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import org.robolectric.RuntimeEnvironment;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.same;
+import static org.mockito.Mockito.spy;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SuggestionRankerTest {
+
+    @Mock
+    private SuggestionRanker mSuggestionRanker;
+    @Mock
+    private SuggestionFeaturizer mSuggestionFeaturizer;
+    private Map<String, Map<String, Double>> mFeatures;
+    private List<String> mPkgNames;
+    private List<Tile> mSuggestions;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mPkgNames = Arrays.asList("pkg1", "pkg2", "pkg3");
+        mFeatures = new HashMap<String, Map<String, Double>>();
+        mFeatures.put("pkg1", new HashMap<String, Double>());
+        mFeatures.put("pkg2", new HashMap<String, Double>());
+        mFeatures.put("pkg3", new HashMap<String, Double>());
+        mSuggestions = new ArrayList<Tile>() {
+            {
+                add(new Tile());
+                add(new Tile());
+                add(new Tile());
+            }
+        };
+        mSuggestionFeaturizer = mock(SuggestionFeaturizer.class);
+        mSuggestionRanker = new SuggestionRanker(mSuggestionFeaturizer);
+        when(mSuggestionFeaturizer.featurize(mPkgNames)).thenReturn(mFeatures);
+        mSuggestionRanker = spy(mSuggestionRanker);
+        when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg1")))).thenReturn(0.9);
+        when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg2")))).thenReturn(0.1);
+        when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg3")))).thenReturn(0.5);
+    }
+
+    @Test
+    public void testRank() {
+        List<Tile> expectedOrderdList = new ArrayList<Tile>() {
+            {
+                add(mSuggestions.get(0)); // relevance = 0.9
+                add(mSuggestions.get(2)); // relevance = 0.5
+                add(mSuggestions.get(1)); // relevance = 0.1
+            }
+        };
+        mSuggestionRanker.rank(mSuggestions, mPkgNames);
+        assertThat(mSuggestions).isEqualTo(expectedOrderdList);
+    }
+}
+