Settings - add support for Launch by Default

- implement UX spec

Change-Id: I7ee8962f83983273d809e0ef6fc81b0eb2df15dd
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 20ce116..864cc95 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -98,6 +98,7 @@
     public static class NotificationAppListActivity extends SettingsActivity { /* empty */ }
     public static class AppNotificationSettingsActivity extends SettingsActivity { /* empty */ }
     public static class OtherSoundSettingsActivity extends SettingsActivity { /* empty */ }
+    public static class DomainsURLsAppListActivity extends SettingsActivity { /* empty */ }
 
     public static class TopLevelSettings extends SettingsActivity { /* empty */ }
     public static class ApnSettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index bc6cbed..23b2c85 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -25,10 +25,12 @@
 import android.app.Dialog;
 import android.app.Fragment;
 import android.app.IActivityManager;
+import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
@@ -43,6 +45,7 @@
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.graphics.drawable.Drawable;
+import android.hardware.usb.IUsbManager;
 import android.net.ConnectivityManager;
 import android.net.LinkProperties;
 import android.net.Uri;
@@ -76,6 +79,7 @@
 
 import com.android.internal.util.UserIcons;
 import com.android.settings.UserAdapter.UserDetails;
+import com.android.settings.applications.ApplicationsState;
 import com.android.settings.dashboard.DashboardTile;
 import com.android.settings.drawable.CircleFramedDrawable;
 
@@ -84,6 +88,7 @@
 import java.net.InetAddress;
 import java.text.NumberFormat;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
@@ -1101,7 +1106,6 @@
         return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
     }
 
