Add default emergency app setting

Bug: 19841649
Change-Id: I1763ee16e1e10c957261fe663f4c87269adcdef7
diff --git a/res/values/strings.xml b/res/values/strings.xml
index b1e862d..23514d4 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -2890,6 +2890,8 @@
     <string name="show_running_services">Show running services</string>
     <!-- [CHAR LIMIT=25] Manage applications screen, menu item.  Show background cached processes. -->
     <string name="show_background_processes">Show cached processes</string>
+    <!-- [CHAR LIMIT=NONE] Advanced applications screen, preference title.  Choose the emergency application. -->
+    <string name="default_emergency_app">Default emergency app</string>
     <!-- [CHAR LIMIT=NONE] Manage applications screen, menu item.  Reset all of user's app preferences. -->
     <string name="reset_app_preferences">Reset app preferences</string>
     <!-- [CHAR LIMIT=NONE] Manage applications screen, menu item.  Title of dialog to confirm resetting user's app preferences. -->
@@ -5637,6 +5639,7 @@
     <string name="keywords_users">restriction restrict restricted</string>
     <string name="keywords_keyboard_and_ime">text correction correct sound vibrate auto language gesture suggest suggestion theme offensive word type emoji international</string>
     <string name="keywords_reset_apps">reset preferences default</string>
+    <string name="keywords_emergency_app">emergency ice app default</string>
     <string name="keywords_all_apps">apps download applications system</string>
     <string name="keywords_app_permissions">apps permissions security</string>
     <!-- Search keywords for different screen unlock modes : slide to unlock, password, pattern and PIN [CHAR LIMIT=none] -->
diff --git a/res/xml/advanced_apps.xml b/res/xml/advanced_apps.xml
index e1759aa..2bbd5be 100644
--- a/res/xml/advanced_apps.xml
+++ b/res/xml/advanced_apps.xml
@@ -41,4 +41,9 @@
         android:summary="@string/reset_app_preferences_description"
         settings:keywords="@string/keywords_reset_apps" />
 
+    <com.android.settings.applications.DefaultEmergencyPreference
+        android:key="default_emergency_app"
+        android:title="@string/default_emergency_app"
+        settings:keywords="@string/keywords_emergency_app" />
+
 </PreferenceScreen>
diff --git a/src/com/android/settings/applications/DefaultEmergencyPreference.java b/src/com/android/settings/applications/DefaultEmergencyPreference.java
new file mode 100644
index 0000000..08e6e94
--- /dev/null
+++ b/src/com/android/settings/applications/DefaultEmergencyPreference.java
@@ -0,0 +1,137 @@
+/*
+ * 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.internal.util.ArrayUtils;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.os.AsyncTask;
+import android.preference.ListPreference;
+import android.provider.Settings;
+import android.telephony.TelephonyManager;
+import android.text.TextUtils;
+import android.util.ArrayMap;
+import android.util.AttributeSet;
+
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * A preference for choosing the default emergency app
+ */
+public class DefaultEmergencyPreference extends ListPreference {
+
+    private final ContentResolver mContentResolver;
+
+    public DefaultEmergencyPreference(Context context, AttributeSet attrs) {
+        super(context, attrs);
+        mContentResolver = context.getContentResolver();
+        load();
+    }
+
+    @Override
+    protected boolean persistString(String value) {
+        String previousValue = Settings.Secure.getString(mContentResolver,
+                Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION);
+
+        if (!TextUtils.isEmpty(value) && !Objects.equals(value, previousValue)) {
+            Settings.Secure.putString(mContentResolver,
+                    Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION,
+                    value);
+        }
+        setSummary(getEntry());
+        return true;
+    }
+
+    private void load() {
+        new AsyncTask<Void, Void, ArrayMap<String, CharSequence>>() {
+            @Override
+            protected ArrayMap<String, CharSequence> doInBackground(Void[] params) {
+                return resolveAssistPackageAndQueryApps();
+            }
+
+            @Override
+            protected void onPostExecute(ArrayMap<String, CharSequence> entries) {
+                setEntries(entries.values().toArray(new CharSequence[entries.size()]));
+                setEntryValues(entries.keySet().toArray(new String[entries.size()]));
+
+                setValue(Settings.Secure.getString(mContentResolver,
+                        Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION));
+            }
+        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+    }
+
+    private ArrayMap<String, CharSequence> resolveAssistPackageAndQueryApps() {
+        ArrayMap<String, CharSequence> packages = new ArrayMap<>();
+
+        Intent queryIntent = new Intent(TelephonyManager.ACTION_EMERGENCY_ASSISTANCE);
+        PackageManager packageManager = getContext().getPackageManager();
+        List<ResolveInfo> infos = packageManager.queryIntentActivities(queryIntent, 0);
+
+        PackageInfo bestMatch = null;
+        for (int i = 0; i < infos.size(); i++) {
+            if (infos.get(i) == null || infos.get(i).activityInfo == null
+                    || packages.containsKey(infos.get(i).activityInfo.packageName)) {
+                continue;
+            }
+
+            String packageName = infos.get(i).activityInfo.packageName;
+            CharSequence label = infos.get(i).activityInfo.applicationInfo
+                    .loadLabel(packageManager);
+
+            packages.put(packageName, label);
+
+            PackageInfo packageInfo;
+            try {
+                packageInfo = packageManager.getPackageInfo(packageName, 0);
+            } catch (PackageManager.NameNotFoundException e) {
+                continue;
+            }
+
+            // Get earliest installed app, but prioritize system apps.
+            if (bestMatch == null
+                    || !isSystemApp(bestMatch) && isSystemApp(packageInfo)
+                    || isSystemApp(bestMatch) == isSystemApp(packageInfo)
+                    && bestMatch.firstInstallTime > packageInfo.firstInstallTime) {
+                bestMatch = packageInfo;
+            }
+        }
+
+        String defaultPackage = Settings.Secure.getString(mContentResolver,
+                Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION);
+        boolean defaultMissing = TextUtils.isEmpty(defaultPackage)
+                || !packages.containsKey(defaultPackage);
+        if (bestMatch != null && defaultMissing) {
+            Settings.Secure.putString(mContentResolver,
+                    Settings.Secure.EMERGENCY_ASSISTANCE_APPLICATION,
+                    bestMatch.packageName);
+        }
+
+        return packages;
+    }
+
+    private static boolean isSystemApp(PackageInfo info) {
+        return info.applicationInfo != null
+                && (info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
+    }
+}