blob: b7f62a300d79b51bb3dfe6e0ce439dca2c52d93f [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;
Jason Monkb45e27b2015-05-20 13:35:43 -040058import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010059import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040060import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070061import android.os.UserHandle;
62import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080063import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080064import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070065import android.preference.PreferenceFrameLayout;
66import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070067import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070068import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070069import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070070import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070071import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070072import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080073import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080074import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070075import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020076import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010077import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000078import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000079import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070080import android.view.View;
81import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040082import android.view.animation.Animation;
83import android.view.animation.Animation.AnimationListener;
84import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070085import android.widget.ListView;
86import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010087
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010088import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050089import com.android.settings.UserAdapter.UserDetails;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080090import com.android.settings.applications.ApplicationsState;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070091import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010092import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070093
Amith Yamasaniae47ef42012-09-16 17:53:35 -070094import java.io.IOException;
95import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080096import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070097import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010098import java.util.ArrayList;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080099import java.util.Collections;
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800100import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700101import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900102import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800103
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700104public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100105 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100106
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800107 /**
108 * Set the preference's title to the matching activity's label.
109 */
110 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
111
112 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900113 * The opacity level of a disabled icon.
114 */
115 public static final float DISABLED_ALPHA = 0.4f;
116
117 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700118 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
119 * 1 is most bad (red), the last value is least bad (green).
120 */
121 public static final int[] BADNESS_COLORS = new int[] {
122 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
123 0xfffabf2c, 0xff679e37, 0xff0a7f42
124 };
125
126 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200127 * Name of the meta-data item that should be set in the AndroidManifest.xml
128 * to specify the icon that should be displayed for the preference.
129 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500130 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200131
132 /**
133 * Name of the meta-data item that should be set in the AndroidManifest.xml
134 * to specify the title that should be displayed for the preference.
135 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500136 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200137
138 /**
139 * Name of the meta-data item that should be set in the AndroidManifest.xml
140 * to specify the summary text that should be displayed for the preference.
141 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500142 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200143
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100144 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
145
Elliott Hughes7253df32014-09-02 17:10:14 -0700146 private static final int SECONDS_PER_MINUTE = 60;
147 private static final int SECONDS_PER_HOUR = 60 * 60;
148 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
149
Jason Monkbeb171d2015-05-21 15:24:37 -0400150 public static final String OS_PKG = "os";
151
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000152 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
153
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200154 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 * Finds a matching activity for a preference's intent. If a matching
156 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800157 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800158 * @param context The context.
159 * @param parentPreferenceGroup The preference group that contains the
160 * preference whose intent is being resolved.
161 * @param preferenceKey The key of the preference whose intent is being
162 * resolved.
163 * @param flags 0 or one or more of
164 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
165 * .
166 * @return Whether an activity was found. If false, the preference was
167 * removed.
168 */
169 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
170 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800171
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800172 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
173 if (preference == null) {
174 return false;
175 }
Ying Wanga7188322010-01-04 18:45:10 -0800176
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800177 Intent intent = preference.getIntent();
178 if (intent != null) {
179 // Find the activity that is in the system image
180 PackageManager pm = context.getPackageManager();
181 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
182 int listSize = list.size();
183 for (int i = 0; i < listSize; i++) {
184 ResolveInfo resolveInfo = list.get(i);
185 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
186 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800187
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800188 // Replace the intent with this specific activity
189 preference.setIntent(new Intent().setClassName(
190 resolveInfo.activityInfo.packageName,
191 resolveInfo.activityInfo.name));
192
193 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
194 // Set the preference title to the activity's label
195 preference.setTitle(resolveInfo.loadLabel(pm));
196 }
Ying Wanga7188322010-01-04 18:45:10 -0800197
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800198 return true;
199 }
200 }
201 }
202
203 // Did not find a matching activity, so remove the preference
204 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800205
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900206 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800207 }
Ying Wanga7188322010-01-04 18:45:10 -0800208
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700209 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700210 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700211
212 Intent intent = tile.intent;
213 if (intent != null) {
214 // Find the activity that is in the system image
215 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500216 List<ResolveInfo> list = tile.userHandle.size() != 0
217 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
218 tile.userHandle.get(0).getIdentifier())
219 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700220 int listSize = list.size();
221 for (int i = 0; i < listSize; i++) {
222 ResolveInfo resolveInfo = list.get(i);
223 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
224 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500225 int icon = 0;
226 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700227 String summary = null;
228
229 // Get the activity's meta-data
230 try {
231 Resources res = pm.getResourcesForApplication(
232 resolveInfo.activityInfo.packageName);
233 Bundle metaData = resolveInfo.activityInfo.metaData;
234
235 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500236 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
237 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
238 }
239 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
240 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
241 }
242 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
243 summary = res.getString(
244 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
245 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700246 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500247 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700248 // Ignore
249 }
250
251 // Set the preference title to the activity's label if no
252 // meta-data is found
253 if (TextUtils.isEmpty(title)) {
254 title = resolveInfo.loadLabel(pm).toString();
255 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500256 if (icon == 0) {
257 icon = resolveInfo.activityInfo.icon;
258 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700259
260 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500261 tile.iconRes = icon;
262 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700263 tile.title = title;
264 tile.summary = summary;
265 // Replace the intent with this specific activity
266 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
267 resolveInfo.activityInfo.name);
268
269 return true;
270 }
271 }
272 }
273
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700274 return false;
275 }
276
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200277 /**
Ying Wanga7188322010-01-04 18:45:10 -0800278 * Returns true if Monkey is running.
279 */
280 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700281 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800282 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700283
284 /**
285 * Returns whether the device is voice-capable (meaning, it is also a phone).
286 */
287 public static boolean isVoiceCapable(Context context) {
288 TelephonyManager telephony =
289 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
290 return telephony != null && telephony.isVoiceCapable();
291 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800292
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700293 public static boolean isWifiOnly(Context context) {
294 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
295 Context.CONNECTIVITY_SERVICE);
296 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800297 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800298
299 /**
300 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
301 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900302 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800303 */
304 public static String getWifiIpAddresses(Context context) {
305 ConnectivityManager cm = (ConnectivityManager)
306 context.getSystemService(Context.CONNECTIVITY_SERVICE);
307 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700308 return formatIpAddresses(prop);
309 }
310
311 /**
312 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
313 * addresses.
314 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900315 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700316 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900317 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700318 LinkProperties prop = cm.getActiveLinkProperties();
319 return formatIpAddresses(prop);
320 }
321
322 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800323 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900324 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800325 // If there are no entries, return null
326 if (!iter.hasNext()) return null;
327 // Concatenate all available addresses, comma separated
328 String addresses = "";
329 while (iter.hasNext()) {
330 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900331 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800332 }
333 return addresses;
334 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900335
336 public static Locale createLocaleFromString(String localeStr) {
337 // TODO: is there a better way to actually construct a locale that will match?
338 // The main problem is, on top of Java specs, locale.toString() and
339 // new Locale(locale.toString()).toString() do not return equal() strings in
340 // many cases, because the constructor takes the only string as the language
341 // code. So : new Locale("en", "US").toString() => "en_US"
342 // And : new Locale("en_US").toString() => "en_us"
343 if (null == localeStr)
344 return Locale.getDefault();
345 String[] brokenDownLocale = localeStr.split("_", 3);
346 // split may not return a 0-length array.
347 if (1 == brokenDownLocale.length) {
348 return new Locale(brokenDownLocale[0]);
349 } else if (2 == brokenDownLocale.length) {
350 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
351 } else {
352 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
353 }
354 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700355
Elliott Hughes7253df32014-09-02 17:10:14 -0700356 /** Formats the ratio of amount/total as a percentage. */
357 public static String formatPercentage(long amount, long total) {
358 return formatPercentage(((double) amount) / total);
359 }
360
361 /** Formats an integer from 0..100 as a percentage. */
362 public static String formatPercentage(int percentage) {
363 return formatPercentage(((double) percentage) / 100.0);
364 }
365
366 /** Formats a double from 0.0..1.0 as a percentage. */
367 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700368 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700369 }
370
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900371 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
372 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
373 }
374
Amith Yamasania4379d62011-07-22 10:34:58 -0700375 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700376 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700377 }
378
379 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900380 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
381 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700382 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700383 }
384
385 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
386 final Intent intent = batteryChangedIntent;
387
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900388 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
389 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
390 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700391 String statusString;
392 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700393 int resId;
394 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
395 resId = R.string.battery_info_status_charging_ac;
396 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
397 resId = R.string.battery_info_status_charging_usb;
398 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
399 resId = R.string.battery_info_status_charging_wireless;
400 } else {
401 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700402 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700403 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700404 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
405 statusString = res.getString(R.string.battery_info_status_discharging);
406 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
407 statusString = res.getString(R.string.battery_info_status_not_charging);
408 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
409 statusString = res.getString(R.string.battery_info_status_full);
410 } else {
411 statusString = res.getString(R.string.battery_info_status_unknown);
412 }
413
414 return statusString;
415 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700416
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800417 public static void forcePrepareCustomPreferencesList(
418 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
419 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
420 list.setClipToPadding(false);
421 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
422 }
423
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700424 /**
425 * Prepare a custom preferences layout, moving padding to {@link ListView}
426 * when outside scrollbars are requested. Usually used to display
427 * {@link ListView} and {@link TabWidget} with correct padding.
428 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700429 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800430 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700431 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700432 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700433 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700434 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700435 final int paddingBottom = res.getDimensionPixelSize(
436 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700437
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700438 if (parent instanceof PreferenceFrameLayout) {
439 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
440
441 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
442 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
443 } else {
444 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
445 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700446 }
447 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700448
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700449 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700450 final Resources res = view.getResources();
451 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700452
453 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
454 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700455 final int paddingBottom = res.getDimensionPixelSize(
456 com.android.internal.R.dimen.preference_fragment_padding_bottom);
457
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700458 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700459 }
460
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700461 /**
462 * Return string resource that best describes combination of tethering
463 * options available on this device.
464 */
465 public static int getTetheringLabel(ConnectivityManager cm) {
466 String[] usbRegexs = cm.getTetherableUsbRegexs();
467 String[] wifiRegexs = cm.getTetherableWifiRegexs();
468 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
469
470 boolean usbAvailable = usbRegexs.length != 0;
471 boolean wifiAvailable = wifiRegexs.length != 0;
472 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
473
474 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
475 return R.string.tether_settings_title_all;
476 } else if (wifiAvailable && usbAvailable) {
477 return R.string.tether_settings_title_all;
478 } else if (wifiAvailable && bluetoothAvailable) {
479 return R.string.tether_settings_title_all;
480 } else if (wifiAvailable) {
481 return R.string.tether_settings_title_wifi;
482 } else if (usbAvailable && bluetoothAvailable) {
483 return R.string.tether_settings_title_usb_bluetooth;
484 } else if (usbAvailable) {
485 return R.string.tether_settings_title_usb;
486 } else {
487 return R.string.tether_settings_title_bluetooth;
488 }
489 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700490
491 /* Used by UserSettings as well. Call this on a non-ui thread. */
492 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
493 Uri contactUri = Profile.CONTENT_URI;
494
495 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
496 context.getContentResolver(),
497 contactUri, true);
498 // If there's no profile photo, assign a default avatar
499 if (avatarDataStream == null) {
500 return false;
501 }
502 int userId = user != null ? user.id : UserHandle.myUserId();
503 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700504 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
505 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700506 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700507 avatarDataStream.close();
508 } catch (IOException ioe) { }
509 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700510 }
511
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700512 public static String getMeProfileName(Context context, boolean full) {
513 if (full) {
514 return getProfileDisplayName(context);
515 } else {
516 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700517 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700518 }
519
520 private static String getShorterNameIfPossible(Context context) {
521 final String given = getLocalProfileGivenName(context);
522 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
523 }
524
525 private static String getLocalProfileGivenName(Context context) {
526 final ContentResolver cr = context.getContentResolver();
527
528 // Find the raw contact ID for the local ME profile raw contact.
529 final long localRowProfileId;
530 final Cursor localRawProfile = cr.query(
531 Profile.CONTENT_RAW_CONTACTS_URI,
532 new String[] {RawContacts._ID},
533 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
534 RawContacts.ACCOUNT_NAME + " IS NULL",
535 null, null);
536 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700537
538 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700539 if (!localRawProfile.moveToFirst()) {
540 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700541 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700542 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700543 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700544 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700545 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700546
547 // Find the structured name for the raw contact.
548 final Cursor structuredName = cr.query(
549 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
550 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
551 CommonDataKinds.StructuredName.FAMILY_NAME},
552 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
553 null, null);
554 if (structuredName == null) return null;
555
556 try {
557 if (!structuredName.moveToFirst()) {
558 return null;
559 }
560 String partialName = structuredName.getString(0);
561 if (TextUtils.isEmpty(partialName)) {
562 partialName = structuredName.getString(1);
563 }
564 return partialName;
565 } finally {
566 structuredName.close();
567 }
568 }
569
570 private static final String getProfileDisplayName(Context context) {
571 final ContentResolver cr = context.getContentResolver();
572 final Cursor profile = cr.query(Profile.CONTENT_URI,
573 new String[] {Profile.DISPLAY_NAME}, null, null, null);
574 if (profile == null) return null;
575
576 try {
577 if (!profile.moveToFirst()) {
578 return null;
579 }
580 return profile.getString(0);
581 } finally {
582 profile.close();
583 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700584 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700585
586 /** Not global warming, it's global change warning. */
587 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
588 final Runnable positiveAction) {
589 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
590 builder.setTitle(titleResId);
591 builder.setMessage(R.string.global_change_warning);
592 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
593 @Override
594 public void onClick(DialogInterface dialog, int which) {
595 positiveAction.run();
596 }
597 });
598 builder.setNegativeButton(android.R.string.cancel, null);
599
600 return builder.create();
601 }
602
603 public static boolean hasMultipleUsers(Context context) {
604 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
605 .getUsers().size() > 1;
606 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700607
608 /**
609 * Start a new instance of the activity, showing only the given fragment.
610 * When launched in this mode, the given preference fragment will be instantiated and fill the
611 * entire activity.
612 *
613 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000614 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700615 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700616 * @param resultTo Option fragment that should receive the result of the activity launch.
617 * @param resultRequestCode If resultTo is non-null, this is the request code in which
618 * to report the result.
619 * @param titleResId resource id for the String to display for the title of this set
620 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700621 * @param title String to display for the title of this set of preferences.
622 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000623 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100624 Fragment resultTo, int resultRequestCode, int titleResId,
625 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700626 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100627 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
628 }
629
630 /**
631 * Start a new instance of the activity, showing only the given fragment.
632 * When launched in this mode, the given preference fragment will be instantiated and fill the
633 * entire activity.
634 *
635 * @param context The context.
636 * @param fragmentName The name of the fragment to display.
637 * @param args Optional arguments to supply to the fragment.
638 * @param resultTo Option fragment that should receive the result of the activity launch.
639 * @param resultRequestCode If resultTo is non-null, this is the request code in which
640 * to report the result.
641 * @param titleResPackageName Optional package name for the resource id of the title.
642 * @param titleResId resource id for the String to display for the title of this set
643 * of preferences.
644 * @param title String to display for the title of this set of preferences.
645 */
646 public static void startWithFragment(Context context, String fragmentName, Bundle args,
647 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
648 CharSequence title) {
649 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
650 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700651 }
652
653 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100654 Fragment resultTo, int resultRequestCode, int titleResId,
655 CharSequence title, boolean isShortcut) {
656 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
657 null /* titleResPackageName */, titleResId, title, isShortcut);
658 if (resultTo == null) {
659 context.startActivity(intent);
660 } else {
661 resultTo.startActivityForResult(intent, resultRequestCode);
662 }
663 }
664
665 public static void startWithFragment(Context context, String fragmentName, Bundle args,
666 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
667 CharSequence title, boolean isShortcut) {
668 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
669 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700670 if (resultTo == null) {
671 context.startActivity(intent);
672 } else {
673 resultTo.startActivityForResult(intent, resultRequestCode);
674 }
675 }
676
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100677 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100678 int titleResId, CharSequence title, boolean isShortcut,
679 UserHandle userHandle) {
680 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
681 null /* titleResPackageName */, titleResId, title, isShortcut);
682 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
683 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
684 context.startActivityAsUser(intent, userHandle);
685 }
686
687 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
688 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
689 UserHandle userHandle) {
690 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
691 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100692 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
693 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100694 context.startActivityAsUser(intent, userHandle);
695 }
696
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700697 /**
698 * Build an Intent to launch a new activity showing the selected fragment.
699 * The implementation constructs an Intent that re-launches the current activity with the
700 * appropriate arguments to display the fragment.
701 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700702 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700703 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000704 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700705 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100706 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700707 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700708 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700709 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700710 * @return Returns an Intent that can be launched to display the given
711 * fragment.
712 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000713 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100714 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
715 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700716 Intent intent = new Intent(Intent.ACTION_MAIN);
717 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000718 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700719 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100720 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
721 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700722 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700723 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700724 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700725 return intent;
726 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100727
728 /**
729 * Returns the managed profile of the current user or null if none found.
730 */
731 public static UserHandle getManagedProfile(UserManager userManager) {
732 List<UserHandle> userProfiles = userManager.getUserProfiles();
733 final int count = userProfiles.size();
734 for (int i = 0; i < count; i++) {
735 final UserHandle profile = userProfiles.get(i);
736 if (profile.getIdentifier() == userManager.getUserHandle()) {
737 continue;
738 }
739 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
740 if (userInfo.isManagedProfile()) {
741 return profile;
742 }
743 }
744 return null;
745 }
746
747 /**
748 * Returns true if the current profile is a managed one.
749 */
750 public static boolean isManagedProfile(UserManager userManager) {
751 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
752 return currentUser.isManagedProfile();
753 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100754
755 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500756 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100757 *
758 * <p> The adapter can be used to populate a spinner that switches between the Settings
759 * app on the different profiles.
760 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500761 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100762 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500763 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100764 Context context) {
765 List<UserHandle> userProfiles = userManager.getUserProfiles();
766 if (userProfiles.size() < 2) {
767 return null;
768 }
769
770 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
771 // The first option should be the current profile
772 userProfiles.remove(myUserHandle);
773 userProfiles.add(0, myUserHandle);
774
Jason Monk2ebc8a02015-02-13 15:23:19 -0500775 return createUserAdapter(userManager, context, userProfiles);
776 }
777
778 public static UserAdapter createUserAdapter(UserManager userManager,
779 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100780 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
781 final int count = userProfiles.size();
782 for (int i = 0; i < count; i++) {
783 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
784 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500785 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100786 }
787
788 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100789 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100790 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100791 * The target user can be either the current user, the user that launched this activity or
792 * the user contained as an extra in the arguments or intent extras.
793 *
794 * Note: This is secure in the sense that it only returns a target user different to the current
795 * one if the app launching this activity is the Settings app itself, running in the same user
796 * 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 +0100797 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100798 public static UserHandle getSecureTargetUser(IBinder activityToken,
799 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
800 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
801 IActivityManager am = ActivityManagerNative.getDefault();
802 try {
803 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
804 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
805
806 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
807 am.getLaunchedFromUid(activityToken)));
808 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
809 // Check it's secure
810 if (isProfileOf(um, launchedFromUser)) {
811 return launchedFromUser;
812 }
813 }
814 UserHandle extrasUser = intentExtras != null
815 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
816 if (extrasUser != null && !extrasUser.equals(currentUser)) {
817 // Check it's secure
818 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
819 return extrasUser;
820 }
821 }
822 UserHandle argumentsUser = arguments != null
823 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
824 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
825 // Check it's secure
826 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
827 return argumentsUser;
828 }
829 }
830 } catch (RemoteException e) {
831 // Should not happen
832 Log.v(TAG, "Could not talk to activity manager.", e);
833 }
834 return currentUser;
835 }
836
837 /**
838 * Returns the target user for a Settings activity.
839 *
840 * The target user can be either the current user, the user that launched this activity or
841 * the user contained as an extra in the arguments or intent extras.
842 *
843 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
844 * possible.
845 *
846 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
847 */
848 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
849 @Nullable Bundle intentExtras) {
850 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
851 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100852 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100853 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
854 am.getLaunchedFromUid(activityToken)));
855 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
856 return launchedFromUser;
857 }
858 UserHandle extrasUser = intentExtras != null
859 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
860 if (extrasUser != null && !extrasUser.equals(currentUser)) {
861 return extrasUser;
862 }
863 UserHandle argumentsUser = arguments != null
864 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
865 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
866 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100867 }
868 } catch (RemoteException e) {
869 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100870 Log.v(TAG, "Could not talk to activity manager.", e);
871 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100872 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100873 return currentUser;
874 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100875
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100876 /**
877 * Returns true if the user provided is in the same profiles group as the current user.
878 */
879 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
880 if (um == null || otherUser == null) return false;
881 return (UserHandle.myUserId() == otherUser.getIdentifier())
882 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100883 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530884
Andres Moralesce249fe2014-07-07 16:58:16 -0700885
886 /**
887 * Returns whether or not this device is able to be OEM unlocked.
888 */
889 static boolean isOemUnlockEnabled(Context context) {
890 PersistentDataBlockManager manager =(PersistentDataBlockManager)
891 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
892 return manager.getOemUnlockEnabled();
893 }
894
895 /**
896 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
897 * devices allow users to flash other OSes to them.
898 */
899 static void setOemUnlockEnabled(Context context, boolean enabled) {
900 PersistentDataBlockManager manager =(PersistentDataBlockManager)
901 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
902 manager.setOemUnlockEnabled(enabled);
903 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100904
905 /**
906 * Returns a circular icon for a user.
907 */
908 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000909 if (user.isManagedProfile()) {
910 // We use predefined values for managed profiles
911 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
912 com.android.internal.R.drawable.ic_corp_icon);
913 return CircleFramedDrawable.getInstance(context, b);
914 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100915 if (user.iconPath != null) {
916 Bitmap icon = um.getUserIcon(user.id);
917 if (icon != null) {
918 return CircleFramedDrawable.getInstance(context, icon);
919 }
920 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000921 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
922 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100923 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700924
925 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000926 * Returns a label for the user, in the form of "User: user name" or "Work profile".
927 */
928 public static String getUserLabel(Context context, UserInfo info) {
929 if (info.isManagedProfile()) {
930 // We use predefined values for managed profiles
931 return context.getString(R.string.managed_user_title);
932 }
933 String name = info != null ? info.name : null;
934 if (name == null && info != null) {
935 name = Integer.toString(info.id);
936 } else if (info == null) {
937 name = context.getString(R.string.unknown);
938 }
939 return context.getResources().getString(R.string.running_process_item_user_label, name);
940 }
941
942 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700943 * Return whether or not the user should have a SIM Cards option in Settings.
944 * TODO: Change back to returning true if count is greater than one after testing.
945 * TODO: See bug 16533525.
946 */
947 public static boolean showSimCardTile(Context context) {
948 final TelephonyManager tm =
949 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
950
PauloftheWestdbd03822014-12-04 11:56:35 -0800951 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700952 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200953
954 /**
955 * Determine whether a package is a "system package", in which case certain things (like
956 * disabling notifications or disabling the package altogether) should be disallowed.
957 */
958 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
959 if (sSystemSignature == null) {
960 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
961 }
962 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
963 }
964
965 private static Signature[] sSystemSignature;
966
967 private static Signature getFirstSignature(PackageInfo pkg) {
968 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
969 return pkg.signatures[0];
970 }
971 return null;
972 }
973
974 private static Signature getSystemSignature(PackageManager pm) {
975 try {
976 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
977 return getFirstSignature(sys);
978 } catch (NameNotFoundException e) {
979 }
980 return null;
981 }
982
Elliott Hughes7253df32014-09-02 17:10:14 -0700983 /**
984 * Returns elapsed time for the given millis, in the following format:
985 * 2d 5h 40m 29s
986 * @param context the application context
987 * @param millis the elapsed time in milli seconds
988 * @param withSeconds include seconds?
989 * @return the formatted elapsed time
990 */
991 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
992 StringBuilder sb = new StringBuilder();
993 int seconds = (int) Math.floor(millis / 1000);
994 if (!withSeconds) {
995 // Round up.
996 seconds += 30;
997 }
998
999 int days = 0, hours = 0, minutes = 0;
1000 if (seconds >= SECONDS_PER_DAY) {
1001 days = seconds / SECONDS_PER_DAY;
1002 seconds -= days * SECONDS_PER_DAY;
1003 }
1004 if (seconds >= SECONDS_PER_HOUR) {
1005 hours = seconds / SECONDS_PER_HOUR;
1006 seconds -= hours * SECONDS_PER_HOUR;
1007 }
1008 if (seconds >= SECONDS_PER_MINUTE) {
1009 minutes = seconds / SECONDS_PER_MINUTE;
1010 seconds -= minutes * SECONDS_PER_MINUTE;
1011 }
1012 if (withSeconds) {
1013 if (days > 0) {
1014 sb.append(context.getString(R.string.battery_history_days,
1015 days, hours, minutes, seconds));
1016 } else if (hours > 0) {
1017 sb.append(context.getString(R.string.battery_history_hours,
1018 hours, minutes, seconds));
1019 } else if (minutes > 0) {
1020 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1021 } else {
1022 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1023 }
1024 } else {
1025 if (days > 0) {
1026 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1027 days, hours, minutes));
1028 } else if (hours > 0) {
1029 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1030 hours, minutes));
1031 } else {
1032 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1033 }
1034 }
1035 return sb.toString();
1036 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001037
1038 /**
Amith Yamasani45f86232014-11-19 17:12:46 -08001039 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1040 * @param userManager Instance of UserManager
1041 * @param checkUser The user to check the existence of.
1042 * @return UserInfo of the user or null for non-existent user.
1043 */
1044 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1045 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1046 final int checkUserId = checkUser.getIdentifier();
1047 for (UserInfo user : users) {
1048 if (user.id == checkUserId) {
1049 return user;
1050 }
1051 }
1052 return null;
1053 }
1054
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001055 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1056 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1057 com.android.internal.R.styleable.Preference,
1058 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1059 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1060 0);
1061 a.recycle();
1062 return inflater.inflate(resId, parent, false);
1063 }
1064
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001065 /**
1066 * Return if we are running low on storage space or not.
1067 *
1068 * @param context The context
1069 * @return true if we are running low on storage space
1070 */
1071 public static boolean isLowStorage(Context context) {
1072 final StorageManager sm = StorageManager.from(context);
1073 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1074 }
1075
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001076 /**
1077 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1078 *
1079 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1080 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1081 */
1082 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1083 Bitmap bitmap = null;
1084 // Try finding the corresponding bitmap in the dark bitmap cache
1085 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1086 if (bitmap == null) {
1087 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1088 // Save it to cache
1089 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1090 }
1091 return bitmap;
1092 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001093
1094 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1095 try {
1096 if (usbManager != null) {
1097 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1098 }
1099 } catch (RemoteException e) {
1100 Log.e(TAG, "mUsbManager.hasDefaults", e);
1101 }
1102 return false;
1103 }
1104
1105 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1106 // Get list of preferred activities
1107 List<ComponentName> prefActList = new ArrayList<>();
1108 // Intent list cannot be null. so pass empty list
1109 List<IntentFilter> intentList = new ArrayList<>();
1110 pm.getPreferredActivities(intentList, prefActList, packageName);
1111 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1112 return prefActList.size() > 0;
1113 }
1114
1115 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1116 IUsbManager usbManager, PackageManager pm, Context context) {
1117 String packageName = appEntry.info.packageName;
1118 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1119 || hasUsbDefaults(usbManager, packageName);
1120 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
1121 boolean hasDomainURLsPreference =
1122 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
1123 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
1124 return context.getString(hasPreferred || hasDomainURLsPreference
1125 ? R.string.launch_defaults_some
1126 : R.string.launch_defaults_none);
1127 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001128
1129 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1130 boolean animate) {
1131 setViewShown(loading, !done, animate);
1132 setViewShown(doneLoading, done, animate);
1133 }
1134
1135 private static void setViewShown(final View view, boolean shown, boolean animate) {
1136 if (animate) {
1137 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1138 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1139 if (shown) {
1140 view.setVisibility(View.VISIBLE);
1141 } else {
1142 animation.setAnimationListener(new AnimationListener() {
1143 @Override
1144 public void onAnimationStart(Animation animation) {
1145 }
1146
1147 @Override
1148 public void onAnimationRepeat(Animation animation) {
1149 }
1150
1151 @Override
1152 public void onAnimationEnd(Animation animation) {
1153 view.setVisibility(View.INVISIBLE);
1154 }
1155 });
1156 }
1157 view.startAnimation(animation);
1158 } else {
1159 view.clearAnimation();
1160 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1161 }
1162 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001163
1164 /**
1165 * Returns the application info of the currently installed MDM package.
1166 */
1167 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1168 DevicePolicyManager dpm =
1169 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1170 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1171 if (mdmPackage == null) {
1172 return null;
1173 }
1174 String mdmPackageName = mdmPackage.getPackageName();
1175 try {
1176 IPackageManager ipm = AppGlobals.getPackageManager();
1177 ApplicationInfo mdmApplicationInfo =
1178 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1179 return mdmApplicationInfo;
1180 } catch (RemoteException e) {
1181 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1182 + ", userId " + profileId, e);
1183 return null;
1184 }
1185 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001186
1187 public static boolean isBandwidthControlEnabled() {
1188 final INetworkManagementService netManager = INetworkManagementService.Stub
1189 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1190 try {
1191 return netManager.isBandwidthControlEnabled();
1192 } catch (RemoteException e) {
1193 return false;
1194 }
1195 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001196}