-
     /**
      * Returns a default user icon (as a {@link Bitmap}) for the given user.
      *
@@ -1119,4 +1123,39 @@
         }
         return bitmap;
     }
+
+    public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
+        try {
+            if (usbManager != null) {
+                return usbManager.hasDefaults(packageName, UserHandle.myUserId());
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG, "mUsbManager.hasDefaults", e);
+        }
+        return false;
+    }
+
+    public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
+        // Get list of preferred activities
+        List<ComponentName> prefActList = new ArrayList<>();
+        // Intent list cannot be null. so pass empty list
+        List<IntentFilter> intentList = new ArrayList<>();
+        pm.getPreferredActivities(intentList, prefActList, packageName);
+        Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
+        return prefActList.size() > 0;
+    }
+
+    public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
+            IUsbManager usbManager, PackageManager pm, Context context) {
+        String packageName = appEntry.info.packageName;
+        boolean hasPreferred = hasPreferredActivities(pm, packageName)
+                || hasUsbDefaults(usbManager, packageName);
+        int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
+        boolean hasDomainURLsPreference =
+                (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
+                (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
+        return context.getString(hasPreferred || hasDomainURLsPreference
+                ? R.string.launch_defaults_some
+                : R.string.launch_defaults_none);
+    }
 }
diff --git a/src/com/android/settings/applications/AdvancedAppSettings.java b/src/com/android/settings/applications/AdvancedAppSettings.java
index d5ab8dc..3d3c9f6 100644
--- a/src/com/android/settings/applications/AdvancedAppSettings.java
+++ b/src/com/android/settings/applications/AdvancedAppSettings.java
@@ -18,6 +18,7 @@
 import static android.net.NetworkPolicyManager.POLICY_NONE;
 import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
 
+import android.app.Activity;
 import android.app.ActivityManager;
 import android.app.AlertDialog;
 import android.app.AppOpsManager;
@@ -26,7 +27,6 @@
 import android.content.DialogInterface;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageManager;
-import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager;
 import android.net.NetworkPolicyManager;
 import android.os.AsyncTask;
@@ -35,11 +35,9 @@
 import android.os.RemoteException;
 import android.os.ServiceManager;
 import android.os.UserHandle;
-import android.os.UserManager;
 import android.preference.Preference;
 import android.preference.Preference.OnPreferenceClickListener;
 import android.util.Log;
-import android.util.Pair;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
@@ -63,14 +61,16 @@
 
     private static final String KEY_APP_PERM = "manage_perms";
     private static final String KEY_ALL_APPS = "all_apps";
+    private static final String KEY_APP_DOMAIN_URLS = "domain_urls";
     private static final String KEY_RESET_ALL = "reset_all";
     private static final String EXTRA_RESET_DIALOG = "resetDialog";
 
     private ApplicationsState mApplicationsState;
     private Session mSession;
-    private Preference mAppPerms;
-    private Preference mAllApps;
-    private Preference mResetAll;
+    private Preference mAppPermsPreference;
+    private Preference mAppDomainURLsPreference;
+    private Preference mAllAppsPreference;
+    private Preference mResetAllPreference;
 
     AlertDialog mResetDialog;
 
@@ -91,17 +91,18 @@
         mApplicationsState = ApplicationsState.getInstance(getActivity().getApplication());
         mSession = mApplicationsState.newSession(this);
 
-        mAppPerms = findPreference(KEY_APP_PERM);
-        mAllApps = findPreference(KEY_ALL_APPS);
-        mResetAll = findPreference(KEY_RESET_ALL);
-        mResetAll.setOnPreferenceClickListener(new OnPreferenceClickListener() {
+        mAppPermsPreference = findPreference(KEY_APP_PERM);
+        mAppDomainURLsPreference = findPreference(KEY_APP_DOMAIN_URLS);
+        mAllAppsPreference = findPreference(KEY_ALL_APPS);
+        mResetAllPreference = findPreference(KEY_RESET_ALL);
+        mResetAllPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
             @Override
             public boolean onPreferenceClick(Preference preference) {
                 buildResetDialog();
                 return true;
             }
         });
-        updateAllAppsSummary();
+        updateUI();
 
         mPm = getActivity().getPackageManager();
         mIPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));
@@ -112,8 +113,19 @@
         mHandler = new Handler(getActivity().getMainLooper());
     }
 
-    private void updateAllAppsSummary() {
-        mAllApps.setSummary(getString(R.string.all_apps_summary, mSession.getAllApps().size()));
+    private void updateUI() {
+        ArrayList<AppEntry> allApps = mSession.getAllApps();
+        mAllAppsPreference.setSummary(getString(R.string.all_apps_summary, allApps.size()));
+
+        int countAppWithDomainURLs = 0;
+        for (AppEntry entry : allApps) {
+            boolean hasDomainURLs =
+                    (entry.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
+            if (hasDomainURLs) countAppWithDomainURLs++;
+        }
+        String summary = getResources().getQuantityString(
+                R.plurals.domain_urls_apps_summary, countAppWithDomainURLs, countAppWithDomainURLs);
+        mAppDomainURLsPreference.setSummary(summary);
     }
 
     @Override
@@ -241,7 +253,7 @@
 
     @Override
     public void onPackageListChanged() {
-        updateAllAppsSummary();
+        updateUI();
     }
 
     @Override
@@ -276,7 +288,9 @@
 
     @Override
     public void onPermissionLoadComplete() {
-        mAppPerms.setSummary(getActivity().getString(R.string.app_permissions_summary,
+        Activity activity = getActivity();
+        if (activity == null) return;
+        mAppPermsPreference.setSummary(activity.getString(R.string.app_permissions_summary,
                 mPermissionsInfo.getRuntimePermAppsGrantedCount(),
                 mPermissionsInfo.getRuntimePermAppsCount()));
     }
diff --git a/src/com/android/settings/applications/AppDomainsPreference.java b/src/com/android/settings/applications/AppDomainsPreference.java
new file mode 100644
index 0000000..7e29a20
--- /dev/null
+++ b/src/com/android/settings/applications/AppDomainsPreference.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.applications;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.TextView;
+import com.android.settings.accessibility.ListDialogPreference;
+
+import com.android.settings.R;
+
+public class AppDomainsPreference extends ListDialogPreference {
+
+    public AppDomainsPreference(Context context, AttributeSet attrs) {
+        super(context, attrs);
+
+        setDialogLayoutResource(R.layout.app_domains_dialog);
+        setListItemLayoutResource(R.layout.app_domains_item);
+    }
+
+    @Override
+    protected void onBindListItem(View view, int index) {
+        final CharSequence title = getTitleAt(index);
+        if (title != null) {
+            final TextView domainName = (TextView) view.findViewById(R.id.domain_name);
+            domainName.setText(title);
+        }
+    }
+}
diff --git a/src/com/android/settings/applications/AppLaunchSettings.java b/src/com/android/settings/applications/AppLaunchSettings.java
index ffb84ef..c0a662a 100644
--- a/src/com/android/settings/applications/AppLaunchSettings.java
+++ b/src/com/android/settings/applications/AppLaunchSettings.java
@@ -17,175 +17,104 @@
 package com.android.settings.applications;
 
 import android.app.AlertDialog;
-import android.appwidget.AppWidgetManager;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.IntentFilter;
+import android.content.pm.IntentFilterVerificationInfo;
 import android.content.pm.PackageManager;
-import android.hardware.usb.IUsbManager;
 import android.os.Bundle;
-import android.os.RemoteException;
 import android.os.UserHandle;
-import android.text.SpannableString;
-import android.text.TextUtils;
-import android.text.style.BulletSpan;
-import android.util.Log;
-import android.view.LayoutInflater;
+import android.preference.Preference;
+import android.preference.SwitchPreference;
+import android.util.ArraySet;
 import android.view.View;
 import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
 
 import com.android.internal.logging.MetricsLogger;
 import com.android.settings.R;
-import com.android.settings.Utils;
-import com.android.settings.applications.ApplicationsState.AppEntry;
 
-import java.util.ArrayList;
 import java.util.List;
 
-public class AppLaunchSettings extends AppInfoWithHeader implements OnClickListener {
+public class AppLaunchSettings extends AppInfoWithHeader implements OnClickListener,
+        Preference.OnPreferenceChangeListener {
 
-    private Button mActivitiesButton;
-    private AppWidgetManager mAppWidgetManager;
+    private static final String KEY_OPEN_DOMAIN_URLS = "app_launch_open_domain_urls";
+    private static final String KEY_SUPPORTED_DOMAIN_URLS = "app_launch_supported_domain_urls";
+    private static final String KEY_CLEAR_DEFAULTS = "app_launch_clear_defaults";
 
-    private View mRootView;
+    private PackageManager mPm;
+
+    private SwitchPreference mOpenDomainUrls;
+    private AppDomainsPreference mAppDomainUrls;
+    private ClearDefaultsPreference mClearDefaultsPreference;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        mAppWidgetManager = AppWidgetManager.getInstance(getActivity());
+
+        addPreferencesFromResource(R.xml.installed_app_launch_settings);
+
+        mPm = getActivity().getPackageManager();
+        final int myUserId = UserHandle.myUserId();
+
+        mOpenDomainUrls = (SwitchPreference) findPreference(KEY_OPEN_DOMAIN_URLS);
+        mOpenDomainUrls.setOnPreferenceChangeListener(this);
+
+        final int status = mPm.getIntentVerificationStatus(mPackageName, myUserId);
+        boolean checked = status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
+        mOpenDomainUrls.setChecked(checked);
+
+        mAppDomainUrls = (AppDomainsPreference) findPreference(KEY_SUPPORTED_DOMAIN_URLS);
+        CharSequence[] entries = getEntries(mPackageName);
+        mAppDomainUrls.setTitles(entries);
+        mAppDomainUrls.setValues(new int[entries.length]);
+
+        mClearDefaultsPreference = (ClearDefaultsPreference) findPreference(KEY_CLEAR_DEFAULTS);
     }
 
-    @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container,
-            Bundle savedInstanceState) {
-        final View view = inflater.inflate(R.layout.app_preferred_settings, container, false);
+    private CharSequence[] getEntries(String packageName) {
+        ArraySet<String> result = new ArraySet<>();
 
-        final ViewGroup allDetails = (ViewGroup) view.findViewById(R.id.all_details);
-        Utils.forceCustomPadding(allDetails, true /* additive padding */);
+        List<IntentFilterVerificationInfo> list =
+                mPm.getIntentFilterVerifications(packageName);
+        for (IntentFilterVerificationInfo ivi : list) {
+            for (String host : ivi.getDomains()) {
+                result.add(host);
+            }
+        }
 
