blob: a9d2c8a396316af0b80f562291d5108fe77854c8 [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070020import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010021import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070022import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010023import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070025import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010026import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010027import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080028import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070029import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080030import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070031import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080033import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010035import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070036import android.content.pm.IntentFilterVerificationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070039import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070040import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020041import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040044import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070045import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070046import android.graphics.Bitmap;
47import android.graphics.BitmapFactory;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080048import android.net.ConnectivityManager;
49import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070050import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070051import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020052import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010053import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040054import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010055import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040056import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070057import android.os.UserHandle;
58import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080059import android.os.storage.StorageManager;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070060import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070064import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070065import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070066import android.service.persistentdata.PersistentDataBlockManager;
Jason Monk39b46742015-09-10 15:52:51 -040067import android.support.v7.preference.Preference;
68import android.support.v7.preference.PreferenceGroup;
Amith Yamasani60133dd2010-09-11 14:17:31 -070069import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040070import android.text.Spannable;
71import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020072import android.text.TextUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040073import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070074import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010075import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000076import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000077import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070078import android.view.View;
79import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040080import android.view.animation.Animation;
81import android.view.animation.Animation.AnimationListener;
82import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070083import android.widget.ListView;
84import android.widget.TabWidget;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010085import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050086import com.android.settings.UserAdapter.UserDetails;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070087
Amith Yamasaniae47ef42012-09-16 17:53:35 -070088import java.io.IOException;
89import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080090import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070091import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010092import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080093import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070094import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090095import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080096
Tony Mantler67cd6ab2015-06-08 14:41:02 -070097import static android.content.Intent.EXTRA_USER;
98
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070099public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100100 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100101
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800102 /**
103 * Set the preference's title to the matching activity's label.
104 */
105 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
106
107 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900108 * The opacity level of a disabled icon.
109 */
110 public static final float DISABLED_ALPHA = 0.4f;
111
112 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700113 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
114 * 1 is most bad (red), the last value is least bad (green).
115 */
116 public static final int[] BADNESS_COLORS = new int[] {
117 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
118 0xfffabf2c, 0xff679e37, 0xff0a7f42
119 };
120
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100121 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
122
Elliott Hughes7253df32014-09-02 17:10:14 -0700123 private static final int SECONDS_PER_MINUTE = 60;
124 private static final int SECONDS_PER_HOUR = 60 * 60;
125 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
126
Jason Monkbeb171d2015-05-21 15:24:37 -0400127 public static final String OS_PKG = "os";
128
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000129 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
130
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200131 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800132 * Finds a matching activity for a preference's intent. If a matching
133 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800134 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800135 * @param context The context.
136 * @param parentPreferenceGroup The preference group that contains the
137 * preference whose intent is being resolved.
138 * @param preferenceKey The key of the preference whose intent is being
139 * resolved.
140 * @param flags 0 or one or more of
141 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
142 * .
143 * @return Whether an activity was found. If false, the preference was
144 * removed.
145 */
146 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
147 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800148
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800149 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
150 if (preference == null) {
151 return false;
152 }
Ying Wanga7188322010-01-04 18:45:10 -0800153
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 Intent intent = preference.getIntent();
155 if (intent != null) {
156 // Find the activity that is in the system image
157 PackageManager pm = context.getPackageManager();
158 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
159 int listSize = list.size();
160 for (int i = 0; i < listSize; i++) {
161 ResolveInfo resolveInfo = list.get(i);
162 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
163 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800164
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800165 // Replace the intent with this specific activity
166 preference.setIntent(new Intent().setClassName(
167 resolveInfo.activityInfo.packageName,
168 resolveInfo.activityInfo.name));
169
170 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
171 // Set the preference title to the activity's label
172 preference.setTitle(resolveInfo.loadLabel(pm));
173 }
Ying Wanga7188322010-01-04 18:45:10 -0800174
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800175 return true;
176 }
177 }
178 }
179
180 // Did not find a matching activity, so remove the preference
181 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800182
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900183 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 }
Ying Wanga7188322010-01-04 18:45:10 -0800185
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200186 /**
Ying Wanga7188322010-01-04 18:45:10 -0800187 * Returns true if Monkey is running.
188 */
189 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700190 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800191 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700192
193 /**
194 * Returns whether the device is voice-capable (meaning, it is also a phone).
195 */
196 public static boolean isVoiceCapable(Context context) {
197 TelephonyManager telephony =
198 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
199 return telephony != null && telephony.isVoiceCapable();
200 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800201
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700202 public static boolean isWifiOnly(Context context) {
203 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
204 Context.CONNECTIVITY_SERVICE);
205 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800206 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800207
208 /**
209 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
210 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900211 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800212 */
213 public static String getWifiIpAddresses(Context context) {
214 ConnectivityManager cm = (ConnectivityManager)
215 context.getSystemService(Context.CONNECTIVITY_SERVICE);
216 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700217 return formatIpAddresses(prop);
218 }
219
220 /**
221 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
222 * addresses.
223 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900224 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700225 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900226 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700227 LinkProperties prop = cm.getActiveLinkProperties();
228 return formatIpAddresses(prop);
229 }
230
231 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800232 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900233 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800234 // If there are no entries, return null
235 if (!iter.hasNext()) return null;
236 // Concatenate all available addresses, comma separated
237 String addresses = "";
238 while (iter.hasNext()) {
239 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900240 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800241 }
242 return addresses;
243 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900244
245 public static Locale createLocaleFromString(String localeStr) {
246 // TODO: is there a better way to actually construct a locale that will match?
247 // The main problem is, on top of Java specs, locale.toString() and
248 // new Locale(locale.toString()).toString() do not return equal() strings in
249 // many cases, because the constructor takes the only string as the language
250 // code. So : new Locale("en", "US").toString() => "en_US"
251 // And : new Locale("en_US").toString() => "en_us"
252 if (null == localeStr)
253 return Locale.getDefault();
254 String[] brokenDownLocale = localeStr.split("_", 3);
255 // split may not return a 0-length array.
256 if (1 == brokenDownLocale.length) {
257 return new Locale(brokenDownLocale[0]);
258 } else if (2 == brokenDownLocale.length) {
259 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
260 } else {
261 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
262 }
263 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700264
Elliott Hughes7253df32014-09-02 17:10:14 -0700265 /** Formats the ratio of amount/total as a percentage. */
266 public static String formatPercentage(long amount, long total) {
267 return formatPercentage(((double) amount) / total);
268 }
269
270 /** Formats an integer from 0..100 as a percentage. */
271 public static String formatPercentage(int percentage) {
272 return formatPercentage(((double) percentage) / 100.0);
273 }
274
275 /** Formats a double from 0.0..1.0 as a percentage. */
276 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700277 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700278 }
279
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900280 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
281 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
282 }
283
Amith Yamasania4379d62011-07-22 10:34:58 -0700284 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700285 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700286 }
287
288 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900289 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
290 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700291 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700292 }
293
294 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
295 final Intent intent = batteryChangedIntent;
296
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900297 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
298 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
299 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700300 String statusString;
301 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700302 int resId;
303 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
304 resId = R.string.battery_info_status_charging_ac;
305 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
306 resId = R.string.battery_info_status_charging_usb;
307 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
308 resId = R.string.battery_info_status_charging_wireless;
309 } else {
310 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700311 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700312 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700313 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
314 statusString = res.getString(R.string.battery_info_status_discharging);
315 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
316 statusString = res.getString(R.string.battery_info_status_not_charging);
317 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
318 statusString = res.getString(R.string.battery_info_status_full);
319 } else {
320 statusString = res.getString(R.string.battery_info_status_unknown);
321 }
322
323 return statusString;
324 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700325
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800326 public static void forcePrepareCustomPreferencesList(
327 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
328 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
329 list.setClipToPadding(false);
330 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
331 }
332
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700333 /**
334 * Prepare a custom preferences layout, moving padding to {@link ListView}
335 * when outside scrollbars are requested. Usually used to display
336 * {@link ListView} and {@link TabWidget} with correct padding.
337 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700338 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800339 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700340 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700341 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700342 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700343 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700344 final int paddingBottom = res.getDimensionPixelSize(
345 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700346
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700347 if (parent instanceof PreferenceFrameLayout) {
348 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
349
350 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
351 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
352 } else {
353 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
354 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700355 }
356 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700357
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700358 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700359 final Resources res = view.getResources();
360 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700361
362 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
363 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700364 final int paddingBottom = res.getDimensionPixelSize(
365 com.android.internal.R.dimen.preference_fragment_padding_bottom);
366
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700367 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700368 }
369
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700370 /* Used by UserSettings as well. Call this on a non-ui thread. */
371 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
372 Uri contactUri = Profile.CONTENT_URI;
373
374 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
375 context.getContentResolver(),
376 contactUri, true);
377 // If there's no profile photo, assign a default avatar
378 if (avatarDataStream == null) {
379 return false;
380 }
381 int userId = user != null ? user.id : UserHandle.myUserId();
382 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700383 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
384 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700385 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700386 avatarDataStream.close();
387 } catch (IOException ioe) { }
388 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700389 }
390
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700391 public static String getMeProfileName(Context context, boolean full) {
392 if (full) {
393 return getProfileDisplayName(context);
394 } else {
395 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700396 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700397 }
398
399 private static String getShorterNameIfPossible(Context context) {
400 final String given = getLocalProfileGivenName(context);
401 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
402 }
403
404 private static String getLocalProfileGivenName(Context context) {
405 final ContentResolver cr = context.getContentResolver();
406
407 // Find the raw contact ID for the local ME profile raw contact.
408 final long localRowProfileId;
409 final Cursor localRawProfile = cr.query(
410 Profile.CONTENT_RAW_CONTACTS_URI,
411 new String[] {RawContacts._ID},
412 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
413 RawContacts.ACCOUNT_NAME + " IS NULL",
414 null, null);
415 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700416
417 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700418 if (!localRawProfile.moveToFirst()) {
419 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700420 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700421 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700422 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700423 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700424 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700425
426 // Find the structured name for the raw contact.
427 final Cursor structuredName = cr.query(
428 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
429 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
430 CommonDataKinds.StructuredName.FAMILY_NAME},
431 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
432 null, null);
433 if (structuredName == null) return null;
434
435 try {
436 if (!structuredName.moveToFirst()) {
437 return null;
438 }
439 String partialName = structuredName.getString(0);
440 if (TextUtils.isEmpty(partialName)) {
441 partialName = structuredName.getString(1);
442 }
443 return partialName;
444 } finally {
445 structuredName.close();
446 }
447 }
448
449 private static final String getProfileDisplayName(Context context) {
450 final ContentResolver cr = context.getContentResolver();
451 final Cursor profile = cr.query(Profile.CONTENT_URI,
452 new String[] {Profile.DISPLAY_NAME}, null, null, null);
453 if (profile == null) return null;
454
455 try {
456 if (!profile.moveToFirst()) {
457 return null;
458 }
459 return profile.getString(0);
460 } finally {
461 profile.close();
462 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700463 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700464
465 /** Not global warming, it's global change warning. */
466 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
467 final Runnable positiveAction) {
468 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
469 builder.setTitle(titleResId);
470 builder.setMessage(R.string.global_change_warning);
471 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
472 @Override
473 public void onClick(DialogInterface dialog, int which) {
474 positiveAction.run();
475 }
476 });
477 builder.setNegativeButton(android.R.string.cancel, null);
478
479 return builder.create();
480 }
481
482 public static boolean hasMultipleUsers(Context context) {
483 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
484 .getUsers().size() > 1;
485 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700486
487 /**
488 * Start a new instance of the activity, showing only the given fragment.
489 * When launched in this mode, the given preference fragment will be instantiated and fill the
490 * entire activity.
491 *
492 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000493 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700494 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700495 * @param resultTo Option fragment that should receive the result of the activity launch.
496 * @param resultRequestCode If resultTo is non-null, this is the request code in which
497 * to report the result.
498 * @param titleResId resource id for the String to display for the title of this set
499 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700500 * @param title String to display for the title of this set of preferences.
501 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000502 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100503 Fragment resultTo, int resultRequestCode, int titleResId,
504 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700505 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100506 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
507 }
508
509 /**
510 * Start a new instance of the activity, showing only the given fragment.
511 * When launched in this mode, the given preference fragment will be instantiated and fill the
512 * entire activity.
513 *
514 * @param context The context.
515 * @param fragmentName The name of the fragment to display.
516 * @param args Optional arguments to supply to the fragment.
517 * @param resultTo Option fragment that should receive the result of the activity launch.
518 * @param resultRequestCode If resultTo is non-null, this is the request code in which
519 * to report the result.
520 * @param titleResPackageName Optional package name for the resource id of the title.
521 * @param titleResId resource id for the String to display for the title of this set
522 * of preferences.
523 * @param title String to display for the title of this set of preferences.
524 */
525 public static void startWithFragment(Context context, String fragmentName, Bundle args,
526 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
527 CharSequence title) {
528 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
529 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700530 }
531
532 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100533 Fragment resultTo, int resultRequestCode, int titleResId,
534 CharSequence title, boolean isShortcut) {
535 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
536 null /* titleResPackageName */, titleResId, title, isShortcut);
537 if (resultTo == null) {
538 context.startActivity(intent);
539 } else {
540 resultTo.startActivityForResult(intent, resultRequestCode);
541 }
542 }
543
544 public static void startWithFragment(Context context, String fragmentName, Bundle args,
545 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
546 CharSequence title, boolean isShortcut) {
547 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
548 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700549 if (resultTo == null) {
550 context.startActivity(intent);
551 } else {
552 resultTo.startActivityForResult(intent, resultRequestCode);
553 }
554 }
555
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100556 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100557 int titleResId, CharSequence title, boolean isShortcut,
558 UserHandle userHandle) {
559 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
560 null /* titleResPackageName */, titleResId, title, isShortcut);
561 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
562 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
563 context.startActivityAsUser(intent, userHandle);
564 }
565
566 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
567 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
568 UserHandle userHandle) {
569 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
570 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100571 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
572 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100573 context.startActivityAsUser(intent, userHandle);
574 }
575
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700576 /**
577 * Build an Intent to launch a new activity showing the selected fragment.
578 * The implementation constructs an Intent that re-launches the current activity with the
579 * appropriate arguments to display the fragment.
580 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700581 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000583 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700584 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100585 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700586 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700587 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700588 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700589 * @return Returns an Intent that can be launched to display the given
590 * fragment.
591 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000592 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100593 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
594 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700595 Intent intent = new Intent(Intent.ACTION_MAIN);
596 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000597 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700598 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100599 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
600 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700601 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700602 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700603 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604 return intent;
605 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100606
607 /**
608 * Returns the managed profile of the current user or null if none found.
609 */
610 public static UserHandle getManagedProfile(UserManager userManager) {
611 List<UserHandle> userProfiles = userManager.getUserProfiles();
612 final int count = userProfiles.size();
613 for (int i = 0; i < count; i++) {
614 final UserHandle profile = userProfiles.get(i);
615 if (profile.getIdentifier() == userManager.getUserHandle()) {
616 continue;
617 }
618 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
619 if (userInfo.isManagedProfile()) {
620 return profile;
621 }
622 }
623 return null;
624 }
625
626 /**
627 * Returns true if the current profile is a managed one.
628 */
629 public static boolean isManagedProfile(UserManager userManager) {
630 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
631 return currentUser.isManagedProfile();
632 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100633
634 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500635 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100636 *
637 * <p> The adapter can be used to populate a spinner that switches between the Settings
638 * app on the different profiles.
639 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500640 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100641 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500642 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100643 Context context) {
644 List<UserHandle> userProfiles = userManager.getUserProfiles();
645 if (userProfiles.size() < 2) {
646 return null;
647 }
648
649 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
650 // The first option should be the current profile
651 userProfiles.remove(myUserHandle);
652 userProfiles.add(0, myUserHandle);
653
Jason Monk2ebc8a02015-02-13 15:23:19 -0500654 return createUserAdapter(userManager, context, userProfiles);
655 }
656
657 public static UserAdapter createUserAdapter(UserManager userManager,
658 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100659 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
660 final int count = userProfiles.size();
661 for (int i = 0; i < count; i++) {
662 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
663 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500664 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100665 }
666
667 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100668 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100669 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100670 * The target user can be either the current user, the user that launched this activity or
671 * the user contained as an extra in the arguments or intent extras.
672 *
673 * Note: This is secure in the sense that it only returns a target user different to the current
674 * one if the app launching this activity is the Settings app itself, running in the same user
675 * or in one that is in the same profile group, or if the user id is provided by the system.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100676 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100677 public static UserHandle getSecureTargetUser(IBinder activityToken,
678 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
679 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
680 IActivityManager am = ActivityManagerNative.getDefault();
681 try {
682 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
683 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
684
685 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
686 am.getLaunchedFromUid(activityToken)));
687 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
688 // Check it's secure
689 if (isProfileOf(um, launchedFromUser)) {
690 return launchedFromUser;
691 }
692 }
693 UserHandle extrasUser = intentExtras != null
694 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
695 if (extrasUser != null && !extrasUser.equals(currentUser)) {
696 // Check it's secure
697 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
698 return extrasUser;
699 }
700 }
701 UserHandle argumentsUser = arguments != null
702 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
703 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
704 // Check it's secure
705 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
706 return argumentsUser;
707 }
708 }
709 } catch (RemoteException e) {
710 // Should not happen
711 Log.v(TAG, "Could not talk to activity manager.", e);
712 }
713 return currentUser;
714 }
715
716 /**
717 * Returns the target user for a Settings activity.
718 *
719 * The target user can be either the current user, the user that launched this activity or
720 * the user contained as an extra in the arguments or intent extras.
721 *
722 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
723 * possible.
724 *
725 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
726 */
727 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
728 @Nullable Bundle intentExtras) {
729 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
730 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100731 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100732 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
733 am.getLaunchedFromUid(activityToken)));
734 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
735 return launchedFromUser;
736 }
737 UserHandle extrasUser = intentExtras != null
738 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
739 if (extrasUser != null && !extrasUser.equals(currentUser)) {
740 return extrasUser;
741 }
742 UserHandle argumentsUser = arguments != null
743 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
744 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
745 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100746 }
747 } catch (RemoteException e) {
748 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100749 Log.v(TAG, "Could not talk to activity manager.", e);
750 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100751 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100752 return currentUser;
753 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100754
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100755 /**
756 * Returns true if the user provided is in the same profiles group as the current user.
757 */
758 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
759 if (um == null || otherUser == null) return false;
760 return (UserHandle.myUserId() == otherUser.getIdentifier())
761 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100762 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530763
Andres Moralesce249fe2014-07-07 16:58:16 -0700764
765 /**
766 * Returns whether or not this device is able to be OEM unlocked.
767 */
768 static boolean isOemUnlockEnabled(Context context) {
769 PersistentDataBlockManager manager =(PersistentDataBlockManager)
770 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
771 return manager.getOemUnlockEnabled();
772 }
773
774 /**
775 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
776 * devices allow users to flash other OSes to them.
777 */
778 static void setOemUnlockEnabled(Context context, boolean enabled) {
779 PersistentDataBlockManager manager =(PersistentDataBlockManager)
780 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
781 manager.setOemUnlockEnabled(enabled);
782 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100783
784 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700785 * Return whether or not the user should have a SIM Cards option in Settings.
786 * TODO: Change back to returning true if count is greater than one after testing.
787 * TODO: See bug 16533525.
788 */
789 public static boolean showSimCardTile(Context context) {
790 final TelephonyManager tm =
791 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
792
PauloftheWestdbd03822014-12-04 11:56:35 -0800793 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700794 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200795
796 /**
797 * Determine whether a package is a "system package", in which case certain things (like
798 * disabling notifications or disabling the package altogether) should be disallowed.
799 */
800 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
801 if (sSystemSignature == null) {
802 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
803 }
804 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
805 }
806
807 private static Signature[] sSystemSignature;
808
809 private static Signature getFirstSignature(PackageInfo pkg) {
810 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
811 return pkg.signatures[0];
812 }
813 return null;
814 }
815
816 private static Signature getSystemSignature(PackageManager pm) {
817 try {
818 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
819 return getFirstSignature(sys);
820 } catch (NameNotFoundException e) {
821 }
822 return null;
823 }
824
Elliott Hughes7253df32014-09-02 17:10:14 -0700825 /**
826 * Returns elapsed time for the given millis, in the following format:
827 * 2d 5h 40m 29s
828 * @param context the application context
829 * @param millis the elapsed time in milli seconds
830 * @param withSeconds include seconds?
831 * @return the formatted elapsed time
832 */
833 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
834 StringBuilder sb = new StringBuilder();
835 int seconds = (int) Math.floor(millis / 1000);
836 if (!withSeconds) {
837 // Round up.
838 seconds += 30;
839 }
840
841 int days = 0, hours = 0, minutes = 0;
842 if (seconds >= SECONDS_PER_DAY) {
843 days = seconds / SECONDS_PER_DAY;
844 seconds -= days * SECONDS_PER_DAY;
845 }
846 if (seconds >= SECONDS_PER_HOUR) {
847 hours = seconds / SECONDS_PER_HOUR;
848 seconds -= hours * SECONDS_PER_HOUR;
849 }
850 if (seconds >= SECONDS_PER_MINUTE) {
851 minutes = seconds / SECONDS_PER_MINUTE;
852 seconds -= minutes * SECONDS_PER_MINUTE;
853 }
854 if (withSeconds) {
855 if (days > 0) {
856 sb.append(context.getString(R.string.battery_history_days,
857 days, hours, minutes, seconds));
858 } else if (hours > 0) {
859 sb.append(context.getString(R.string.battery_history_hours,
860 hours, minutes, seconds));
861 } else if (minutes > 0) {
862 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
863 } else {
864 sb.append(context.getString(R.string.battery_history_seconds, seconds));
865 }
866 } else {
867 if (days > 0) {
868 sb.append(context.getString(R.string.battery_history_days_no_seconds,
869 days, hours, minutes));
870 } else if (hours > 0) {
871 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
872 hours, minutes));
873 } else {
874 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
875 }
876 }
877 return sb.toString();
878 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800879
880 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800881 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
882 * @param userManager Instance of UserManager
883 * @param checkUser The user to check the existence of.
884 * @return UserInfo of the user or null for non-existent user.
885 */
886 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
887 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
888 final int checkUserId = checkUser.getIdentifier();
889 for (UserInfo user : users) {
890 if (user.id == checkUserId) {
891 return user;
892 }
893 }
894 return null;
895 }
896
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000897 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
898 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
899 com.android.internal.R.styleable.Preference,
900 com.android.internal.R.attr.preferenceCategoryStyle, 0);
901 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
902 0);
903 a.recycle();
904 return inflater.inflate(resId, parent, false);
905 }
906
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800907 /**
908 * Return if we are running low on storage space or not.
909 *
910 * @param context The context
911 * @return true if we are running low on storage space
912 */
913 public static boolean isLowStorage(Context context) {
914 final StorageManager sm = StorageManager.from(context);
915 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
916 }
917
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000918 /**
919 * Returns a default user icon (as a {@link Bitmap}) for the given user.
920 *
921 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
922 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
923 */
924 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
925 Bitmap bitmap = null;
926 // Try finding the corresponding bitmap in the dark bitmap cache
927 bitmap = sDarkDefaultUserBitmapCache.get(userId);
928 if (bitmap == null) {
929 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
930 // Save it to cache
931 sDarkDefaultUserBitmapCache.put(userId, bitmap);
932 }
933 return bitmap;
934 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800935
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800936 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
937 // Get list of preferred activities
938 List<ComponentName> prefActList = new ArrayList<>();
939 // Intent list cannot be null. so pass empty list
940 List<IntentFilter> intentList = new ArrayList<>();
941 pm.getPreferredActivities(intentList, prefActList, packageName);
942 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
943 return prefActList.size() > 0;
944 }
945
Christopher Tatea08a2252015-07-01 16:52:43 -0700946 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
947 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
948 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
949
950 ArraySet<String> result = new ArraySet<>();
951 if (iviList.size() > 0) {
952 for (IntentFilterVerificationInfo ivi : iviList) {
953 for (String host : ivi.getDomains()) {
954 result.add(host);
955 }
956 }
957 }
958 if (filters != null && filters.size() > 0) {
959 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700960 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
961 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
962 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700963 result.addAll(filter.getHostsList());
964 }
965 }
966 }
967 return result;
968 }
969
Jason Monkb5aa73f2015-03-31 12:59:33 -0400970 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
971 boolean animate) {
972 setViewShown(loading, !done, animate);
973 setViewShown(doneLoading, done, animate);
974 }
975
976 private static void setViewShown(final View view, boolean shown, boolean animate) {
977 if (animate) {
978 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
979 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
980 if (shown) {
981 view.setVisibility(View.VISIBLE);
982 } else {
983 animation.setAnimationListener(new AnimationListener() {
984 @Override
985 public void onAnimationStart(Animation animation) {
986 }
987
988 @Override
989 public void onAnimationRepeat(Animation animation) {
990 }
991
992 @Override
993 public void onAnimationEnd(Animation animation) {
994 view.setVisibility(View.INVISIBLE);
995 }
996 });
997 }
998 view.startAnimation(animation);
999 } else {
1000 view.clearAnimation();
1001 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1002 }
1003 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001004
1005 /**
1006 * Returns the application info of the currently installed MDM package.
1007 */
1008 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1009 DevicePolicyManager dpm =
1010 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1011 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1012 if (mdmPackage == null) {
1013 return null;
1014 }
1015 String mdmPackageName = mdmPackage.getPackageName();
1016 try {
1017 IPackageManager ipm = AppGlobals.getPackageManager();
1018 ApplicationInfo mdmApplicationInfo =
1019 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1020 return mdmApplicationInfo;
1021 } catch (RemoteException e) {
1022 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1023 + ", userId " + profileId, e);
1024 return null;
1025 }
1026 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001027
1028 public static boolean isBandwidthControlEnabled() {
1029 final INetworkManagementService netManager = INetworkManagementService.Stub
1030 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1031 try {
1032 return netManager.isBandwidthControlEnabled();
1033 } catch (RemoteException e) {
1034 return false;
1035 }
1036 }
Julia Reynoldsce25af42015-07-08 16:56:31 -04001037
1038 /**
1039 * Returns an accessible SpannableString.
1040 * @param displayText the text to display
1041 * @param accessibileText the text text-to-speech engines should read
1042 */
1043 public static SpannableString createAccessibleSequence(CharSequence displayText,
1044 String accessibileText) {
1045 SpannableString str = new SpannableString(displayText);
1046 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
1047 displayText.length(),
1048 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1049 return str;
1050 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001051
Clara Bayarrife432e82015-10-12 12:07:02 +01001052 /**
1053 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
1054 * belongs to the current user.
1055 *
1056 * @throws SecurityException if the given userId does not belong to the current user group.
1057 */
1058 public static int getSameOwnerUserId(Context context, Bundle bundle) {
1059 if (bundle == null) {
1060 return getEffectiveUserId(context);
1061 }
1062 int userId = bundle.getInt(ChooseLockGeneric.KEY_USER_ID, UserHandle.myUserId());
1063 return getSameOwnerUserId(context, userId);
1064 }
1065
1066 /**
1067 * Returns the given user id if it belongs to the current user.
1068 *
1069 * @throws SecurityException if the given userId does not belong to the current user group.
1070 */
1071 public static int getSameOwnerUserId(Context context, int userId) {
1072 UserManager um = UserManager.get(context);
1073 if (um != null) {
1074 if (um.getUserProfiles().contains(new UserHandle(userId))) {
1075 return userId;
1076 } else {
1077 throw new SecurityException("Given user id " + userId + " does not belong to user "
1078 + UserHandle.myUserId());
1079 }
1080 }
1081 return getEffectiveUserId(context);
1082 }
1083
Andres Morales7bdffd82015-08-04 16:55:00 -07001084 public static int getEffectiveUserId(Context context) {
1085 UserManager um = UserManager.get(context);
1086 if (um != null) {
1087 return um.getCredentialOwnerProfile(UserHandle.myUserId());
1088 } else {
1089 Log.e(TAG, "Unable to acquire UserManager");
1090 return UserHandle.myUserId();
1091 }
1092 }
1093}
1094