blob: bc6cbedebec6a7d641905990f90e90e59066f802 [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 static android.content.Intent.EXTRA_USER;
20
21import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070022import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010023import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.AlertDialog;
25import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070026import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010027import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070028import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080029import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070030import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080031import android.content.Intent;
32import android.content.pm.ApplicationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020033import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070035import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070036import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070038import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020039import android.content.res.Resources;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000040import android.content.res.TypedArray;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020041import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070043import android.graphics.Bitmap;
44import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080046import android.net.ConnectivityManager;
47import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070048import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070049import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020050import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010051import android.os.IBinder;
52import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070053import android.os.UserHandle;
54import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080055import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080056import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070057import android.preference.PreferenceFrameLayout;
58import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070059import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070060import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070064import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080065import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080066import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070067import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020068import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010069import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000070import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000071import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070072import android.view.View;
73import android.view.ViewGroup;
74import android.widget.ListView;
75import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010076
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010077import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050078import com.android.settings.UserAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070079import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010080import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070081
Amith Yamasaniae47ef42012-09-16 17:53:35 -070082import java.io.IOException;
83import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080084import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070085import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010086import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080087import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070088import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090089import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080090
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070091public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010092 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010093
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080094 /**
95 * Set the preference's title to the matching activity's label.
96 */
97 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
98
99 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900100 * The opacity level of a disabled icon.
101 */
102 public static final float DISABLED_ALPHA = 0.4f;
103
104 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700105 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
106 * 1 is most bad (red), the last value is least bad (green).
107 */
108 public static final int[] BADNESS_COLORS = new int[] {
109 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
110 0xfffabf2c, 0xff679e37, 0xff0a7f42
111 };
112
113 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200114 * Name of the meta-data item that should be set in the AndroidManifest.xml
115 * to specify the icon that should be displayed for the preference.
116 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500117 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200118
119 /**
120 * Name of the meta-data item that should be set in the AndroidManifest.xml
121 * to specify the title that should be displayed for the preference.
122 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500123 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200124
125 /**
126 * Name of the meta-data item that should be set in the AndroidManifest.xml
127 * to specify the summary text that should be displayed for the preference.
128 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500129 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200130
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100131 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
132
Elliott Hughes7253df32014-09-02 17:10:14 -0700133 private static final int SECONDS_PER_MINUTE = 60;
134 private static final int SECONDS_PER_HOUR = 60 * 60;
135 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
136
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000137 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
138
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200139 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800140 * Finds a matching activity for a preference's intent. If a matching
141 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800142 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800143 * @param context The context.
144 * @param parentPreferenceGroup The preference group that contains the
145 * preference whose intent is being resolved.
146 * @param preferenceKey The key of the preference whose intent is being
147 * resolved.
148 * @param flags 0 or one or more of
149 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
150 * .
151 * @return Whether an activity was found. If false, the preference was
152 * removed.
153 */
154 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
155 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800156
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800157 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
158 if (preference == null) {
159 return false;
160 }
Ying Wanga7188322010-01-04 18:45:10 -0800161
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800162 Intent intent = preference.getIntent();
163 if (intent != null) {
164 // Find the activity that is in the system image
165 PackageManager pm = context.getPackageManager();
166 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
167 int listSize = list.size();
168 for (int i = 0; i < listSize; i++) {
169 ResolveInfo resolveInfo = list.get(i);
170 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
171 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800172
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 // Replace the intent with this specific activity
174 preference.setIntent(new Intent().setClassName(
175 resolveInfo.activityInfo.packageName,
176 resolveInfo.activityInfo.name));
177
178 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
179 // Set the preference title to the activity's label
180 preference.setTitle(resolveInfo.loadLabel(pm));
181 }
Ying Wanga7188322010-01-04 18:45:10 -0800182
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800183 return true;
184 }
185 }
186 }
187
188 // Did not find a matching activity, so remove the preference
189 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800190
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900191 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700194 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700195 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700196
197 Intent intent = tile.intent;
198 if (intent != null) {
199 // Find the activity that is in the system image
200 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500201 List<ResolveInfo> list = tile.userHandle.size() != 0
202 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
203 tile.userHandle.get(0).getIdentifier())
204 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700205 int listSize = list.size();
206 for (int i = 0; i < listSize; i++) {
207 ResolveInfo resolveInfo = list.get(i);
208 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
209 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500210 int icon = 0;
211 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700212 String summary = null;
213
214 // Get the activity's meta-data
215 try {
216 Resources res = pm.getResourcesForApplication(
217 resolveInfo.activityInfo.packageName);
218 Bundle metaData = resolveInfo.activityInfo.metaData;
219
220 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500221 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
222 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
223 }
224 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
225 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
226 }
227 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
228 summary = res.getString(
229 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
230 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700231 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500232 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700233 // Ignore
234 }
235
236 // Set the preference title to the activity's label if no
237 // meta-data is found
238 if (TextUtils.isEmpty(title)) {
239 title = resolveInfo.loadLabel(pm).toString();
240 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500241 if (icon == 0) {
242 icon = resolveInfo.activityInfo.icon;
243 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700244
245 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500246 tile.iconRes = icon;
247 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700248 tile.title = title;
249 tile.summary = summary;
250 // Replace the intent with this specific activity
251 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
252 resolveInfo.activityInfo.name);
253
254 return true;
255 }
256 }
257 }
258
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700259 return false;
260 }
261
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200262 /**
Ying Wanga7188322010-01-04 18:45:10 -0800263 * Returns true if Monkey is running.
264 */
265 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700266 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800267 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700268
269 /**
270 * Returns whether the device is voice-capable (meaning, it is also a phone).
271 */
272 public static boolean isVoiceCapable(Context context) {
273 TelephonyManager telephony =
274 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
275 return telephony != null && telephony.isVoiceCapable();
276 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800277
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700278 public static boolean isWifiOnly(Context context) {
279 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
280 Context.CONNECTIVITY_SERVICE);
281 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800282 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800283
284 /**
285 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
286 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900287 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800288 */
289 public static String getWifiIpAddresses(Context context) {
290 ConnectivityManager cm = (ConnectivityManager)
291 context.getSystemService(Context.CONNECTIVITY_SERVICE);
292 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700293 return formatIpAddresses(prop);
294 }
295
296 /**
297 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
298 * addresses.
299 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900300 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700301 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900302 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700303 LinkProperties prop = cm.getActiveLinkProperties();
304 return formatIpAddresses(prop);
305 }
306
307 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800308 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900309 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800310 // If there are no entries, return null
311 if (!iter.hasNext()) return null;
312 // Concatenate all available addresses, comma separated
313 String addresses = "";
314 while (iter.hasNext()) {
315 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900316 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800317 }
318 return addresses;
319 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900320
321 public static Locale createLocaleFromString(String localeStr) {
322 // TODO: is there a better way to actually construct a locale that will match?
323 // The main problem is, on top of Java specs, locale.toString() and
324 // new Locale(locale.toString()).toString() do not return equal() strings in
325 // many cases, because the constructor takes the only string as the language
326 // code. So : new Locale("en", "US").toString() => "en_US"
327 // And : new Locale("en_US").toString() => "en_us"
328 if (null == localeStr)
329 return Locale.getDefault();
330 String[] brokenDownLocale = localeStr.split("_", 3);
331 // split may not return a 0-length array.
332 if (1 == brokenDownLocale.length) {
333 return new Locale(brokenDownLocale[0]);
334 } else if (2 == brokenDownLocale.length) {
335 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
336 } else {
337 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
338 }
339 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700340
Elliott Hughes7253df32014-09-02 17:10:14 -0700341 /** Formats the ratio of amount/total as a percentage. */
342 public static String formatPercentage(long amount, long total) {
343 return formatPercentage(((double) amount) / total);
344 }
345
346 /** Formats an integer from 0..100 as a percentage. */
347 public static String formatPercentage(int percentage) {
348 return formatPercentage(((double) percentage) / 100.0);
349 }
350
351 /** Formats a double from 0.0..1.0 as a percentage. */
352 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700353 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700354 }
355
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900356 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
357 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
358 }
359
Amith Yamasania4379d62011-07-22 10:34:58 -0700360 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700361 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700362 }
363
364 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900365 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
366 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700367 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700368 }
369
370 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
371 final Intent intent = batteryChangedIntent;
372
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900373 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
374 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
375 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700376 String statusString;
377 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700378 int resId;
379 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
380 resId = R.string.battery_info_status_charging_ac;
381 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
382 resId = R.string.battery_info_status_charging_usb;
383 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
384 resId = R.string.battery_info_status_charging_wireless;
385 } else {
386 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700387 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700388 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700389 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
390 statusString = res.getString(R.string.battery_info_status_discharging);
391 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
392 statusString = res.getString(R.string.battery_info_status_not_charging);
393 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
394 statusString = res.getString(R.string.battery_info_status_full);
395 } else {
396 statusString = res.getString(R.string.battery_info_status_unknown);
397 }
398
399 return statusString;
400 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700401
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800402 public static void forcePrepareCustomPreferencesList(
403 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
404 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
405 list.setClipToPadding(false);
406 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
407 }
408
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700409 /**
410 * Prepare a custom preferences layout, moving padding to {@link ListView}
411 * when outside scrollbars are requested. Usually used to display
412 * {@link ListView} and {@link TabWidget} with correct padding.
413 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700414 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800415 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700416 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700417 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700418 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700419 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700420 final int paddingBottom = res.getDimensionPixelSize(
421 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700422
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700423 if (parent instanceof PreferenceFrameLayout) {
424 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
425
426 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
427 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
428 } else {
429 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
430 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700431 }
432 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700433
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700434 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700435 final Resources res = view.getResources();
436 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700437
438 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
439 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700440 final int paddingBottom = res.getDimensionPixelSize(
441 com.android.internal.R.dimen.preference_fragment_padding_bottom);
442
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700443 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700444 }
445
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700446 /**
447 * Return string resource that best describes combination of tethering
448 * options available on this device.
449 */
450 public static int getTetheringLabel(ConnectivityManager cm) {
451 String[] usbRegexs = cm.getTetherableUsbRegexs();
452 String[] wifiRegexs = cm.getTetherableWifiRegexs();
453 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
454
455 boolean usbAvailable = usbRegexs.length != 0;
456 boolean wifiAvailable = wifiRegexs.length != 0;
457 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
458
459 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
460 return R.string.tether_settings_title_all;
461 } else if (wifiAvailable && usbAvailable) {
462 return R.string.tether_settings_title_all;
463 } else if (wifiAvailable && bluetoothAvailable) {
464 return R.string.tether_settings_title_all;
465 } else if (wifiAvailable) {
466 return R.string.tether_settings_title_wifi;
467 } else if (usbAvailable && bluetoothAvailable) {
468 return R.string.tether_settings_title_usb_bluetooth;
469 } else if (usbAvailable) {
470 return R.string.tether_settings_title_usb;
471 } else {
472 return R.string.tether_settings_title_bluetooth;
473 }
474 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700475
476 /* Used by UserSettings as well. Call this on a non-ui thread. */
477 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
478 Uri contactUri = Profile.CONTENT_URI;
479
480 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
481 context.getContentResolver(),
482 contactUri, true);
483 // If there's no profile photo, assign a default avatar
484 if (avatarDataStream == null) {
485 return false;
486 }
487 int userId = user != null ? user.id : UserHandle.myUserId();
488 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700489 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
490 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700491 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700492 avatarDataStream.close();
493 } catch (IOException ioe) { }
494 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700495 }
496
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700497 public static String getMeProfileName(Context context, boolean full) {
498 if (full) {
499 return getProfileDisplayName(context);
500 } else {
501 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700502 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700503 }
504
505 private static String getShorterNameIfPossible(Context context) {
506 final String given = getLocalProfileGivenName(context);
507 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
508 }
509
510 private static String getLocalProfileGivenName(Context context) {
511 final ContentResolver cr = context.getContentResolver();
512
513 // Find the raw contact ID for the local ME profile raw contact.
514 final long localRowProfileId;
515 final Cursor localRawProfile = cr.query(
516 Profile.CONTENT_RAW_CONTACTS_URI,
517 new String[] {RawContacts._ID},
518 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
519 RawContacts.ACCOUNT_NAME + " IS NULL",
520 null, null);
521 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700522
523 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700524 if (!localRawProfile.moveToFirst()) {
525 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700526 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700527 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700528 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700529 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700530 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700531
532 // Find the structured name for the raw contact.
533 final Cursor structuredName = cr.query(
534 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
535 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
536 CommonDataKinds.StructuredName.FAMILY_NAME},
537 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
538 null, null);
539 if (structuredName == null) return null;
540
541 try {
542 if (!structuredName.moveToFirst()) {
543 return null;
544 }
545 String partialName = structuredName.getString(0);
546 if (TextUtils.isEmpty(partialName)) {
547 partialName = structuredName.getString(1);
548 }
549 return partialName;
550 } finally {
551 structuredName.close();
552 }
553 }
554
555 private static final String getProfileDisplayName(Context context) {
556 final ContentResolver cr = context.getContentResolver();
557 final Cursor profile = cr.query(Profile.CONTENT_URI,
558 new String[] {Profile.DISPLAY_NAME}, null, null, null);
559 if (profile == null) return null;
560
561 try {
562 if (!profile.moveToFirst()) {
563 return null;
564 }
565 return profile.getString(0);
566 } finally {
567 profile.close();
568 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700569 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700570
571 /** Not global warming, it's global change warning. */
572 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
573 final Runnable positiveAction) {
574 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
575 builder.setTitle(titleResId);
576 builder.setMessage(R.string.global_change_warning);
577 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
578 @Override
579 public void onClick(DialogInterface dialog, int which) {
580 positiveAction.run();
581 }
582 });
583 builder.setNegativeButton(android.R.string.cancel, null);
584
585 return builder.create();
586 }
587
588 public static boolean hasMultipleUsers(Context context) {
589 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
590 .getUsers().size() > 1;
591 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700592
593 /**
594 * Start a new instance of the activity, showing only the given fragment.
595 * When launched in this mode, the given preference fragment will be instantiated and fill the
596 * entire activity.
597 *
598 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000599 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700600 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700601 * @param resultTo Option fragment that should receive the result of the activity launch.
602 * @param resultRequestCode If resultTo is non-null, this is the request code in which
603 * to report the result.
604 * @param titleResId resource id for the String to display for the title of this set
605 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700606 * @param title String to display for the title of this set of preferences.
607 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000608 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100609 Fragment resultTo, int resultRequestCode, int titleResId,
610 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700611 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100612 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
613 }
614
615 /**
616 * Start a new instance of the activity, showing only the given fragment.
617 * When launched in this mode, the given preference fragment will be instantiated and fill the
618 * entire activity.
619 *
620 * @param context The context.
621 * @param fragmentName The name of the fragment to display.
622 * @param args Optional arguments to supply to the fragment.
623 * @param resultTo Option fragment that should receive the result of the activity launch.
624 * @param resultRequestCode If resultTo is non-null, this is the request code in which
625 * to report the result.
626 * @param titleResPackageName Optional package name for the resource id of the title.
627 * @param titleResId resource id for the String to display for the title of this set
628 * of preferences.
629 * @param title String to display for the title of this set of preferences.
630 */
631 public static void startWithFragment(Context context, String fragmentName, Bundle args,
632 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
633 CharSequence title) {
634 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
635 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700636 }
637
638 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100639 Fragment resultTo, int resultRequestCode, int titleResId,
640 CharSequence title, boolean isShortcut) {
641 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
642 null /* titleResPackageName */, titleResId, title, isShortcut);
643 if (resultTo == null) {
644 context.startActivity(intent);
645 } else {
646 resultTo.startActivityForResult(intent, resultRequestCode);
647 }
648 }
649
650 public static void startWithFragment(Context context, String fragmentName, Bundle args,
651 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
652 CharSequence title, boolean isShortcut) {
653 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
654 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700655 if (resultTo == null) {
656 context.startActivity(intent);
657 } else {
658 resultTo.startActivityForResult(intent, resultRequestCode);
659 }
660 }
661
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100662 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100663 int titleResId, CharSequence title, boolean isShortcut,
664 UserHandle userHandle) {
665 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
666 null /* titleResPackageName */, titleResId, title, isShortcut);
667 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
668 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
669 context.startActivityAsUser(intent, userHandle);
670 }
671
672 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
673 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
674 UserHandle userHandle) {
675 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
676 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100677 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
678 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100679 context.startActivityAsUser(intent, userHandle);
680 }
681
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700682 /**
683 * Build an Intent to launch a new activity showing the selected fragment.
684 * The implementation constructs an Intent that re-launches the current activity with the
685 * appropriate arguments to display the fragment.
686 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700687 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700688 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000689 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700690 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100691 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700692 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700693 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700694 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700695 * @return Returns an Intent that can be launched to display the given
696 * fragment.
697 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000698 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100699 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
700 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700701 Intent intent = new Intent(Intent.ACTION_MAIN);
702 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000703 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700704 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100705 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
706 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700707 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700708 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700709 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700710 return intent;
711 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100712
713 /**
714 * Returns the managed profile of the current user or null if none found.
715 */
716 public static UserHandle getManagedProfile(UserManager userManager) {
717 List<UserHandle> userProfiles = userManager.getUserProfiles();
718 final int count = userProfiles.size();
719 for (int i = 0; i < count; i++) {
720 final UserHandle profile = userProfiles.get(i);
721 if (profile.getIdentifier() == userManager.getUserHandle()) {
722 continue;
723 }
724 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
725 if (userInfo.isManagedProfile()) {
726 return profile;
727 }
728 }
729 return null;
730 }
731
732 /**
733 * Returns true if the current profile is a managed one.
734 */
735 public static boolean isManagedProfile(UserManager userManager) {
736 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
737 return currentUser.isManagedProfile();
738 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100739
740 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500741 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100742 *
743 * <p> The adapter can be used to populate a spinner that switches between the Settings
744 * app on the different profiles.
745 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500746 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100747 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500748 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100749 Context context) {
750 List<UserHandle> userProfiles = userManager.getUserProfiles();
751 if (userProfiles.size() < 2) {
752 return null;
753 }
754
755 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
756 // The first option should be the current profile
757 userProfiles.remove(myUserHandle);
758 userProfiles.add(0, myUserHandle);
759
Jason Monk2ebc8a02015-02-13 15:23:19 -0500760 return createUserAdapter(userManager, context, userProfiles);
761 }
762
763 public static UserAdapter createUserAdapter(UserManager userManager,
764 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100765 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
766 final int count = userProfiles.size();
767 for (int i = 0; i < count; i++) {
768 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
769 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500770 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100771 }
772
773 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100774 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100775 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100776 * The target user can be either the current user, the user that launched this activity or
777 * the user contained as an extra in the arguments or intent extras.
778 *
779 * Note: This is secure in the sense that it only returns a target user different to the current
780 * one if the app launching this activity is the Settings app itself, running in the same user
781 * 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 +0100782 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100783 public static UserHandle getSecureTargetUser(IBinder activityToken,
784 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
785 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
786 IActivityManager am = ActivityManagerNative.getDefault();
787 try {
788 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
789 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
790
791 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
792 am.getLaunchedFromUid(activityToken)));
793 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
794 // Check it's secure
795 if (isProfileOf(um, launchedFromUser)) {
796 return launchedFromUser;
797 }
798 }
799 UserHandle extrasUser = intentExtras != null
800 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
801 if (extrasUser != null && !extrasUser.equals(currentUser)) {
802 // Check it's secure
803 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
804 return extrasUser;
805 }
806 }
807 UserHandle argumentsUser = arguments != null
808 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
809 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
810 // Check it's secure
811 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
812 return argumentsUser;
813 }
814 }
815 } catch (RemoteException e) {
816 // Should not happen
817 Log.v(TAG, "Could not talk to activity manager.", e);
818 }
819 return currentUser;
820 }
821
822 /**
823 * Returns the target user for a Settings activity.
824 *
825 * The target user can be either the current user, the user that launched this activity or
826 * the user contained as an extra in the arguments or intent extras.
827 *
828 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
829 * possible.
830 *
831 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
832 */
833 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
834 @Nullable Bundle intentExtras) {
835 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
836 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100837 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100838 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
839 am.getLaunchedFromUid(activityToken)));
840 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
841 return launchedFromUser;
842 }
843 UserHandle extrasUser = intentExtras != null
844 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
845 if (extrasUser != null && !extrasUser.equals(currentUser)) {
846 return extrasUser;
847 }
848 UserHandle argumentsUser = arguments != null
849 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
850 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
851 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100852 }
853 } catch (RemoteException e) {
854 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100855 Log.v(TAG, "Could not talk to activity manager.", e);
856 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100857 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100858 return currentUser;
859 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100860
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100861 /**
862 * Returns true if the user provided is in the same profiles group as the current user.
863 */
864 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
865 if (um == null || otherUser == null) return false;
866 return (UserHandle.myUserId() == otherUser.getIdentifier())
867 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100868 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530869
Andres Moralesce249fe2014-07-07 16:58:16 -0700870
871 /**
872 * Returns whether or not this device is able to be OEM unlocked.
873 */
874 static boolean isOemUnlockEnabled(Context context) {
875 PersistentDataBlockManager manager =(PersistentDataBlockManager)
876 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
877 return manager.getOemUnlockEnabled();
878 }
879
880 /**
881 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
882 * devices allow users to flash other OSes to them.
883 */
884 static void setOemUnlockEnabled(Context context, boolean enabled) {
885 PersistentDataBlockManager manager =(PersistentDataBlockManager)
886 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
887 manager.setOemUnlockEnabled(enabled);
888 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100889
890 /**
891 * Returns a circular icon for a user.
892 */
893 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000894 if (user.isManagedProfile()) {
895 // We use predefined values for managed profiles
896 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
897 com.android.internal.R.drawable.ic_corp_icon);
898 return CircleFramedDrawable.getInstance(context, b);
899 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100900 if (user.iconPath != null) {
901 Bitmap icon = um.getUserIcon(user.id);
902 if (icon != null) {
903 return CircleFramedDrawable.getInstance(context, icon);
904 }
905 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000906 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
907 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100908 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700909
910 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000911 * Returns a label for the user, in the form of "User: user name" or "Work profile".
912 */
913 public static String getUserLabel(Context context, UserInfo info) {
914 if (info.isManagedProfile()) {
915 // We use predefined values for managed profiles
916 return context.getString(R.string.managed_user_title);
917 }
918 String name = info != null ? info.name : null;
919 if (name == null && info != null) {
920 name = Integer.toString(info.id);
921 } else if (info == null) {
922 name = context.getString(R.string.unknown);
923 }
924 return context.getResources().getString(R.string.running_process_item_user_label, name);
925 }
926
927 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700928 * Return whether or not the user should have a SIM Cards option in Settings.
929 * TODO: Change back to returning true if count is greater than one after testing.
930 * TODO: See bug 16533525.
931 */
932 public static boolean showSimCardTile(Context context) {
933 final TelephonyManager tm =
934 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
935
PauloftheWestdbd03822014-12-04 11:56:35 -0800936 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700937 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200938
939 /**
940 * Determine whether a package is a "system package", in which case certain things (like
941 * disabling notifications or disabling the package altogether) should be disallowed.
942 */
943 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
944 if (sSystemSignature == null) {
945 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
946 }
947 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
948 }
949
950 private static Signature[] sSystemSignature;
951
952 private static Signature getFirstSignature(PackageInfo pkg) {
953 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
954 return pkg.signatures[0];
955 }
956 return null;
957 }
958
959 private static Signature getSystemSignature(PackageManager pm) {
960 try {
961 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
962 return getFirstSignature(sys);
963 } catch (NameNotFoundException e) {
964 }
965 return null;
966 }
967
Elliott Hughes7253df32014-09-02 17:10:14 -0700968 /**
969 * Returns elapsed time for the given millis, in the following format:
970 * 2d 5h 40m 29s
971 * @param context the application context
972 * @param millis the elapsed time in milli seconds
973 * @param withSeconds include seconds?
974 * @return the formatted elapsed time
975 */
976 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
977 StringBuilder sb = new StringBuilder();
978 int seconds = (int) Math.floor(millis / 1000);
979 if (!withSeconds) {
980 // Round up.
981 seconds += 30;
982 }
983
984 int days = 0, hours = 0, minutes = 0;
985 if (seconds >= SECONDS_PER_DAY) {
986 days = seconds / SECONDS_PER_DAY;
987 seconds -= days * SECONDS_PER_DAY;
988 }
989 if (seconds >= SECONDS_PER_HOUR) {
990 hours = seconds / SECONDS_PER_HOUR;
991 seconds -= hours * SECONDS_PER_HOUR;
992 }
993 if (seconds >= SECONDS_PER_MINUTE) {
994 minutes = seconds / SECONDS_PER_MINUTE;
995 seconds -= minutes * SECONDS_PER_MINUTE;
996 }
997 if (withSeconds) {
998 if (days > 0) {
999 sb.append(context.getString(R.string.battery_history_days,
1000 days, hours, minutes, seconds));
1001 } else if (hours > 0) {
1002 sb.append(context.getString(R.string.battery_history_hours,
1003 hours, minutes, seconds));
1004 } else if (minutes > 0) {
1005 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1006 } else {
1007 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1008 }
1009 } else {
1010 if (days > 0) {
1011 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1012 days, hours, minutes));
1013 } else if (hours > 0) {
1014 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1015 hours, minutes));
1016 } else {
1017 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1018 }
1019 }
1020 return sb.toString();
1021 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001022
1023 /**
1024 * finds a record with subId.
1025 * Since the number of SIMs are few, an array is fine.
1026 */
Wink Saville0183fb52014-11-22 10:11:39 -08001027 public static SubscriptionInfo findRecordBySubId(Context context, final int subId) {
Wink Savilleca756612014-11-08 10:47:12 -08001028 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001029 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1030 if (subInfoList != null) {
1031 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001032
Wink Saville0183fb52014-11-22 10:11:39 -08001033 for (int i = 0; i < subInfoLength; ++i) {
1034 final SubscriptionInfo sir = subInfoList.get(i);
1035 if (sir != null && sir.getSubscriptionId() == subId) {
1036 return sir;
1037 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001038 }
1039 }
1040
1041 return null;
1042 }
1043
1044 /**
1045 * finds a record with slotId.
1046 * Since the number of SIMs are few, an array is fine.
1047 */
Wink Saville0183fb52014-11-22 10:11:39 -08001048 public static SubscriptionInfo findRecordBySlotId(Context context, final int slotId) {
Wink Savilleca756612014-11-08 10:47:12 -08001049 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001050 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1051 if (subInfoList != null) {
1052 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001053
Wink Saville0183fb52014-11-22 10:11:39 -08001054 for (int i = 0; i < subInfoLength; ++i) {
1055 final SubscriptionInfo sir = subInfoList.get(i);
1056 if (sir.getSimSlotIndex() == slotId) {
1057 //Right now we take the first subscription on a SIM.
1058 return sir;
1059 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001060 }
1061 }
1062
1063 return null;
1064 }
1065
Amith Yamasani45f86232014-11-19 17:12:46 -08001066 /**
1067 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1068 * @param userManager Instance of UserManager
1069 * @param checkUser The user to check the existence of.
1070 * @return UserInfo of the user or null for non-existent user.
1071 */
1072 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1073 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1074 final int checkUserId = checkUser.getIdentifier();
1075 for (UserInfo user : users) {
1076 if (user.id == checkUserId) {
1077 return user;
1078 }
1079 }
1080 return null;
1081 }
1082
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001083 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1084 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1085 com.android.internal.R.styleable.Preference,
1086 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1087 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1088 0);
1089 a.recycle();
1090 return inflater.inflate(resId, parent, false);
1091 }
1092
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001093 /**
1094 * Return if we are running low on storage space or not.
1095 *
1096 * @param context The context
1097 * @return true if we are running low on storage space
1098 */
1099 public static boolean isLowStorage(Context context) {
1100 final StorageManager sm = StorageManager.from(context);
1101 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1102 }
1103
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001104
1105 /**
1106 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1107 *
1108 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1109 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1110 */
1111 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1112 Bitmap bitmap = null;
1113 // Try finding the corresponding bitmap in the dark bitmap cache
1114 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1115 if (bitmap == null) {
1116 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1117 // Save it to cache
1118 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1119 }
1120 return bitmap;
1121 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001122}