-        mActivitiesButton = (Button) view.findViewById(R.id.clear_activities_button);
-        mRootView = view;
-
-        return view;
+        return result.toArray(new CharSequence[0]);
     }
 
     @Override
     protected boolean refreshUi() {
-        retrieveAppEntry();
-        boolean hasBindAppWidgetPermission =
-                mAppWidgetManager.hasBindAppWidgetPermission(mAppEntry.info.packageName);
+        mClearDefaultsPreference.setPackageName(mPackageName);
+        mClearDefaultsPreference.setAppEntry(mAppEntry);
 
-        TextView autoLaunchTitleView = (TextView) mRootView.findViewById(R.id.auto_launch_title);
-        TextView autoLaunchView = (TextView) mRootView.findViewById(R.id.auto_launch);
-        boolean autoLaunchEnabled = hasPreferredActivities(mPm, mPackageName)
-                || hasUsbDefaults(mUsbManager, mPackageName);
-        if (!autoLaunchEnabled && !hasBindAppWidgetPermission) {
-            resetLaunchDefaultsUi(autoLaunchTitleView, autoLaunchView);
-        } else {
-            boolean useBullets = hasBindAppWidgetPermission && autoLaunchEnabled;
-
-            if (hasBindAppWidgetPermission) {
-                autoLaunchTitleView.setText(R.string.auto_launch_label_generic);
-            } else {
-                autoLaunchTitleView.setText(R.string.auto_launch_label);
-            }
-
-            CharSequence text = null;
-            int bulletIndent = getResources()
-                    .getDimensionPixelSize(R.dimen.installed_app_details_bullet_offset);
-            if (autoLaunchEnabled) {
-                CharSequence autoLaunchEnableText = getText(R.string.auto_launch_enable_text);
-                SpannableString s = new SpannableString(autoLaunchEnableText);
-                if (useBullets) {
-                    s.setSpan(new BulletSpan(bulletIndent), 0, autoLaunchEnableText.length(), 0);
-                }
-                text = (text == null) ?
-                        TextUtils.concat(s, "\n") : TextUtils.concat(text, "\n", s, "\n");
-            }
-            if (hasBindAppWidgetPermission) {
-                CharSequence alwaysAllowBindAppWidgetsText =
-                        getText(R.string.always_allow_bind_appwidgets_text);
-                SpannableString s = new SpannableString(alwaysAllowBindAppWidgetsText);
-                if (useBullets) {
-                    s.setSpan(new BulletSpan(bulletIndent),
-                            0, alwaysAllowBindAppWidgetsText.length(), 0);
-                }
-                text = (text == null) ?
-                        TextUtils.concat(s, "\n") : TextUtils.concat(text, "\n", s, "\n");
-            }
-            autoLaunchView.setText(text);
-            mActivitiesButton.setEnabled(true);
-            mActivitiesButton.setOnClickListener(this);
-        }
         return true;
     }
 
