blob: 0a5853fce5f4866e327f2a1b70b974280e840ae4 [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070020import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010021import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070022import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010023import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070025import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010026import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010027import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080028import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070029import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080030import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070031import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080033import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010035import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070036import android.content.pm.IntentFilterVerificationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070039import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070040import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020041import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.content.res.Resources;
44import android.content.res.Resources.NotFoundException;
Jason Monkb5aa73f2015-03-31 12:59:33 -040045import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070046import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070047import android.graphics.Bitmap;
48import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020049import android.graphics.drawable.Drawable;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080050import android.hardware.usb.IUsbManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080051import android.net.ConnectivityManager;
52import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070053import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070054import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020055import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010056import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040057import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010058import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040059import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070060import android.os.UserHandle;
61import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080062import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080063import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070064import android.preference.PreferenceFrameLayout;
65import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070066import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070067import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070068import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070069import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070070import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070071import android.service.persistentdata.PersistentDataBlockManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070072import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020073import android.text.TextUtils;
Christopher Tatea08a2252015-07-01 16:52:43 -070074import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010075import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000076import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000077import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070078import android.view.View;
79import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040080import android.view.animation.Animation;
81import android.view.animation.Animation.AnimationListener;
82import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070083import android.widget.ListView;
84import android.widget.TabWidget;
Alexandra 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 Meglio63bbb8e2014-04-23 16:44:30 -070088import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010089import com.android.settings.drawable.CircleFramedDrawable;
Tony Mantler67cd6ab2015-06-08 14:41:02 -070090import com.android.settingslib.applications.ApplicationsState;
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;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080097import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070098import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090099import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800100
Tony Mantler67cd6ab2015-06-08 14:41:02 -0700101import static android.content.Intent.EXTRA_USER;
102
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700103public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100104 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100105
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800106 /**
107 * Set the preference's title to the matching activity's label.
108 */
109 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
110
111 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900112 * The opacity level of a disabled icon.
113 */
114 public static final float DISABLED_ALPHA = 0.4f;
115
116 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700117 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
118 * 1 is most bad (red), the last value is least bad (green).
119 */
120 public static final int[] BADNESS_COLORS = new int[] {
121 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
122 0xfffabf2c, 0xff679e37, 0xff0a7f42
123 };
124
125 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200126 * Name of the meta-data item that should be set in the AndroidManifest.xml
127 * to specify the icon that should be displayed for the preference.
128 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500129 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200130
131 /**
132 * Name of the meta-data item that should be set in the AndroidManifest.xml
133 * to specify the title that should be displayed for the preference.
134 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500135 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200136
137 /**
138 * Name of the meta-data item that should be set in the AndroidManifest.xml
139 * to specify the summary text that should be displayed for the preference.
140 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500141 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200142
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100143 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
144
Elliott Hughes7253df32014-09-02 17:10:14 -0700145 private static final int SECONDS_PER_MINUTE = 60;
146 private static final int SECONDS_PER_HOUR = 60 * 60;
147 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
148
Jason Monkbeb171d2015-05-21 15:24:37 -0400149 public static final String OS_PKG = "os";
150
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000151 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
152
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200153 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 * Finds a matching activity for a preference's intent. If a matching
155 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800156 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800157 * @param context The context.
158 * @param parentPreferenceGroup The preference group that contains the
159 * preference whose intent is being resolved.
160 * @param preferenceKey The key of the preference whose intent is being
161 * resolved.
162 * @param flags 0 or one or more of
163 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
164 * .
165 * @return Whether an activity was found. If false, the preference was
166 * removed.
167 */
168 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
169 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800170
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800171 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
172 if (preference == null) {
173 return false;
174 }
Ying Wanga7188322010-01-04 18:45:10 -0800175
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800176 Intent intent = preference.getIntent();
177 if (intent != null) {
178 // Find the activity that is in the system image
179 PackageManager pm = context.getPackageManager();
180 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
181 int listSize = list.size();
182 for (int i = 0; i < listSize; i++) {
183 ResolveInfo resolveInfo = list.get(i);
184 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
185 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800186
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800187 // Replace the intent with this specific activity
188 preference.setIntent(new Intent().setClassName(
189 resolveInfo.activityInfo.packageName,
190 resolveInfo.activityInfo.name));
191
192 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
193 // Set the preference title to the activity's label
194 preference.setTitle(resolveInfo.loadLabel(pm));
195 }
Ying Wanga7188322010-01-04 18:45:10 -0800196
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800197 return true;
198 }
199 }
200 }
201
202 // Did not find a matching activity, so remove the preference
203 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800204
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900205 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800206 }
Ying Wanga7188322010-01-04 18:45:10 -0800207
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700208 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700209 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700210
211 Intent intent = tile.intent;
212 if (intent != null) {
213 // Find the activity that is in the system image
214 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500215 List<ResolveInfo> list = tile.userHandle.size() != 0
216 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
217 tile.userHandle.get(0).getIdentifier())
218 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700219 int listSize = list.size();
220 for (int i = 0; i < listSize; i++) {
221 ResolveInfo resolveInfo = list.get(i);
222 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
223 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500224 int icon = 0;
225 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700226 String summary = null;
227
228 // Get the activity's meta-data
229 try {
230 Resources res = pm.getResourcesForApplication(
231 resolveInfo.activityInfo.packageName);
232 Bundle metaData = resolveInfo.activityInfo.metaData;
233
234 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500235 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
236 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
237 }
238 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
239 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
240 }
241 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
242 summary = res.getString(
243 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
244 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700245 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500246 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700247 // Ignore
248 }
249
250 // Set the preference title to the activity's label if no
251 // meta-data is found
252 if (TextUtils.isEmpty(title)) {
253 title = resolveInfo.loadLabel(pm).toString();
254 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500255 if (icon == 0) {
256 icon = resolveInfo.activityInfo.icon;
257 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700258
259 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500260 tile.iconRes = icon;
261 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700262 tile.title = title;
263 tile.summary = summary;
264 // Replace the intent with this specific activity
265 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
266 resolveInfo.activityInfo.name);
267
268 return true;
269 }
270 }
271 }
272
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700273 return false;
274 }
275
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200276 /**
Ying Wanga7188322010-01-04 18:45:10 -0800277 * Returns true if Monkey is running.
278 */
279 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700280 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800281 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700282
283 /**
284 * Returns whether the device is voice-capable (meaning, it is also a phone).
285 */
286 public static boolean isVoiceCapable(Context context) {
287 TelephonyManager telephony =
288 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
289 return telephony != null && telephony.isVoiceCapable();
290 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800291
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700292 public static boolean isWifiOnly(Context context) {
293 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
294 Context.CONNECTIVITY_SERVICE);
295 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800296 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800297
298 /**
299 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
300 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900301 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800302 */
303 public static String getWifiIpAddresses(Context context) {
304 ConnectivityManager cm = (ConnectivityManager)
305 context.getSystemService(Context.CONNECTIVITY_SERVICE);
306 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700307 return formatIpAddresses(prop);
308 }
309
310 /**
311 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
312 * addresses.
313 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900314 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700315 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900316 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700317 LinkProperties prop = cm.getActiveLinkProperties();
318 return formatIpAddresses(prop);
319 }
320
321 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800322 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900323 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800324 // If there are no entries, return null
325 if (!iter.hasNext()) return null;
326 // Concatenate all available addresses, comma separated
327 String addresses = "";
328 while (iter.hasNext()) {
329 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900330 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800331 }
332 return addresses;
333 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900334
335 public static Locale createLocaleFromString(String localeStr) {
336 // TODO: is there a better way to actually construct a locale that will match?
337 // The main problem is, on top of Java specs, locale.toString() and
338 // new Locale(locale.toString()).toString() do not return equal() strings in
339 // many cases, because the constructor takes the only string as the language
340 // code. So : new Locale("en", "US").toString() => "en_US"
341 // And : new Locale("en_US").toString() => "en_us"
342 if (null == localeStr)
343 return Locale.getDefault();
344 String[] brokenDownLocale = localeStr.split("_", 3);
345 // split may not return a 0-length array.
346 if (1 == brokenDownLocale.length) {
347 return new Locale(brokenDownLocale[0]);
348 } else if (2 == brokenDownLocale.length) {
349 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
350 } else {
351 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
352 }
353 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700354
Elliott Hughes7253df32014-09-02 17:10:14 -0700355 /** Formats the ratio of amount/total as a percentage. */
356 public static String formatPercentage(long amount, long total) {
357 return formatPercentage(((double) amount) / total);
358 }
359
360 /** Formats an integer from 0..100 as a percentage. */
361 public static String formatPercentage(int percentage) {
362 return formatPercentage(((double) percentage) / 100.0);
363 }
364
365 /** Formats a double from 0.0..1.0 as a percentage. */
366 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700367 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700368 }
369
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900370 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
371 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
372 }
373
Amith Yamasania4379d62011-07-22 10:34:58 -0700374 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700375 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700376 }
377
378 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900379 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
380 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700381 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700382 }
383
384 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
385 final Intent intent = batteryChangedIntent;
386
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900387 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
388 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
389 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700390 String statusString;
391 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700392 int resId;
393 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
394 resId = R.string.battery_info_status_charging_ac;
395 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
396 resId = R.string.battery_info_status_charging_usb;
397 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
398 resId = R.string.battery_info_status_charging_wireless;
399 } else {
400 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700401 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700402 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700403 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
404 statusString = res.getString(R.string.battery_info_status_discharging);
405 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
406 statusString = res.getString(R.string.battery_info_status_not_charging);
407 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
408 statusString = res.getString(R.string.battery_info_status_full);
409 } else {
410 statusString = res.getString(R.string.battery_info_status_unknown);
411 }
412
413 return statusString;
414 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700415
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800416 public static void forcePrepareCustomPreferencesList(
417 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
418 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
419 list.setClipToPadding(false);
420 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
421 }
422
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700423 /**
424 * Prepare a custom preferences layout, moving padding to {@link ListView}
425 * when outside scrollbars are requested. Usually used to display
426 * {@link ListView} and {@link TabWidget} with correct padding.
427 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700428 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800429 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700430 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700431 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700432 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700433 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700434 final int paddingBottom = res.getDimensionPixelSize(
435 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700436
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700437 if (parent instanceof PreferenceFrameLayout) {
438 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
439
440 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
441 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
442 } else {
443 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
444 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700445 }
446 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700447
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700448 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700449 final Resources res = view.getResources();
450 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700451
452 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
453 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700454 final int paddingBottom = res.getDimensionPixelSize(
455 com.android.internal.R.dimen.preference_fragment_padding_bottom);
456
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700457 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700458 }
459
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700460 /**
461 * Return string resource that best describes combination of tethering
462 * options available on this device.
463 */
464 public static int getTetheringLabel(ConnectivityManager cm) {
465 String[] usbRegexs = cm.getTetherableUsbRegexs();
466 String[] wifiRegexs = cm.getTetherableWifiRegexs();
467 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
468
469 boolean usbAvailable = usbRegexs.length != 0;
470 boolean wifiAvailable = wifiRegexs.length != 0;
471 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
472
473 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
474 return R.string.tether_settings_title_all;
475 } else if (wifiAvailable && usbAvailable) {
476 return R.string.tether_settings_title_all;
477 } else if (wifiAvailable && bluetoothAvailable) {
478 return R.string.tether_settings_title_all;
479 } else if (wifiAvailable) {
480 return R.string.tether_settings_title_wifi;
481 } else if (usbAvailable && bluetoothAvailable) {
482 return R.string.tether_settings_title_usb_bluetooth;
483 } else if (usbAvailable) {
484 return R.string.tether_settings_title_usb;
485 } else {
486 return R.string.tether_settings_title_bluetooth;
487 }
488 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700489
490 /* Used by UserSettings as well. Call this on a non-ui thread. */
491 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
492 Uri contactUri = Profile.CONTENT_URI;
493
494 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
495 context.getContentResolver(),
496 contactUri, true);
497 // If there's no profile photo, assign a default avatar
498 if (avatarDataStream == null) {
499 return false;
500 }
501 int userId = user != null ? user.id : UserHandle.myUserId();
502 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700503 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
504 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700505 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700506 avatarDataStream.close();
507 } catch (IOException ioe) { }
508 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700509 }
510
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700511 public static String getMeProfileName(Context context, boolean full) {
512 if (full) {
513 return getProfileDisplayName(context);
514 } else {
515 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700516 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700517 }
518
519 private static String getShorterNameIfPossible(Context context) {
520 final String given = getLocalProfileGivenName(context);
521 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
522 }
523
524 private static String getLocalProfileGivenName(Context context) {
525 final ContentResolver cr = context.getContentResolver();
526
527 // Find the raw contact ID for the local ME profile raw contact.
528 final long localRowProfileId;
529 final Cursor localRawProfile = cr.query(
530 Profile.CONTENT_RAW_CONTACTS_URI,
531 new String[] {RawContacts._ID},
532 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
533 RawContacts.ACCOUNT_NAME + " IS NULL",
534 null, null);
535 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700536
537 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700538 if (!localRawProfile.moveToFirst()) {
539 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700540 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700541 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700542 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700543 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700544 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700545
546 // Find the structured name for the raw contact.
547 final Cursor structuredName = cr.query(
548 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
549 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
550 CommonDataKinds.StructuredName.FAMILY_NAME},
551 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
552 null, null);
553 if (structuredName == null) return null;
554
555 try {
556 if (!structuredName.moveToFirst()) {
557 return null;
558 }
559 String partialName = structuredName.getString(0);
560 if (TextUtils.isEmpty(partialName)) {
561 partialName = structuredName.getString(1);
562 }
563 return partialName;
564 } finally {
565 structuredName.close();
566 }
567 }
568
569 private static final String getProfileDisplayName(Context context) {
570 final ContentResolver cr = context.getContentResolver();
571 final Cursor profile = cr.query(Profile.CONTENT_URI,
572 new String[] {Profile.DISPLAY_NAME}, null, null, null);
573 if (profile == null) return null;
574
575 try {
576 if (!profile.moveToFirst()) {
577 return null;
578 }
579 return profile.getString(0);
580 } finally {
581 profile.close();
582 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700583 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700584
585 /** Not global warming, it's global change warning. */
586 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
587 final Runnable positiveAction) {
588 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
589 builder.setTitle(titleResId);
590 builder.setMessage(R.string.global_change_warning);
591 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
592 @Override
593 public void onClick(DialogInterface dialog, int which) {
594 positiveAction.run();
595 }
596 });
597 builder.setNegativeButton(android.R.string.cancel, null);
598
599 return builder.create();
600 }
601
602 public static boolean hasMultipleUsers(Context context) {
603 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
604 .getUsers().size() > 1;
605 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700606
607 /**
608 * Start a new instance of the activity, showing only the given fragment.
609 * When launched in this mode, the given preference fragment will be instantiated and fill the
610 * entire activity.
611 *
612 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000613 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700614 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700615 * @param resultTo Option fragment that should receive the result of the activity launch.
616 * @param resultRequestCode If resultTo is non-null, this is the request code in which
617 * to report the result.
618 * @param titleResId resource id for the String to display for the title of this set
619 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700620 * @param title String to display for the title of this set of preferences.
621 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000622 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100623 Fragment resultTo, int resultRequestCode, int titleResId,
624 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700625 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100626 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
627 }
628
629 /**
630 * Start a new instance of the activity, showing only the given fragment.
631 * When launched in this mode, the given preference fragment will be instantiated and fill the
632 * entire activity.
633 *
634 * @param context The context.
635 * @param fragmentName The name of the fragment to display.
636 * @param args Optional arguments to supply to the fragment.
637 * @param resultTo Option fragment that should receive the result of the activity launch.
638 * @param resultRequestCode If resultTo is non-null, this is the request code in which
639 * to report the result.
640 * @param titleResPackageName Optional package name for the resource id of the title.
641 * @param titleResId resource id for the String to display for the title of this set
642 * of preferences.
643 * @param title String to display for the title of this set of preferences.
644 */
645 public static void startWithFragment(Context context, String fragmentName, Bundle args,
646 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
647 CharSequence title) {
648 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
649 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700650 }
651
652 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100653 Fragment resultTo, int resultRequestCode, int titleResId,
654 CharSequence title, boolean isShortcut) {
655 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
656 null /* titleResPackageName */, titleResId, title, isShortcut);
657 if (resultTo == null) {
658 context.startActivity(intent);
659 } else {
660 resultTo.startActivityForResult(intent, resultRequestCode);
661 }
662 }
663
664 public static void startWithFragment(Context context, String fragmentName, Bundle args,
665 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
666 CharSequence title, boolean isShortcut) {
667 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
668 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700669 if (resultTo == null) {
670 context.startActivity(intent);
671 } else {
672 resultTo.startActivityForResult(intent, resultRequestCode);
673 }
674 }
675
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100676 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100677 int titleResId, CharSequence title, boolean isShortcut,
678 UserHandle userHandle) {
679 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
680 null /* titleResPackageName */, titleResId, title, isShortcut);
681 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
682 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
683 context.startActivityAsUser(intent, userHandle);
684 }
685
686 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
687 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
688 UserHandle userHandle) {
689 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
690 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100691 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
692 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100693 context.startActivityAsUser(intent, userHandle);
694 }
695
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700696 /**
697 * Build an Intent to launch a new activity showing the selected fragment.
698 * The implementation constructs an Intent that re-launches the current activity with the
699 * appropriate arguments to display the fragment.
700 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700701 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700702 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000703 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700704 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100705 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700706 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700707 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700708 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700709 * @return Returns an Intent that can be launched to display the given
710 * fragment.
711 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000712 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100713 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
714 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700715 Intent intent = new Intent(Intent.ACTION_MAIN);
716 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000717 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700718 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100719 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
720 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700721 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700722 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700723 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700724 return intent;
725 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100726
727 /**
728 * Returns the managed profile of the current user or null if none found.
729 */
730 public static UserHandle getManagedProfile(UserManager userManager) {
731 List<UserHandle> userProfiles = userManager.getUserProfiles();
732 final int count = userProfiles.size();
733 for (int i = 0; i < count; i++) {
734 final UserHandle profile = userProfiles.get(i);
735 if (profile.getIdentifier() == userManager.getUserHandle()) {
736 continue;
737 }
738 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
739 if (userInfo.isManagedProfile()) {
740 return profile;
741 }
742 }
743 return null;
744 }
745
746 /**
747 * Returns true if the current profile is a managed one.
748 */
749 public static boolean isManagedProfile(UserManager userManager) {
750 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
751 return currentUser.isManagedProfile();
752 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100753
754 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500755 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100756 *
757 * <p> The adapter can be used to populate a spinner that switches between the Settings
758 * app on the different profiles.
759 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500760 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100761 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500762 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100763 Context context) {
764 List<UserHandle> userProfiles = userManager.getUserProfiles();
765 if (userProfiles.size() < 2) {
766 return null;
767 }
768
769 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
770 // The first option should be the current profile
771 userProfiles.remove(myUserHandle);
772 userProfiles.add(0, myUserHandle);
773
Jason Monk2ebc8a02015-02-13 15:23:19 -0500774 return createUserAdapter(userManager, context, userProfiles);
775 }
776
777 public static UserAdapter createUserAdapter(UserManager userManager,
778 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100779 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
780 final int count = userProfiles.size();
781 for (int i = 0; i < count; i++) {
782 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
783 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500784 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100785 }
786
787 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100788 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100789 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100790 * The target user can be either the current user, the user that launched this activity or
791 * the user contained as an extra in the arguments or intent extras.
792 *
793 * Note: This is secure in the sense that it only returns a target user different to the current
794 * one if the app launching this activity is the Settings app itself, running in the same user
795 * 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 +0100796 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100797 public static UserHandle getSecureTargetUser(IBinder activityToken,
798 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
799 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
800 IActivityManager am = ActivityManagerNative.getDefault();
801 try {
802 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
803 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
804
805 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
806 am.getLaunchedFromUid(activityToken)));
807 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
808 // Check it's secure
809 if (isProfileOf(um, launchedFromUser)) {
810 return launchedFromUser;
811 }
812 }
813 UserHandle extrasUser = intentExtras != null
814 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
815 if (extrasUser != null && !extrasUser.equals(currentUser)) {
816 // Check it's secure
817 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
818 return extrasUser;
819 }
820 }
821 UserHandle argumentsUser = arguments != null
822 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
823 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
824 // Check it's secure
825 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
826 return argumentsUser;
827 }
828 }
829 } catch (RemoteException e) {
830 // Should not happen
831 Log.v(TAG, "Could not talk to activity manager.", e);
832 }
833 return currentUser;
834 }
835
836 /**
837 * Returns the target user for a Settings activity.
838 *
839 * The target user can be either the current user, the user that launched this activity or
840 * the user contained as an extra in the arguments or intent extras.
841 *
842 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
843 * possible.
844 *
845 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
846 */
847 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
848 @Nullable Bundle intentExtras) {
849 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
850 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100851 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100852 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
853 am.getLaunchedFromUid(activityToken)));
854 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
855 return launchedFromUser;
856 }
857 UserHandle extrasUser = intentExtras != null
858 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
859 if (extrasUser != null && !extrasUser.equals(currentUser)) {
860 return extrasUser;
861 }
862 UserHandle argumentsUser = arguments != null
863 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
864 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
865 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100866 }
867 } catch (RemoteException e) {
868 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100869 Log.v(TAG, "Could not talk to activity manager.", e);
870 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100871 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100872 return currentUser;
873 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100874
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100875 /**
876 * Returns true if the user provided is in the same profiles group as the current user.
877 */
878 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
879 if (um == null || otherUser == null) return false;
880 return (UserHandle.myUserId() == otherUser.getIdentifier())
881 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100882 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530883
Andres Moralesce249fe2014-07-07 16:58:16 -0700884
885 /**
886 * Returns whether or not this device is able to be OEM unlocked.
887 */
888 static boolean isOemUnlockEnabled(Context context) {
889 PersistentDataBlockManager manager =(PersistentDataBlockManager)
890 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
891 return manager.getOemUnlockEnabled();
892 }
893
894 /**
895 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
896 * devices allow users to flash other OSes to them.
897 */
898 static void setOemUnlockEnabled(Context context, boolean enabled) {
899 PersistentDataBlockManager manager =(PersistentDataBlockManager)
900 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
901 manager.setOemUnlockEnabled(enabled);
902 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100903
904 /**
905 * Returns a circular icon for a user.
906 */
907 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000908 if (user.isManagedProfile()) {
909 // We use predefined values for managed profiles
910 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
911 com.android.internal.R.drawable.ic_corp_icon);
912 return CircleFramedDrawable.getInstance(context, b);
913 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100914 if (user.iconPath != null) {
915 Bitmap icon = um.getUserIcon(user.id);
916 if (icon != null) {
917 return CircleFramedDrawable.getInstance(context, icon);
918 }
919 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000920 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
921 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100922 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700923
924 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000925 * Returns a label for the user, in the form of "User: user name" or "Work profile".
926 */
927 public static String getUserLabel(Context context, UserInfo info) {
Amith Yamasani5d69aae2015-07-07 10:13:12 -0700928 String name = info != null ? info.name : null;
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000929 if (info.isManagedProfile()) {
930 // We use predefined values for managed profiles
931 return context.getString(R.string.managed_user_title);
Amith Yamasani5d69aae2015-07-07 10:13:12 -0700932 } else if (info.isGuest()) {
933 name = context.getString(R.string.user_guest);
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000934 }
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000935 if (name == null && info != null) {
936 name = Integer.toString(info.id);
937 } else if (info == null) {
938 name = context.getString(R.string.unknown);
939 }
940 return context.getResources().getString(R.string.running_process_item_user_label, name);
941 }
942
943 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700944 * Return whether or not the user should have a SIM Cards option in Settings.
945 * TODO: Change back to returning true if count is greater than one after testing.
946 * TODO: See bug 16533525.
947 */
948 public static boolean showSimCardTile(Context context) {
949 final TelephonyManager tm =
950 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
951
PauloftheWestdbd03822014-12-04 11:56:35 -0800952 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700953 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200954
955 /**
956 * Determine whether a package is a "system package", in which case certain things (like
957 * disabling notifications or disabling the package altogether) should be disallowed.
958 */
959 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
960 if (sSystemSignature == null) {
961 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
962 }
963 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
964 }
965
966 private static Signature[] sSystemSignature;
967
968 private static Signature getFirstSignature(PackageInfo pkg) {
969 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
970 return pkg.signatures[0];
971 }
972 return null;
973 }
974
975 private static Signature getSystemSignature(PackageManager pm) {
976 try {
977 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
978 return getFirstSignature(sys);
979 } catch (NameNotFoundException e) {
980 }
981 return null;
982 }
983
Elliott Hughes7253df32014-09-02 17:10:14 -0700984 /**
985 * Returns elapsed time for the given millis, in the following format:
986 * 2d 5h 40m 29s
987 * @param context the application context
988 * @param millis the elapsed time in milli seconds
989 * @param withSeconds include seconds?
990 * @return the formatted elapsed time
991 */
992 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
993 StringBuilder sb = new StringBuilder();
994 int seconds = (int) Math.floor(millis / 1000);
995 if (!withSeconds) {
996 // Round up.
997 seconds += 30;
998 }
999
1000 int days = 0, hours = 0, minutes = 0;
1001 if (seconds >= SECONDS_PER_DAY) {
1002 days = seconds / SECONDS_PER_DAY;
1003 seconds -= days * SECONDS_PER_DAY;
1004 }
1005 if (seconds >= SECONDS_PER_HOUR) {
1006 hours = seconds / SECONDS_PER_HOUR;
1007 seconds -= hours * SECONDS_PER_HOUR;
1008 }
1009 if (seconds >= SECONDS_PER_MINUTE) {
1010 minutes = seconds / SECONDS_PER_MINUTE;
1011 seconds -= minutes * SECONDS_PER_MINUTE;
1012 }
1013 if (withSeconds) {
1014 if (days > 0) {
1015 sb.append(context.getString(R.string.battery_history_days,
1016 days, hours, minutes, seconds));
1017 } else if (hours > 0) {
1018 sb.append(context.getString(R.string.battery_history_hours,
1019 hours, minutes, seconds));
1020 } else if (minutes > 0) {
1021 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1022 } else {
1023 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1024 }
1025 } else {
1026 if (days > 0) {
1027 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1028 days, hours, minutes));
1029 } else if (hours > 0) {
1030 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1031 hours, minutes));
1032 } else {
1033 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1034 }
1035 }
1036 return sb.toString();
1037 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001038
1039 /**
Amith Yamasani45f86232014-11-19 17:12:46 -08001040 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1041 * @param userManager Instance of UserManager
1042 * @param checkUser The user to check the existence of.
1043 * @return UserInfo of the user or null for non-existent user.
1044 */
1045 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1046 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1047 final int checkUserId = checkUser.getIdentifier();
1048 for (UserInfo user : users) {
1049 if (user.id == checkUserId) {
1050 return user;
1051 }
1052 }
1053 return null;
1054 }
1055
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001056 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1057 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1058 com.android.internal.R.styleable.Preference,
1059 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1060 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1061 0);
1062 a.recycle();
1063 return inflater.inflate(resId, parent, false);
1064 }
1065
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001066 /**
1067 * Return if we are running low on storage space or not.
1068 *
1069 * @param context The context
1070 * @return true if we are running low on storage space
1071 */
1072 public static boolean isLowStorage(Context context) {
1073 final StorageManager sm = StorageManager.from(context);
1074 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1075 }
1076
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001077 /**
1078 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1079 *
1080 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1081 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1082 */
1083 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1084 Bitmap bitmap = null;
1085 // Try finding the corresponding bitmap in the dark bitmap cache
1086 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1087 if (bitmap == null) {
1088 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1089 // Save it to cache
1090 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1091 }
1092 return bitmap;
1093 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001094
1095 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1096 try {
1097 if (usbManager != null) {
1098 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1099 }
1100 } catch (RemoteException e) {
1101 Log.e(TAG, "mUsbManager.hasDefaults", e);
1102 }
1103 return false;
1104 }
1105
1106 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1107 // Get list of preferred activities
1108 List<ComponentName> prefActList = new ArrayList<>();
1109 // Intent list cannot be null. so pass empty list
1110 List<IntentFilter> intentList = new ArrayList<>();
1111 pm.getPreferredActivities(intentList, prefActList, packageName);
1112 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1113 return prefActList.size() > 0;
1114 }
1115
Christopher Tatea08a2252015-07-01 16:52:43 -07001116 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
1117 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
1118 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
1119
1120 ArraySet<String> result = new ArraySet<>();
1121 if (iviList.size() > 0) {
1122 for (IntentFilterVerificationInfo ivi : iviList) {
1123 for (String host : ivi.getDomains()) {
1124 result.add(host);
1125 }
1126 }
1127 }
1128 if (filters != null && filters.size() > 0) {
1129 for (IntentFilter filter : filters) {
1130 if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1131 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
1132 result.addAll(filter.getHostsList());
1133 }
1134 }
1135 }
1136 return result;
1137 }
1138
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001139 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1140 IUsbManager usbManager, PackageManager pm, Context context) {
1141 String packageName = appEntry.info.packageName;
1142 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1143 || hasUsbDefaults(usbManager, packageName);
1144 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
1145 boolean hasDomainURLsPreference =
1146 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
1147 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
1148 return context.getString(hasPreferred || hasDomainURLsPreference
1149 ? R.string.launch_defaults_some
1150 : R.string.launch_defaults_none);
1151 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001152
1153 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1154 boolean animate) {
1155 setViewShown(loading, !done, animate);
1156 setViewShown(doneLoading, done, animate);
1157 }
1158
1159 private static void setViewShown(final View view, boolean shown, boolean animate) {
1160 if (animate) {
1161 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1162 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1163 if (shown) {
1164 view.setVisibility(View.VISIBLE);
1165 } else {
1166 animation.setAnimationListener(new AnimationListener() {
1167 @Override
1168 public void onAnimationStart(Animation animation) {
1169 }
1170
1171 @Override
1172 public void onAnimationRepeat(Animation animation) {
1173 }
1174
1175 @Override
1176 public void onAnimationEnd(Animation animation) {
1177 view.setVisibility(View.INVISIBLE);
1178 }
1179 });
1180 }
1181 view.startAnimation(animation);
1182 } else {
1183 view.clearAnimation();
1184 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1185 }
1186 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001187
1188 /**
1189 * Returns the application info of the currently installed MDM package.
1190 */
1191 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1192 DevicePolicyManager dpm =
1193 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1194 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1195 if (mdmPackage == null) {
1196 return null;
1197 }
1198 String mdmPackageName = mdmPackage.getPackageName();
1199 try {
1200 IPackageManager ipm = AppGlobals.getPackageManager();
1201 ApplicationInfo mdmApplicationInfo =
1202 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1203 return mdmApplicationInfo;
1204 } catch (RemoteException e) {
1205 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1206 + ", userId " + profileId, e);
1207 return null;
1208 }
1209 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001210
1211 public static boolean isBandwidthControlEnabled() {
1212 final INetworkManagementService netManager = INetworkManagementService.Stub
1213 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1214 try {
1215 return netManager.isBandwidthControlEnabled();
1216 } catch (RemoteException e) {
1217 return false;
1218 }
1219 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001220}