blob: 4ddba80522bf9ac219834d1456dead2f929e3841 [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;
Sudheer Shankabc956302015-04-09 12:19:53 +010025import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070026import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070027import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010028import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010029import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080030import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070031import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070033import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080035import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080036import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010037import android.content.pm.IPackageManager;
Dan Sandlerb58b5122014-09-02 18:31:49 +020038import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080039import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070040import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070041import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020042import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070043import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020044import android.content.res.Resources;
45import android.content.res.Resources.NotFoundException;
Jason Monkb5aa73f2015-03-31 12:59:33 -040046import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070048import android.graphics.Bitmap;
49import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020050import android.graphics.drawable.Drawable;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080051import android.hardware.usb.IUsbManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080052import android.net.ConnectivityManager;
53import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070054import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070055import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020056import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010057import android.os.IBinder;
58import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070059import android.os.UserHandle;
60import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080061import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080062import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070063import android.preference.PreferenceFrameLayout;
64import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070065import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070066import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070067import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070068import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070069import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070070import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080071import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080072import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070073import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020074import android.text.TextUtils;
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 Gherghina7d748c02014-06-27 12:33:42 +010085
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010086import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050087import com.android.settings.UserAdapter.UserDetails;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080088import com.android.settings.applications.ApplicationsState;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070089import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010090import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070091
Amith Yamasaniae47ef42012-09-16 17:53:35 -070092import java.io.IOException;
93import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080094import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070095import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010096import java.util.ArrayList;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080097import java.util.Collections;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080098import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070099import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900100import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800101
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700102public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100103 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100104
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800105 /**
106 * Set the preference's title to the matching activity's label.
107 */
108 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
109
110 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900111 * The opacity level of a disabled icon.
112 */
113 public static final float DISABLED_ALPHA = 0.4f;
114
115 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700116 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
117 * 1 is most bad (red), the last value is least bad (green).
118 */
119 public static final int[] BADNESS_COLORS = new int[] {
120 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
121 0xfffabf2c, 0xff679e37, 0xff0a7f42
122 };
123
124 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200125 * Name of the meta-data item that should be set in the AndroidManifest.xml
126 * to specify the icon that should be displayed for the preference.
127 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500128 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200129
130 /**
131 * Name of the meta-data item that should be set in the AndroidManifest.xml
132 * to specify the title that should be displayed for the preference.
133 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500134 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200135
136 /**
137 * Name of the meta-data item that should be set in the AndroidManifest.xml
138 * to specify the summary text that should be displayed for the preference.
139 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500140 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200141
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100142 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
143
Elliott Hughes7253df32014-09-02 17:10:14 -0700144 private static final int SECONDS_PER_MINUTE = 60;
145 private static final int SECONDS_PER_HOUR = 60 * 60;
146 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
147
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000148 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
149
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200150 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800151 * Finds a matching activity for a preference's intent. If a matching
152 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800153 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 * @param context The context.
155 * @param parentPreferenceGroup The preference group that contains the
156 * preference whose intent is being resolved.
157 * @param preferenceKey The key of the preference whose intent is being
158 * resolved.
159 * @param flags 0 or one or more of
160 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
161 * .
162 * @return Whether an activity was found. If false, the preference was
163 * removed.
164 */
165 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
166 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800167
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800168 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
169 if (preference == null) {
170 return false;
171 }
Ying Wanga7188322010-01-04 18:45:10 -0800172
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 Intent intent = preference.getIntent();
174 if (intent != null) {
175 // Find the activity that is in the system image
176 PackageManager pm = context.getPackageManager();
177 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
178 int listSize = list.size();
179 for (int i = 0; i < listSize; i++) {
180 ResolveInfo resolveInfo = list.get(i);
181 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
182 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800183
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 // Replace the intent with this specific activity
185 preference.setIntent(new Intent().setClassName(
186 resolveInfo.activityInfo.packageName,
187 resolveInfo.activityInfo.name));
188
189 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
190 // Set the preference title to the activity's label
191 preference.setTitle(resolveInfo.loadLabel(pm));
192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800194 return true;
195 }
196 }
197 }
198
199 // Did not find a matching activity, so remove the preference
200 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800201
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900202 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800203 }
Ying Wanga7188322010-01-04 18:45:10 -0800204
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700205 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700206 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700207
208 Intent intent = tile.intent;
209 if (intent != null) {
210 // Find the activity that is in the system image
211 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500212 List<ResolveInfo> list = tile.userHandle.size() != 0
213 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
214 tile.userHandle.get(0).getIdentifier())
215 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700216 int listSize = list.size();
217 for (int i = 0; i < listSize; i++) {
218 ResolveInfo resolveInfo = list.get(i);
219 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
220 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500221 int icon = 0;
222 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700223 String summary = null;
224
225 // Get the activity's meta-data
226 try {
227 Resources res = pm.getResourcesForApplication(
228 resolveInfo.activityInfo.packageName);
229 Bundle metaData = resolveInfo.activityInfo.metaData;
230
231 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500232 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
233 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
234 }
235 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
236 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
237 }
238 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
239 summary = res.getString(
240 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
241 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700242 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500243 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700244 // Ignore
245 }
246
247 // Set the preference title to the activity's label if no
248 // meta-data is found
249 if (TextUtils.isEmpty(title)) {
250 title = resolveInfo.loadLabel(pm).toString();
251 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500252 if (icon == 0) {
253 icon = resolveInfo.activityInfo.icon;
254 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700255
256 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500257 tile.iconRes = icon;
258 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700259 tile.title = title;
260 tile.summary = summary;
261 // Replace the intent with this specific activity
262 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
263 resolveInfo.activityInfo.name);
264
265 return true;
266 }
267 }
268 }
269
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700270 return false;
271 }
272
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200273 /**
Ying Wanga7188322010-01-04 18:45:10 -0800274 * Returns true if Monkey is running.
275 */
276 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700277 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800278 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700279
280 /**
281 * Returns whether the device is voice-capable (meaning, it is also a phone).
282 */
283 public static boolean isVoiceCapable(Context context) {
284 TelephonyManager telephony =
285 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
286 return telephony != null && telephony.isVoiceCapable();
287 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800288
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700289 public static boolean isWifiOnly(Context context) {
290 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
291 Context.CONNECTIVITY_SERVICE);
292 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800293 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800294
295 /**
296 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
297 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900298 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800299 */
300 public static String getWifiIpAddresses(Context context) {
301 ConnectivityManager cm = (ConnectivityManager)
302 context.getSystemService(Context.CONNECTIVITY_SERVICE);
303 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700304 return formatIpAddresses(prop);
305 }
306
307 /**
308 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
309 * addresses.
310 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900311 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700312 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900313 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700314 LinkProperties prop = cm.getActiveLinkProperties();
315 return formatIpAddresses(prop);
316 }
317
318 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800319 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900320 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800321 // If there are no entries, return null
322 if (!iter.hasNext()) return null;
323 // Concatenate all available addresses, comma separated
324 String addresses = "";
325 while (iter.hasNext()) {
326 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900327 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800328 }
329 return addresses;
330 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900331
332 public static Locale createLocaleFromString(String localeStr) {
333 // TODO: is there a better way to actually construct a locale that will match?
334 // The main problem is, on top of Java specs, locale.toString() and
335 // new Locale(locale.toString()).toString() do not return equal() strings in
336 // many cases, because the constructor takes the only string as the language
337 // code. So : new Locale("en", "US").toString() => "en_US"
338 // And : new Locale("en_US").toString() => "en_us"
339 if (null == localeStr)
340 return Locale.getDefault();
341 String[] brokenDownLocale = localeStr.split("_", 3);
342 // split may not return a 0-length array.
343 if (1 == brokenDownLocale.length) {
344 return new Locale(brokenDownLocale[0]);
345 } else if (2 == brokenDownLocale.length) {
346 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
347 } else {
348 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
349 }
350 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700351
Elliott Hughes7253df32014-09-02 17:10:14 -0700352 /** Formats the ratio of amount/total as a percentage. */
353 public static String formatPercentage(long amount, long total) {
354 return formatPercentage(((double) amount) / total);
355 }
356
357 /** Formats an integer from 0..100 as a percentage. */
358 public static String formatPercentage(int percentage) {
359 return formatPercentage(((double) percentage) / 100.0);
360 }
361
362 /** Formats a double from 0.0..1.0 as a percentage. */
363 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700364 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700365 }
366
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900367 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
368 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
369 }
370
Amith Yamasania4379d62011-07-22 10:34:58 -0700371 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700372 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700373 }
374
375 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900376 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
377 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700378 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700379 }
380
381 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
382 final Intent intent = batteryChangedIntent;
383
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900384 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
385 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
386 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700387 String statusString;
388 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700389 int resId;
390 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
391 resId = R.string.battery_info_status_charging_ac;
392 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
393 resId = R.string.battery_info_status_charging_usb;
394 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
395 resId = R.string.battery_info_status_charging_wireless;
396 } else {
397 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700398 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700399 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700400 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
401 statusString = res.getString(R.string.battery_info_status_discharging);
402 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
403 statusString = res.getString(R.string.battery_info_status_not_charging);
404 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
405 statusString = res.getString(R.string.battery_info_status_full);
406 } else {
407 statusString = res.getString(R.string.battery_info_status_unknown);
408 }
409
410 return statusString;
411 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700412
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800413 public static void forcePrepareCustomPreferencesList(
414 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
415 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
416 list.setClipToPadding(false);
417 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
418 }
419
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700420 /**
421 * Prepare a custom preferences layout, moving padding to {@link ListView}
422 * when outside scrollbars are requested. Usually used to display
423 * {@link ListView} and {@link TabWidget} with correct padding.
424 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700425 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800426 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700427 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700428 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700429 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700430 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700431 final int paddingBottom = res.getDimensionPixelSize(
432 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700433
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700434 if (parent instanceof PreferenceFrameLayout) {
435 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
436
437 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
438 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
439 } else {
440 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
441 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700442 }
443 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700444
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700445 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700446 final Resources res = view.getResources();
447 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700448
449 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
450 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700451 final int paddingBottom = res.getDimensionPixelSize(
452 com.android.internal.R.dimen.preference_fragment_padding_bottom);
453
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700454 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700455 }
456
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700457 /**
458 * Return string resource that best describes combination of tethering
459 * options available on this device.
460 */
461 public static int getTetheringLabel(ConnectivityManager cm) {
462 String[] usbRegexs = cm.getTetherableUsbRegexs();
463 String[] wifiRegexs = cm.getTetherableWifiRegexs();
464 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
465
466 boolean usbAvailable = usbRegexs.length != 0;
467 boolean wifiAvailable = wifiRegexs.length != 0;
468 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
469
470 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
471 return R.string.tether_settings_title_all;
472 } else if (wifiAvailable && usbAvailable) {
473 return R.string.tether_settings_title_all;
474 } else if (wifiAvailable && bluetoothAvailable) {
475 return R.string.tether_settings_title_all;
476 } else if (wifiAvailable) {
477 return R.string.tether_settings_title_wifi;
478 } else if (usbAvailable && bluetoothAvailable) {
479 return R.string.tether_settings_title_usb_bluetooth;
480 } else if (usbAvailable) {
481 return R.string.tether_settings_title_usb;
482 } else {
483 return R.string.tether_settings_title_bluetooth;
484 }
485 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700486
487 /* Used by UserSettings as well. Call this on a non-ui thread. */
488 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
489 Uri contactUri = Profile.CONTENT_URI;
490
491 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
492 context.getContentResolver(),
493 contactUri, true);
494 // If there's no profile photo, assign a default avatar
495 if (avatarDataStream == null) {
496 return false;
497 }
498 int userId = user != null ? user.id : UserHandle.myUserId();
499 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700500 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
501 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700502 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700503 avatarDataStream.close();
504 } catch (IOException ioe) { }
505 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700506 }
507
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700508 public static String getMeProfileName(Context context, boolean full) {
509 if (full) {
510 return getProfileDisplayName(context);
511 } else {
512 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700513 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700514 }
515
516 private static String getShorterNameIfPossible(Context context) {
517 final String given = getLocalProfileGivenName(context);
518 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
519 }
520
521 private static String getLocalProfileGivenName(Context context) {
522 final ContentResolver cr = context.getContentResolver();
523
524 // Find the raw contact ID for the local ME profile raw contact.
525 final long localRowProfileId;
526 final Cursor localRawProfile = cr.query(
527 Profile.CONTENT_RAW_CONTACTS_URI,
528 new String[] {RawContacts._ID},
529 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
530 RawContacts.ACCOUNT_NAME + " IS NULL",
531 null, null);
532 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700533
534 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700535 if (!localRawProfile.moveToFirst()) {
536 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700537 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700538 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700539 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700540 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700541 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700542
543 // Find the structured name for the raw contact.
544 final Cursor structuredName = cr.query(
545 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
546 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
547 CommonDataKinds.StructuredName.FAMILY_NAME},
548 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
549 null, null);
550 if (structuredName == null) return null;
551
552 try {
553 if (!structuredName.moveToFirst()) {
554 return null;
555 }
556 String partialName = structuredName.getString(0);
557 if (TextUtils.isEmpty(partialName)) {
558 partialName = structuredName.getString(1);
559 }
560 return partialName;
561 } finally {
562 structuredName.close();
563 }
564 }
565
566 private static final String getProfileDisplayName(Context context) {
567 final ContentResolver cr = context.getContentResolver();
568 final Cursor profile = cr.query(Profile.CONTENT_URI,
569 new String[] {Profile.DISPLAY_NAME}, null, null, null);
570 if (profile == null) return null;
571
572 try {
573 if (!profile.moveToFirst()) {
574 return null;
575 }
576 return profile.getString(0);
577 } finally {
578 profile.close();
579 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700580 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700581
582 /** Not global warming, it's global change warning. */
583 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
584 final Runnable positiveAction) {
585 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
586 builder.setTitle(titleResId);
587 builder.setMessage(R.string.global_change_warning);
588 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
589 @Override
590 public void onClick(DialogInterface dialog, int which) {
591 positiveAction.run();
592 }
593 });
594 builder.setNegativeButton(android.R.string.cancel, null);
595
596 return builder.create();
597 }
598
599 public static boolean hasMultipleUsers(Context context) {
600 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
601 .getUsers().size() > 1;
602 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700603
604 /**
605 * Start a new instance of the activity, showing only the given fragment.
606 * When launched in this mode, the given preference fragment will be instantiated and fill the
607 * entire activity.
608 *
609 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000610 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700611 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700612 * @param resultTo Option fragment that should receive the result of the activity launch.
613 * @param resultRequestCode If resultTo is non-null, this is the request code in which
614 * to report the result.
615 * @param titleResId resource id for the String to display for the title of this set
616 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700617 * @param title String to display for the title of this set of preferences.
618 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000619 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100620 Fragment resultTo, int resultRequestCode, int titleResId,
621 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700622 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100623 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
624 }
625
626 /**
627 * Start a new instance of the activity, showing only the given fragment.
628 * When launched in this mode, the given preference fragment will be instantiated and fill the
629 * entire activity.
630 *
631 * @param context The context.
632 * @param fragmentName The name of the fragment to display.
633 * @param args Optional arguments to supply to the fragment.
634 * @param resultTo Option fragment that should receive the result of the activity launch.
635 * @param resultRequestCode If resultTo is non-null, this is the request code in which
636 * to report the result.
637 * @param titleResPackageName Optional package name for the resource id of the title.
638 * @param titleResId resource id for the String to display for the title of this set
639 * of preferences.
640 * @param title String to display for the title of this set of preferences.
641 */
642 public static void startWithFragment(Context context, String fragmentName, Bundle args,
643 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
644 CharSequence title) {
645 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
646 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700647 }
648
649 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100650 Fragment resultTo, int resultRequestCode, int titleResId,
651 CharSequence title, boolean isShortcut) {
652 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
653 null /* titleResPackageName */, titleResId, title, isShortcut);
654 if (resultTo == null) {
655 context.startActivity(intent);
656 } else {
657 resultTo.startActivityForResult(intent, resultRequestCode);
658 }
659 }
660
661 public static void startWithFragment(Context context, String fragmentName, Bundle args,
662 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
663 CharSequence title, boolean isShortcut) {
664 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
665 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700666 if (resultTo == null) {
667 context.startActivity(intent);
668 } else {
669 resultTo.startActivityForResult(intent, resultRequestCode);
670 }
671 }
672
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100673 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100674 int titleResId, CharSequence title, boolean isShortcut,
675 UserHandle userHandle) {
676 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
677 null /* titleResPackageName */, titleResId, title, isShortcut);
678 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
679 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
680 context.startActivityAsUser(intent, userHandle);
681 }
682
683 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
684 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
685 UserHandle userHandle) {
686 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
687 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100688 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
689 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100690 context.startActivityAsUser(intent, userHandle);
691 }
692
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700693 /**
694 * Build an Intent to launch a new activity showing the selected fragment.
695 * The implementation constructs an Intent that re-launches the current activity with the
696 * appropriate arguments to display the fragment.
697 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700698 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700699 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000700 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700701 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100702 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700703 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700704 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700705 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700706 * @return Returns an Intent that can be launched to display the given
707 * fragment.
708 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000709 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100710 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
711 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700712 Intent intent = new Intent(Intent.ACTION_MAIN);
713 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000714 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700715 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100716 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
717 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700718 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700719 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700720 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700721 return intent;
722 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100723
724 /**
725 * Returns the managed profile of the current user or null if none found.
726 */
727 public static UserHandle getManagedProfile(UserManager userManager) {
728 List<UserHandle> userProfiles = userManager.getUserProfiles();
729 final int count = userProfiles.size();
730 for (int i = 0; i < count; i++) {
731 final UserHandle profile = userProfiles.get(i);
732 if (profile.getIdentifier() == userManager.getUserHandle()) {
733 continue;
734 }
735 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
736 if (userInfo.isManagedProfile()) {
737 return profile;
738 }
739 }
740 return null;
741 }
742
743 /**
744 * Returns true if the current profile is a managed one.
745 */
746 public static boolean isManagedProfile(UserManager userManager) {
747 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
748 return currentUser.isManagedProfile();
749 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100750
751 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500752 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100753 *
754 * <p> The adapter can be used to populate a spinner that switches between the Settings
755 * app on the different profiles.
756 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500757 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100758 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500759 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100760 Context context) {
761 List<UserHandle> userProfiles = userManager.getUserProfiles();
762 if (userProfiles.size() < 2) {
763 return null;
764 }
765
766 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
767 // The first option should be the current profile
768 userProfiles.remove(myUserHandle);
769 userProfiles.add(0, myUserHandle);
770
Jason Monk2ebc8a02015-02-13 15:23:19 -0500771 return createUserAdapter(userManager, context, userProfiles);
772 }
773
774 public static UserAdapter createUserAdapter(UserManager userManager,
775 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100776 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
777 final int count = userProfiles.size();
778 for (int i = 0; i < count; i++) {
779 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
780 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500781 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100782 }
783
784 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100785 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100786 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100787 * The target user can be either the current user, the user that launched this activity or
788 * the user contained as an extra in the arguments or intent extras.
789 *
790 * Note: This is secure in the sense that it only returns a target user different to the current
791 * one if the app launching this activity is the Settings app itself, running in the same user
792 * 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 +0100793 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100794 public static UserHandle getSecureTargetUser(IBinder activityToken,
795 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
796 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
797 IActivityManager am = ActivityManagerNative.getDefault();
798 try {
799 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
800 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
801
802 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
803 am.getLaunchedFromUid(activityToken)));
804 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
805 // Check it's secure
806 if (isProfileOf(um, launchedFromUser)) {
807 return launchedFromUser;
808 }
809 }
810 UserHandle extrasUser = intentExtras != null
811 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
812 if (extrasUser != null && !extrasUser.equals(currentUser)) {
813 // Check it's secure
814 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
815 return extrasUser;
816 }
817 }
818 UserHandle argumentsUser = arguments != null
819 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
820 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
821 // Check it's secure
822 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
823 return argumentsUser;
824 }
825 }
826 } catch (RemoteException e) {
827 // Should not happen
828 Log.v(TAG, "Could not talk to activity manager.", e);
829 }
830 return currentUser;
831 }
832
833 /**
834 * Returns the target user for a Settings activity.
835 *
836 * The target user can be either the current user, the user that launched this activity or
837 * the user contained as an extra in the arguments or intent extras.
838 *
839 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
840 * possible.
841 *
842 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
843 */
844 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
845 @Nullable Bundle intentExtras) {
846 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
847 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100848 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100849 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
850 am.getLaunchedFromUid(activityToken)));
851 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
852 return launchedFromUser;
853 }
854 UserHandle extrasUser = intentExtras != null
855 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
856 if (extrasUser != null && !extrasUser.equals(currentUser)) {
857 return extrasUser;
858 }
859 UserHandle argumentsUser = arguments != null
860 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
861 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
862 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100863 }
864 } catch (RemoteException e) {
865 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100866 Log.v(TAG, "Could not talk to activity manager.", e);
867 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100868 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100869 return currentUser;
870 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100871
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100872 /**
873 * Returns true if the user provided is in the same profiles group as the current user.
874 */
875 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
876 if (um == null || otherUser == null) return false;
877 return (UserHandle.myUserId() == otherUser.getIdentifier())
878 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100879 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530880
Andres Moralesce249fe2014-07-07 16:58:16 -0700881
882 /**
883 * Returns whether or not this device is able to be OEM unlocked.
884 */
885 static boolean isOemUnlockEnabled(Context context) {
886 PersistentDataBlockManager manager =(PersistentDataBlockManager)
887 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
888 return manager.getOemUnlockEnabled();
889 }
890
891 /**
892 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
893 * devices allow users to flash other OSes to them.
894 */
895 static void setOemUnlockEnabled(Context context, boolean enabled) {
896 PersistentDataBlockManager manager =(PersistentDataBlockManager)
897 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
898 manager.setOemUnlockEnabled(enabled);
899 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100900
901 /**
902 * Returns a circular icon for a user.
903 */
904 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000905 if (user.isManagedProfile()) {
906 // We use predefined values for managed profiles
907 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
908 com.android.internal.R.drawable.ic_corp_icon);
909 return CircleFramedDrawable.getInstance(context, b);
910 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100911 if (user.iconPath != null) {
912 Bitmap icon = um.getUserIcon(user.id);
913 if (icon != null) {
914 return CircleFramedDrawable.getInstance(context, icon);
915 }
916 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000917 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
918 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100919 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700920
921 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000922 * Returns a label for the user, in the form of "User: user name" or "Work profile".
923 */
924 public static String getUserLabel(Context context, UserInfo info) {
925 if (info.isManagedProfile()) {
926 // We use predefined values for managed profiles
927 return context.getString(R.string.managed_user_title);
928 }
929 String name = info != null ? info.name : null;
930 if (name == null && info != null) {
931 name = Integer.toString(info.id);
932 } else if (info == null) {
933 name = context.getString(R.string.unknown);
934 }
935 return context.getResources().getString(R.string.running_process_item_user_label, name);
936 }
937
938 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700939 * Return whether or not the user should have a SIM Cards option in Settings.
940 * TODO: Change back to returning true if count is greater than one after testing.
941 * TODO: See bug 16533525.
942 */
943 public static boolean showSimCardTile(Context context) {
944 final TelephonyManager tm =
945 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
946
PauloftheWestdbd03822014-12-04 11:56:35 -0800947 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700948 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200949
950 /**
951 * Determine whether a package is a "system package", in which case certain things (like
952 * disabling notifications or disabling the package altogether) should be disallowed.
953 */
954 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
955 if (sSystemSignature == null) {
956 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
957 }
958 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
959 }
960
961 private static Signature[] sSystemSignature;
962
963 private static Signature getFirstSignature(PackageInfo pkg) {
964 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
965 return pkg.signatures[0];
966 }
967 return null;
968 }
969
970 private static Signature getSystemSignature(PackageManager pm) {
971 try {
972 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
973 return getFirstSignature(sys);
974 } catch (NameNotFoundException e) {
975 }
976 return null;
977 }
978
Elliott Hughes7253df32014-09-02 17:10:14 -0700979 /**
980 * Returns elapsed time for the given millis, in the following format:
981 * 2d 5h 40m 29s
982 * @param context the application context
983 * @param millis the elapsed time in milli seconds
984 * @param withSeconds include seconds?
985 * @return the formatted elapsed time
986 */
987 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
988 StringBuilder sb = new StringBuilder();
989 int seconds = (int) Math.floor(millis / 1000);
990 if (!withSeconds) {
991 // Round up.
992 seconds += 30;
993 }
994
995 int days = 0, hours = 0, minutes = 0;
996 if (seconds >= SECONDS_PER_DAY) {
997 days = seconds / SECONDS_PER_DAY;
998 seconds -= days * SECONDS_PER_DAY;
999 }
1000 if (seconds >= SECONDS_PER_HOUR) {
1001 hours = seconds / SECONDS_PER_HOUR;
1002 seconds -= hours * SECONDS_PER_HOUR;
1003 }
1004 if (seconds >= SECONDS_PER_MINUTE) {
1005 minutes = seconds / SECONDS_PER_MINUTE;
1006 seconds -= minutes * SECONDS_PER_MINUTE;
1007 }
1008 if (withSeconds) {
1009 if (days > 0) {
1010 sb.append(context.getString(R.string.battery_history_days,
1011 days, hours, minutes, seconds));
1012 } else if (hours > 0) {
1013 sb.append(context.getString(R.string.battery_history_hours,
1014 hours, minutes, seconds));
1015 } else if (minutes > 0) {
1016 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1017 } else {
1018 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1019 }
1020 } else {
1021 if (days > 0) {
1022 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1023 days, hours, minutes));
1024 } else if (hours > 0) {
1025 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1026 hours, minutes));
1027 } else {
1028 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1029 }
1030 }
1031 return sb.toString();
1032 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001033
1034 /**
Amith Yamasani45f86232014-11-19 17:12:46 -08001035 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1036 * @param userManager Instance of UserManager
1037 * @param checkUser The user to check the existence of.
1038 * @return UserInfo of the user or null for non-existent user.
1039 */
1040 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1041 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1042 final int checkUserId = checkUser.getIdentifier();
1043 for (UserInfo user : users) {
1044 if (user.id == checkUserId) {
1045 return user;
1046 }
1047 }
1048 return null;
1049 }
1050
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001051 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1052 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1053 com.android.internal.R.styleable.Preference,
1054 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1055 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1056 0);
1057 a.recycle();
1058 return inflater.inflate(resId, parent, false);
1059 }
1060
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001061 /**
1062 * Return if we are running low on storage space or not.
1063 *
1064 * @param context The context
1065 * @return true if we are running low on storage space
1066 */
1067 public static boolean isLowStorage(Context context) {
1068 final StorageManager sm = StorageManager.from(context);
1069 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1070 }
1071
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001072 /**
1073 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1074 *
1075 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1076 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1077 */
1078 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1079 Bitmap bitmap = null;
1080 // Try finding the corresponding bitmap in the dark bitmap cache
1081 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1082 if (bitmap == null) {
1083 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1084 // Save it to cache
1085 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1086 }
1087 return bitmap;
1088 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001089
1090 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1091 try {
1092 if (usbManager != null) {
1093 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1094 }
1095 } catch (RemoteException e) {
1096 Log.e(TAG, "mUsbManager.hasDefaults", e);
1097 }
1098 return false;
1099 }
1100
1101 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1102 // Get list of preferred activities
1103 List<ComponentName> prefActList = new ArrayList<>();
1104 // Intent list cannot be null. so pass empty list
1105 List<IntentFilter> intentList = new ArrayList<>();
1106 pm.getPreferredActivities(intentList, prefActList, packageName);
1107 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1108 return prefActList.size() > 0;
1109 }
1110
1111 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1112 IUsbManager usbManager, PackageManager pm, Context context) {
1113 String packageName = appEntry.info.packageName;
1114 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1115 || hasUsbDefaults(usbManager, packageName);
1116 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
1117 boolean hasDomainURLsPreference =
1118 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
1119 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
1120 return context.getString(hasPreferred || hasDomainURLsPreference
1121 ? R.string.launch_defaults_some
1122 : R.string.launch_defaults_none);
1123 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001124
1125 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1126 boolean animate) {
1127 setViewShown(loading, !done, animate);
1128 setViewShown(doneLoading, done, animate);
1129 }
1130
1131 private static void setViewShown(final View view, boolean shown, boolean animate) {
1132 if (animate) {
1133 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1134 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1135 if (shown) {
1136 view.setVisibility(View.VISIBLE);
1137 } else {
1138 animation.setAnimationListener(new AnimationListener() {
1139 @Override
1140 public void onAnimationStart(Animation animation) {
1141 }
1142
1143 @Override
1144 public void onAnimationRepeat(Animation animation) {
1145 }
1146
1147 @Override
1148 public void onAnimationEnd(Animation animation) {
1149 view.setVisibility(View.INVISIBLE);
1150 }
1151 });
1152 }
1153 view.startAnimation(animation);
1154 } else {
1155 view.clearAnimation();
1156 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1157 }
1158 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001159
1160 /**
1161 * Returns the application info of the currently installed MDM package.
1162 */
1163 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1164 DevicePolicyManager dpm =
1165 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1166 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1167 if (mdmPackage == null) {
1168 return null;
1169 }
1170 String mdmPackageName = mdmPackage.getPackageName();
1171 try {
1172 IPackageManager ipm = AppGlobals.getPackageManager();
1173 ApplicationInfo mdmApplicationInfo =
1174 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1175 return mdmApplicationInfo;
1176 } catch (RemoteException e) {
1177 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1178 + ", userId " + profileId, e);
1179 return null;
1180 }
1181 }
1182}