-    private void resetLaunchDefaultsUi(TextView title, TextView autoLaunchView) {
-        title.setText(R.string.auto_launch_label);
-        autoLaunchView.setText(R.string.auto_launch_disable_text);
-        // Disable clear activities button
-        mActivitiesButton.setEnabled(false);
-    }
-
     @Override
     protected AlertDialog createDialog(int id, int errorCode) {
         // No dialogs for preferred launch settings.
         return null;
     }
 
+
     @Override
     public void onClick(View v) {
-        if (v == mActivitiesButton) {
-            if (mUsbManager != null) {
-                mPm.clearPackagePreferredActivities(mPackageName);
-                try {
-                    mUsbManager.clearDefaults(mPackageName, UserHandle.myUserId());
-                } catch (RemoteException e) {
-                    Log.e(TAG, "mUsbManager.clearDefaults", e);
-                }
-                mAppWidgetManager.setBindAppWidgetPermission(mPackageName, false);
-                TextView autoLaunchTitleView =
-                        (TextView) mRootView.findViewById(R.id.auto_launch_title);
-                TextView autoLaunchView = (TextView) mRootView.findViewById(R.id.auto_launch);
-                resetLaunchDefaultsUi(autoLaunchTitleView, autoLaunchView);
-            }
-        }
+        // Nothing to do
     }
 
-    private static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
-        try {
-            if (usbManager != null) {
-                return usbManager.hasDefaults(packageName, UserHandle.myUserId());
-            }
-        } catch (RemoteException e) {
-            Log.e(TAG, "mUsbManager.hasDefaults", e);
+    @Override
+    public boolean onPreferenceChange(Preference preference, Object newValue) {
+        boolean ret = false;
+        final String key = preference.getKey();
+        if (KEY_OPEN_DOMAIN_URLS.equals(key)) {
+            SwitchPreference pref = (SwitchPreference) preference;
+            int status = !pref.isChecked() ?
+                    PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS :
+                    PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
+            ret = mPm.updateIntentVerificationStatus(mPackageName, status, UserHandle.myUserId());
         }
-        return false;
-    }
-
-    private static boolean hasPreferredActivities(PackageManager pm, String packageName) {
-        // Get list of preferred activities
-        List<ComponentName> prefActList = new ArrayList<>();
-        // Intent list cannot be null. so pass empty list
-        List<IntentFilter> intentList = new ArrayList<>();
-        pm.getPreferredActivities(intentList, prefActList, packageName);
-        if (localLOGV) {
-            Log.i(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
-        }
-        return prefActList.size() > 0;
-    }
-
-    public static CharSequence getSummary(AppEntry appEntry, IUsbManager usbManager,
-            PackageManager pm, Context context) {
-        String packageName = appEntry.info.packageName;
-        boolean hasPreferred = hasPreferredActivities(pm, packageName)
-                || hasUsbDefaults(usbManager, packageName);
-        return context.getString(hasPreferred
-                ? R.string.launch_defaults_some
-                : R.string.launch_defaults_none);
+        return ret;
     }
 
     @Override
diff --git a/src/com/android/settings/applications/AppViewHolder.java b/src/com/android/settings/applications/AppViewHolder.java
index 176ccca..92aa87a 100644
--- a/src/com/android/settings/applications/AppViewHolder.java
+++ b/src/com/android/settings/applications/AppViewHolder.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package com.android.settings.applications;
 
 import com.android.settings.R;
diff --git a/src/com/android/settings/applications/ApplicationsState.java b/src/com/android/settings/applications/ApplicationsState.java
index daa3842..71d0790 100644
--- a/src/com/android/settings/applications/ApplicationsState.java
+++ b/src/com/android/settings/applications/ApplicationsState.java
@@ -1,3 +1,19 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
 package com.android.settings.applications;
 
 import android.app.ActivityManager;
@@ -116,7 +132,7 @@
         }
 
         // Need to synchronize on 'this' for the following.
-        ApplicationInfo info;
+        public ApplicationInfo info;
         Drawable icon;
         String sizeStr;
         String internalSizeStr;
@@ -323,6 +339,16 @@
         }
     };
 
+    public static final AppFilter FILTER_WITH_DOMAIN_URLS = new AppFilter() {
+        public void init() {
+        }
+
+        @Override
+        public boolean filterApp(AppEntry entry) {
+            return (entry.info.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
+        }
+    };
+
     final Context mContext;
     final PackageManager mPm;
     final IPackageManager mIpm;
diff --git a/src/com/android/settings/applications/ClearDefaultsPreference.java b/src/com/android/settings/applications/ClearDefaultsPreference.java
new file mode 100644
index 0000000..1799cad
--- /dev/null
+++ b/src/com/android/settings/applications/ClearDefaultsPreference.java
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.applications;
+
+import android.appwidget.AppWidgetManager;
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.usb.IUsbManager;
+import android.os.IBinder;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.UserHandle;
+import android.preference.Preference;
+import android.text.SpannableString;
+import android.text.TextUtils;
+import android.text.style.BulletSpan;
+import android.util.AttributeSet;
+import android.util.Log;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.TextView;
+
+import com.android.settings.R;
+import com.android.settings.Utils;
+
+public class ClearDefaultsPreference extends Preference {
+
+    protected static final String TAG = ClearDefaultsPreference.class.getSimpleName();
+
+    private View mRootView;
+    private Button mActivitiesButton;
+
+    private AppWidgetManager mAppWidgetManager;
+    private IUsbManager mUsbManager;
+    private PackageManager mPm;
+    private String mPackageName;
+    protected ApplicationsState.AppEntry mAppEntry;
+
+    public ClearDefaultsPreference(Context context, AttributeSet attrs, int defStyleAttr,
+            int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+
+        setLayoutResource(R.layout.app_preferred_settings);
+
+        mAppWidgetManager = AppWidgetManager.getInstance(context);
+        mPm = context.getPackageManager();
+        IBinder b = ServiceManager.getService(Context.USB_SERVICE);
+        mUsbManager = IUsbManager.Stub.asInterface(b);
+    }
+
+    public ClearDefaultsPreference(Context context, AttributeSet attrs, int defStyleAttr) {
+        this(context, attrs, defStyleAttr, 0);
+    }
+
+    public ClearDefaultsPreference(Context context, AttributeSet attrs) {
+        this(context, attrs, 0);
+    }
+
+    public ClearDefaultsPreference(Context context) {
+        this(context, null);
+    }
+
+    public void setPackageName(String packageName) {
+        mPackageName = packageName;
+    }
+
+    public void setAppEntry(ApplicationsState.AppEntry entry) {
+        mAppEntry = entry;
+    }
+
+    @Override
+    protected View onCreateView(ViewGroup parent) {
+        mRootView = super.onCreateView(parent);
+
+        mActivitiesButton = (Button) mRootView.findViewById(R.id.clear_activities_button);
+        mActivitiesButton.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                if (mUsbManager != null) {
+                    mPm.clearPackagePreferredActivities(mPackageName);
+                    try {
+                        mUsbManager.clearDefaults(mPackageName, UserHandle.myUserId());
+                    } catch (RemoteException e) {
+                        Log.e(TAG, "mUsbManager.clearDefaults", e);
+                    }
+                    mAppWidgetManager.setBindAppWidgetPermission(mPackageName, false);
+                    TextView autoLaunchView = (TextView) mRootView.findViewById(R.id.auto_launch);
+                    resetLaunchDefaultsUi(autoLaunchView);
+                }
+            }
+        });
+
+        return mRootView;
+    }
+
+    @Override
+    protected void onBindView(View view) {
+        super.onBindView(view);
+
+        updateUI();
+    }
+
+    public boolean updateUI() {
+        boolean hasBindAppWidgetPermission =
+                mAppWidgetManager.hasBindAppWidgetPermission(mAppEntry.info.packageName);
+
+        TextView autoLaunchView = (TextView) mRootView.findViewById(R.id.auto_launch);
+        boolean autoLaunchEnabled = Utils.hasPreferredActivities(mPm, mPackageName)
+                || Utils.hasUsbDefaults(mUsbManager, mPackageName);
+        if (!autoLaunchEnabled && !hasBindAppWidgetPermission) {
+            resetLaunchDefaultsUi(autoLaunchView);
+        } else {
+            boolean useBullets = hasBindAppWidgetPermission && autoLaunchEnabled;
+
+            if (hasBindAppWidgetPermission) {
+                autoLaunchView.setText(R.string.auto_launch_label_generic);
+            } else {
+                autoLaunchView.setText(R.string.auto_launch_label);
+            }
+
+            Context context = getContext();
+            CharSequence text = null;
+            int bulletIndent = context.getResources().getDimensionPixelSize(
+                    R.dimen.installed_app_details_bullet_offset);
+            if (autoLaunchEnabled) {
+                CharSequence autoLaunchEnableText = context.getText(
+                        R.string.auto_launch_enable_text);
+                SpannableString s = new SpannableString(autoLaunchEnableText);
+                if (useBullets) {
+                    s.setSpan(new BulletSpan(bulletIndent), 0, autoLaunchEnableText.length(), 0);
+                }
+                text = (text == null) ?
+                        TextUtils.concat(s, "\n") : TextUtils.concat(text, "\n", s, "\n");
+            }
+            if (hasBindAppWidgetPermission) {
+                CharSequence alwaysAllowBindAppWidgetsText =
+                        context.getText(R.string.always_allow_bind_appwidgets_text);
+                SpannableString s = new SpannableString(alwaysAllowBindAppWidgetsText);
+                if (useBullets) {
+                    s.setSpan(new BulletSpan(bulletIndent),
+                            0, alwaysAllowBindAppWidgetsText.length(), 0);
+                }
+                text = (text == null) ?
+                        TextUtils.concat(s, "\n") : TextUtils.concat(text, "\n", s, "\n");
+            }
+            autoLaunchView.setText(text);
+            mActivitiesButton.setEnabled(true);
+        }
+        return true;
+    }
+
+    private void resetLaunchDefaultsUi(TextView autoLaunchView) {
+        autoLaunchView.setText(R.string.auto_launch_disable_text);
+        // Disable clear activities button
+        mActivitiesButton.setEnabled(false);
+    }
+}
diff --git a/src/com/android/settings/applications/InstalledAppDetails.java b/src/com/android/settings/applications/InstalledAppDetails.java
index 9f6c969..33a7428 100755
--- a/src/com/android/settings/applications/InstalledAppDetails.java
+++ b/src/com/android/settings/applications/InstalledAppDetails.java
@@ -261,10 +261,17 @@
         mStoragePreference.setOnPreferenceClickListener(this);
         mPermissionsPreference = findPreference(KEY_PERMISSION);
         mPermissionsPreference.setOnPreferenceClickListener(this);
-        mLaunchPreference = findPreference(KEY_LAUNCH);
-        mLaunchPreference.setOnPreferenceClickListener(this);
         mDataPreference = findPreference(KEY_DATA);
         mDataPreference.setOnPreferenceClickListener(this);
+
+        mLaunchPreference = findPreference(KEY_LAUNCH);
+        if ((mAppEntry.info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
+            mLaunchPreference.setEnabled(false);
+        } else if (!mAppEntry.info.enabled) {
+            mLaunchPreference.setEnabled(false);
+        } else {
+            mLaunchPreference.setOnPreferenceClickListener(this);
+        }
     }
 
     private void handleHeader() {
@@ -421,7 +428,7 @@
         Activity context = getActivity();
         mStoragePreference.setSummary(AppStorageSettings.getSummary(mAppEntry, context));
         mPermissionsPreference.setSummary(AppPermissionSettings.getSummary(mAppEntry, context));
-        mLaunchPreference.setSummary(AppLaunchSettings.getSummary(mAppEntry, mUsbManager,
+        mLaunchPreference.setSummary(Utils.getLaunchByDeafaultSummary(mAppEntry, mUsbManager,
                 mPm, context));
         mNotificationPreference.setSummary(getNotificationSummary(mAppEntry, context,
                 mBackend));
diff --git a/src/com/android/settings/applications/ManageApplications.java b/src/com/android/settings/applications/ManageApplications.java
index 84b9763..b416aef 100644
--- a/src/com/android/settings/applications/ManageApplications.java
+++ b/src/com/android/settings/applications/ManageApplications.java
@@ -17,12 +17,13 @@
 package com.android.settings.applications;
 
 import android.app.Activity;
-import android.app.Fragment;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.IPackageManager;
+import android.content.pm.IntentFilterVerificationInfo;
 import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.Environment;
@@ -32,6 +33,7 @@
 import android.os.UserManager;
 import android.preference.PreferenceFrameLayout;
 import android.provider.Settings;
+import android.util.ArraySet;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.Menu;
@@ -63,10 +65,12 @@
 import com.android.settings.applications.ApplicationsState.AppFilter;
 import com.android.settings.notification.NotificationBackend;
 import com.android.settings.notification.NotificationBackend.AppRow;
+import com.android.settings.Settings.DomainsURLsAppListActivity;
 
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
+import java.util.List;
 
 final class CanBeOnSdCardChecker {
     final IPackageManager mPm;
@@ -145,6 +149,7 @@
     public static final int FILTER_APPS_SENSITIVE               = 6;
     public static final int FILTER_APPS_PERSONAL                = 7;
     public static final int FILTER_APPS_WORK                    = 8;
+    public static final int FILTER_APPS_WITH_DOMAIN_URLS        = 9;
 
     // This is the string labels for the filter modes above, the order must be kept in sync.
     public static final int[] FILTER_LABELS = new int[] {
@@ -157,6 +162,7 @@
         R.string.filter_notif_sensitive_apps, // Sensitive Notifications
         R.string.filter_personal_apps, // Personal
         R.string.filter_work_apps,     // Work
+        R.string.filter_with_domain_urls_apps,     // Domain URLs
     };
     // This is the actual mapping to filters from FILTER_ constants above, the order must
     // be kept in sync.
@@ -170,6 +176,7 @@
         AppStateNotificationBridge.FILTER_APP_NOTIFICATION_SENSITIVE, // Sensitive Notifications
         ApplicationsState.FILTER_PERSONAL,    // Personal
         ApplicationsState.FILTER_WORK,        // Work
+        ApplicationsState.FILTER_WITH_DOMAIN_URLS,   // Apps with Domain URLs
     };
 
     // sort order that can be changed through the menu can be sorted alphabetically
@@ -209,6 +216,7 @@
     public static final int LIST_TYPE_MAIN = 0;
     public static final int LIST_TYPE_ALL = 1;
     public static final int LIST_TYPE_NOTIFICATION = 2;
+    public static final int LIST_TYPE_DOMAINS_URLS = 3;
 
     private View mRootView;
 
@@ -224,7 +232,6 @@
         mApplicationsState = ApplicationsState.getInstance(getActivity().getApplication());
 
         Intent intent = getActivity().getIntent();
-        String action = intent.getAction();
         String className = getArguments() != null
                 ? getArguments().getString("classname") : null;
         if (className == null) {
@@ -235,6 +242,8 @@
         } else if (className.equals(NotificationAppListActivity.class.getName())) {
             mListType = LIST_TYPE_NOTIFICATION;
             mNotifBackend = new NotificationBackend();
+        } else if (className.equals(DomainsURLsAppListActivity.class.getName())) {
+            mListType = LIST_TYPE_DOMAINS_URLS;
         } else {
             mListType = LIST_TYPE_MAIN;
         }
@@ -311,12 +320,17 @@
             mFilterAdapter.enableFilter(FILTER_APPS_BLOCKED);
             mFilterAdapter.enableFilter(FILTER_APPS_PRIORITY);
             mFilterAdapter.enableFilter(FILTER_APPS_SENSITIVE);
+        } else if (mListType == LIST_TYPE_DOMAINS_URLS) {
+            mFilterAdapter.disableFilter(FILTER_APPS_ALL);
+            mFilterAdapter.enableFilter(FILTER_APPS_WITH_DOMAIN_URLS);
         }
     }
 
     private int getDefaultFilter() {
         if (mListType == LIST_TYPE_MAIN) {
             return FILTER_APPS_DOWNLOADED_AND_LAUNCHER;
+        } else if (mListType == LIST_TYPE_DOMAINS_URLS) {
+            return FILTER_APPS_WITH_DOMAIN_URLS;
         }
         return FILTER_APPS_ALL;
     }
@@ -330,6 +344,8 @@
                 return MetricsLogger.MANAGE_APPLICATIONS_ALL;
             case LIST_TYPE_NOTIFICATION:
                 return MetricsLogger.MANAGE_APPLICATIONS_NOTIFICATIONS;
+            case LIST_TYPE_DOMAINS_URLS:
+                return MetricsLogger.MANAGE_DOMAIN_URLS;
             default:
                 return MetricsLogger.VIEW_UNKNOWN;
         }
@@ -382,24 +398,39 @@
 
     // utility method used to start sub activity
     private void startApplicationDetailsActivity() {
+        Activity activity = getActivity();
         if (mListType == LIST_TYPE_NOTIFICATION) {
-            getActivity().startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
+            activity.startActivity(new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                     .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                     .putExtra(Settings.EXTRA_APP_PACKAGE, mCurrentPkgName)
                     .putExtra(Settings.EXTRA_APP_UID, mCurrentUid));
+        } else if (mListType == LIST_TYPE_DOMAINS_URLS) {
+            final String title = getString(R.string.auto_launch_label);
+            startAppInfoFragment(AppLaunchSettings.class, title);
         } else {
             // TODO: Figure out if there is a way where we can spin up the profile's settings
             // process ahead of time, to avoid a long load of data when user clicks on a managed app.
             // Maybe when they load the list of apps that contains managed profile apps.
             Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
             intent.setData(Uri.fromParts("package", mCurrentPkgName, null));
-            getActivity().startActivityAsUser(intent,
-                    new UserHandle(UserHandle.getUserId(mCurrentUid)));
+            activity.startActivityAsUser(intent, new UserHandle(UserHandle.getUserId(mCurrentUid)));
         }
     }
 
+    private void startAppInfoFragment(Class<? extends AppInfoBase> fragment, CharSequence title) {
+        Bundle args = new Bundle();
+        args.putString("package", mCurrentPkgName);
+
+        SettingsActivity sa = (SettingsActivity) getActivity();
+        sa.startPreferencePanel(fragment.getName(), args, -1, title, this, 0);
+    }
+
     @Override
     public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+        if (mListType == LIST_TYPE_DOMAINS_URLS) {
+            // No option menu
+            return;
+        }
         mOptionsMenu = menu;
         if (mListType == LIST_TYPE_MAIN) {
             // Only show advanced options when in the main app list (from dashboard).
@@ -426,7 +457,6 @@
         if (mOptionsMenu == null) {
             return;
         }
-
         if (mListType != LIST_TYPE_MAIN) {
             // Allow sorting except on main apps list.
             mOptionsMenu.findItem(SORT_ORDER_ALPHA).setVisible(mSortOrder != SORT_ORDER_ALPHA);
@@ -580,6 +610,7 @@
         private int mLastSortMode=-1;
         private int mWhichSize = SIZE_TOTAL;
         CharSequence mCurFilterPrefix;
+        private PackageManager mPm;
 
         private Filter mFilter = new Filter() {
             @Override
@@ -607,6 +638,7 @@
             mSession = state.newSession(this);
             mManageApplications = manageApplications;
             mContext = manageApplications.getActivity();
+            mPm = mContext.getPackageManager();
             mFilterMode = filterMode;
             if (mManageApplications.mListType == LIST_TYPE_NOTIFICATION) {
                 mNotifBridge = new AppStateNotificationBridge(
@@ -842,6 +874,24 @@
             return mEntries.get(position).id;
         }
 
+        @Override
+        public boolean areAllItemsEnabled() {
+            return false;
+        }
+
+        @Override
+        public boolean isEnabled(int position) {
+            ApplicationsState.AppEntry entry = mEntries.get(position);
+            synchronized (entry) {
+                if ((entry.info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
+                    return false;
+                } else if (!entry.info.enabled) {
+                    return false;
+                }
+                return true;
+            }
+        }
+
         public View getView(int position, View convertView, ViewGroup parent) {
             // A ViewHolder keeps references to children views to avoid unnecessary calls
             // to findViewById() on each row.
@@ -860,15 +910,23 @@
                 if (entry.icon != null) {
                     holder.appIcon.setImageDrawable(entry.icon);
                 }
-                if (mManageApplications.mListType == LIST_TYPE_NOTIFICATION) {
-                    if (entry.extraInfo != null) {
-                        holder.summary.setText(InstalledAppDetails.getNotificationSummary(
-                                (AppRow) entry.extraInfo, mContext));
-                    } else {
-                        holder.summary.setText("");
-                    }
-                } else {
-                    holder.updateSizeText(mManageApplications.mInvalidSizeStr, mWhichSize);
+                switch (mManageApplications.mListType) {
+                    case LIST_TYPE_NOTIFICATION:
+                        if (entry.extraInfo != null) {
+                            holder.summary.setText(InstalledAppDetails.getNotificationSummary(
+                                    (AppRow) entry.extraInfo, mContext));
+                        } else {
+                            holder.summary.setText("");
+                        }
+                        break;
+
+                    case LIST_TYPE_DOMAINS_URLS:
+                        holder.summary.setText(getDomainsSummary(entry.info.packageName));
+                        break;
+
+                    default:
+                        holder.updateSizeText(mManageApplications.mInvalidSizeStr, mWhichSize);
+                        break;
                 }
                 if ((entry.info.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {
                     holder.disabled.setVisibility(View.VISIBLE);
@@ -895,5 +953,23 @@
         public void onMovedToScrapHeap(View view) {
             mActive.remove(view);
         }
+
+        private CharSequence getDomainsSummary(String packageName) {
+            ArraySet<String> result = new ArraySet<>();
+            List<IntentFilterVerificationInfo> list =
+                    mPm.getIntentFilterVerifications(packageName);
+            for (IntentFilterVerificationInfo ivi : list) {
+                for (String host : ivi.getDomains()) {
+                    result.add(host);
+                }
+            }
+            if (result.size() == 0) {
+                return mContext.getString(R.string.domain_urls_summary_none);
+            } else if (result.size() == 1) {
+                return mContext.getString(R.string.domain_urls_summary_one, result.valueAt(0));
+            } else {
+                return mContext.getString(R.string.domain_urls_summary_some, result.valueAt(0));
+            }
+        }
     }
 }