blob: 21a5019f039b63b86b27ffbe0330ecca49e29a2f [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;
Dan Sandlerb58b5122014-09-02 18:31:49 +020036import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080037import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070038import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070039import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020040import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070041import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020042import android.content.res.Resources;
43import android.content.res.Resources.NotFoundException;
Jason Monkb5aa73f2015-03-31 12:59:33 -040044import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070045import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070046import android.graphics.Bitmap;
47import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020048import android.graphics.drawable.Drawable;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080049import android.hardware.usb.IUsbManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080050import android.net.ConnectivityManager;
51import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070052import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070053import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020054import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010055import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040056import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010057import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040058import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070059import android.os.UserHandle;
60import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080061import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080062import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070063import android.preference.PreferenceFrameLayout;
64import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070065import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070066import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070067import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070068import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070069import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070070import android.service.persistentdata.PersistentDataBlockManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070071import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020072import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010073import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000074import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000075import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070076import android.view.View;
77import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040078import android.view.animation.Animation;
79import android.view.animation.Animation.AnimationListener;
80import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070081import android.widget.ListView;
82import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010083
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010084import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050085import com.android.settings.UserAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070086import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010087import com.android.settings.drawable.CircleFramedDrawable;
Tony Mantler67cd6ab2015-06-08 14:41:02 -070088import com.android.settingslib.applications.ApplicationsState;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070089
Amith Yamasaniae47ef42012-09-16 17:53:35 -070090import java.io.IOException;
91import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080092import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070093import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010094import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080095import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070096import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090097import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080098
Tony Mantler67cd6ab2015-06-08 14:41:02 -070099import static android.content.Intent.EXTRA_USER;
100
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700101public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100102 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100103
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800104 /**
105 * Set the preference's title to the matching activity's label.
106 */
107 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
108
109 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900110 * The opacity level of a disabled icon.
111 */
112 public static final float DISABLED_ALPHA = 0.4f;
113
114 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700115 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
116 * 1 is most bad (red), the last value is least bad (green).
117 */
118 public static final int[] BADNESS_COLORS = new int[] {
119 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
120 0xfffabf2c, 0xff679e37, 0xff0a7f42
121 };
122
123 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200124 * Name of the meta-data item that should be set in the AndroidManifest.xml
125 * to specify the icon that should be displayed for the preference.
126 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500127 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200128
129 /**
130 * Name of the meta-data item that should be set in the AndroidManifest.xml
131 * to specify the title that should be displayed for the preference.
132 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500133 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200134
135 /**
136 * Name of the meta-data item that should be set in the AndroidManifest.xml
137 * to specify the summary text that should be displayed for the preference.
138 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500139 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200140
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100141 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
142
Elliott Hughes7253df32014-09-02 17:10:14 -0700143 private static final int SECONDS_PER_MINUTE = 60;
144 private static final int SECONDS_PER_HOUR = 60 * 60;
145 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
146
Jason Monkbeb171d2015-05-21 15:24:37 -0400147 public static final String OS_PKG = "os";
148
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000149 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
150
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200151 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800152 * Finds a matching activity for a preference's intent. If a matching
153 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800154 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 * @param context The context.
156 * @param parentPreferenceGroup The preference group that contains the
157 * preference whose intent is being resolved.
158 * @param preferenceKey The key of the preference whose intent is being
159 * resolved.
160 * @param flags 0 or one or more of
161 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
162 * .
163 * @return Whether an activity was found. If false, the preference was
164 * removed.
165 */
166 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
167 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800168
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800169 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
170 if (preference == null) {
171 return false;
172 }
Ying Wanga7188322010-01-04 18:45:10 -0800173
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800174 Intent intent = preference.getIntent();
175 if (intent != null) {
176 // Find the activity that is in the system image
177 PackageManager pm = context.getPackageManager();
178 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
179 int listSize = list.size();
180 for (int i = 0; i < listSize; i++) {
181 ResolveInfo resolveInfo = list.get(i);
182 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
183 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800184
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800185 // Replace the intent with this specific activity
186 preference.setIntent(new Intent().setClassName(
187 resolveInfo.activityInfo.packageName,
188 resolveInfo.activityInfo.name));
189
190 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
191 // Set the preference title to the activity's label
192 preference.setTitle(resolveInfo.loadLabel(pm));
193 }
Ying Wanga7188322010-01-04 18:45:10 -0800194
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800195 return true;
196 }
197 }
198 }
199
200 // Did not find a matching activity, so remove the preference
201 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800202
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900203 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800204 }
Ying Wanga7188322010-01-04 18:45:10 -0800205
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700206 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700207 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700208
209 Intent intent = tile.intent;
210 if (intent != null) {
211 // Find the activity that is in the system image
212 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500213 List<ResolveInfo> list = tile.userHandle.size() != 0
214 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
215 tile.userHandle.get(0).getIdentifier())
216 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700217 int listSize = list.size();
218 for (int i = 0; i < listSize; i++) {
219 ResolveInfo resolveInfo = list.get(i);
220 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
221 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500222 int icon = 0;
223 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700224 String summary = null;
225
226 // Get the activity's meta-data
227 try {
228 Resources res = pm.getResourcesForApplication(
229 resolveInfo.activityInfo.packageName);
230 Bundle metaData = resolveInfo.activityInfo.metaData;
231
232 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500233 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
234 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
235 }
236 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
237 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
238 }
239 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
240 summary = res.getString(
241 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
242 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700243 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500244 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700245 // Ignore
246 }
247
248 // Set the preference title to the activity's label if no
249 // meta-data is found
250 if (TextUtils.isEmpty(title)) {
251 title = resolveInfo.loadLabel(pm).toString();
252 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500253 if (icon == 0) {
254 icon = resolveInfo.activityInfo.icon;
255 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700256
257 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500258 tile.iconRes = icon;
259 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700260 tile.title = title;
261 tile.summary = summary;
262 // Replace the intent with this specific activity
263 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
264 resolveInfo.activityInfo.name);
265
266 return true;
267 }
268 }
269 }
270
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700271 return false;
272 }
273
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200274 /**
Ying Wanga7188322010-01-04 18:45:10 -0800275 * Returns true if Monkey is running.
276 */
277 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700278 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800279 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700280
281 /**
282 * Returns whether the device is voice-capable (meaning, it is also a phone).
283 */
284 public static boolean isVoiceCapable(Context context) {
285 TelephonyManager telephony =
286 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
287 return telephony != null && telephony.isVoiceCapable();
288 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800289
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700290 public static boolean isWifiOnly(Context context) {
291 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
292 Context.CONNECTIVITY_SERVICE);
293 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800294 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800295
296 /**
297 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
298 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900299 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800300 */
301 public static String getWifiIpAddresses(Context context) {
302 ConnectivityManager cm = (ConnectivityManager)
303 context.getSystemService(Context.CONNECTIVITY_SERVICE);
304 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700305 return formatIpAddresses(prop);
306 }
307
308 /**
309 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
310 * addresses.
311 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900312 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700313 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900314 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700315 LinkProperties prop = cm.getActiveLinkProperties();
316 return formatIpAddresses(prop);
317 }
318
319 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800320 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900321 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800322 // If there are no entries, return null
323 if (!iter.hasNext()) return null;
324 // Concatenate all available addresses, comma separated
325 String addresses = "";
326 while (iter.hasNext()) {
327 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900328 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800329 }
330 return addresses;
331 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900332
333 public static Locale createLocaleFromString(String localeStr) {
334 // TODO: is there a better way to actually construct a locale that will match?
335 // The main problem is, on top of Java specs, locale.toString() and
336 // new Locale(locale.toString()).toString() do not return equal() strings in
337 // many cases, because the constructor takes the only string as the language
338 // code. So : new Locale("en", "US").toString() => "en_US"
339 // And : new Locale("en_US").toString() => "en_us"
340 if (null == localeStr)
341 return Locale.getDefault();
342 String[] brokenDownLocale = localeStr.split("_", 3);
343 // split may not return a 0-length array.
344 if (1 == brokenDownLocale.length) {
345 return new Locale(brokenDownLocale[0]);
346 } else if (2 == brokenDownLocale.length) {
347 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
348 } else {
349 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
350 }
351 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700352
Elliott Hughes7253df32014-09-02 17:10:14 -0700353 /** Formats the ratio of amount/total as a percentage. */
354 public static String formatPercentage(long amount, long total) {
355 return formatPercentage(((double) amount) / total);
356 }
357
358 /** Formats an integer from 0..100 as a percentage. */
359 public static String formatPercentage(int percentage) {
360 return formatPercentage(((double) percentage) / 100.0);
361 }
362
363 /** Formats a double from 0.0..1.0 as a percentage. */
364 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700365 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700366 }
367
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900368 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
369 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
370 }
371
Amith Yamasania4379d62011-07-22 10:34:58 -0700372 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700373 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700374 }
375
376 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900377 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
378 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700379 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700380 }
381
382 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
383 final Intent intent = batteryChangedIntent;
384
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900385 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
386 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
387 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700388 String statusString;
389 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700390 int resId;
391 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
392 resId = R.string.battery_info_status_charging_ac;
393 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
394 resId = R.string.battery_info_status_charging_usb;
395 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
396 resId = R.string.battery_info_status_charging_wireless;
397 } else {
398 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700399 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700400 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700401 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
402 statusString = res.getString(R.string.battery_info_status_discharging);
403 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
404 statusString = res.getString(R.string.battery_info_status_not_charging);
405 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
406 statusString = res.getString(R.string.battery_info_status_full);
407 } else {
408 statusString = res.getString(R.string.battery_info_status_unknown);
409 }
410
411 return statusString;
412 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700413
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800414 public static void forcePrepareCustomPreferencesList(
415 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
416 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
417 list.setClipToPadding(false);
418 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
419 }
420
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700421 /**
422 * Prepare a custom preferences layout, moving padding to {@link ListView}
423 * when outside scrollbars are requested. Usually used to display
424 * {@link ListView} and {@link TabWidget} with correct padding.
425 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700426 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800427 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700428 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700429 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700430 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700431 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700432 final int paddingBottom = res.getDimensionPixelSize(
433 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700434
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700435 if (parent instanceof PreferenceFrameLayout) {
436 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
437
438 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
439 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
440 } else {
441 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
442 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700443 }
444 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700445
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700446 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700447 final Resources res = view.getResources();
448 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700449
450 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
451 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700452 final int paddingBottom = res.getDimensionPixelSize(
453 com.android.internal.R.dimen.preference_fragment_padding_bottom);
454
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700455 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700456 }
457
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700458 /**
459 * Return string resource that best describes combination of tethering
460 * options available on this device.
461 */
462 public static int getTetheringLabel(ConnectivityManager cm) {
463 String[] usbRegexs = cm.getTetherableUsbRegexs();
464 String[] wifiRegexs = cm.getTetherableWifiRegexs();
465 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
466
467 boolean usbAvailable = usbRegexs.length != 0;
468 boolean wifiAvailable = wifiRegexs.length != 0;
469 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
470
471 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
472 return R.string.tether_settings_title_all;
473 } else if (wifiAvailable && usbAvailable) {
474 return R.string.tether_settings_title_all;
475 } else if (wifiAvailable && bluetoothAvailable) {
476 return R.string.tether_settings_title_all;
477 } else if (wifiAvailable) {
478 return R.string.tether_settings_title_wifi;
479 } else if (usbAvailable && bluetoothAvailable) {
480 return R.string.tether_settings_title_usb_bluetooth;
481 } else if (usbAvailable) {
482 return R.string.tether_settings_title_usb;
483 } else {
484 return R.string.tether_settings_title_bluetooth;
485 }
486 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700487
488 /* Used by UserSettings as well. Call this on a non-ui thread. */
489 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
490 Uri contactUri = Profile.CONTENT_URI;
491
492 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
493 context.getContentResolver(),
494 contactUri, true);
495 // If there's no profile photo, assign a default avatar
496 if (avatarDataStream == null) {
497 return false;
498 }
499 int userId = user != null ? user.id : UserHandle.myUserId();
500 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700501 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
502 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700503 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700504 avatarDataStream.close();
505 } catch (IOException ioe) { }
506 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700507 }
508
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700509 public static String getMeProfileName(Context context, boolean full) {
510 if (full) {
511 return getProfileDisplayName(context);
512 } else {
513 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700514 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700515 }
516
517 private static String getShorterNameIfPossible(Context context) {
518 final String given = getLocalProfileGivenName(context);
519 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
520 }
521
522 private static String getLocalProfileGivenName(Context context) {
523 final ContentResolver cr = context.getContentResolver();
524
525 // Find the raw contact ID for the local ME profile raw contact.
526 final long localRowProfileId;
527 final Cursor localRawProfile = cr.query(
528 Profile.CONTENT_RAW_CONTACTS_URI,
529 new String[] {RawContacts._ID},
530 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
531 RawContacts.ACCOUNT_NAME + " IS NULL",
532 null, null);
533 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700534
535 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700536 if (!localRawProfile.moveToFirst()) {
537 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700538 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700539 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700540 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700541 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700542 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700543
544 // Find the structured name for the raw contact.
545 final Cursor structuredName = cr.query(
546 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
547 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
548 CommonDataKinds.StructuredName.FAMILY_NAME},
549 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
550 null, null);
551 if (structuredName == null) return null;
552
553 try {
554 if (!structuredName.moveToFirst()) {
555 return null;
556 }
557 String partialName = structuredName.getString(0);
558 if (TextUtils.isEmpty(partialName)) {
559 partialName = structuredName.getString(1);
560 }
561 return partialName;
562 } finally {
563 structuredName.close();
564 }
565 }
566
567 private static final String getProfileDisplayName(Context context) {
568 final ContentResolver cr = context.getContentResolver();
569 final Cursor profile = cr.query(Profile.CONTENT_URI,
570 new String[] {Profile.DISPLAY_NAME}, null, null, null);
571 if (profile == null) return null;
572
573 try {
574 if (!profile.moveToFirst()) {
575 return null;
576 }
577 return profile.getString(0);
578 } finally {
579 profile.close();
580 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700581 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700582
583 /** Not global warming, it's global change warning. */
584 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
585 final Runnable positiveAction) {
586 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
587 builder.setTitle(titleResId);
588 builder.setMessage(R.string.global_change_warning);
589 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
590 @Override
591 public void onClick(DialogInterface dialog, int which) {
592 positiveAction.run();
593 }
594 });
595 builder.setNegativeButton(android.R.string.cancel, null);
596
597 return builder.create();
598 }
599
600 public static boolean hasMultipleUsers(Context context) {
601 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
602 .getUsers().size() > 1;
603 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604
605 /**
606 * Start a new instance of the activity, showing only the given fragment.
607 * When launched in this mode, the given preference fragment will be instantiated and fill the
608 * entire activity.
609 *
610 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000611 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700612 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700613 * @param resultTo Option fragment that should receive the result of the activity launch.
614 * @param resultRequestCode If resultTo is non-null, this is the request code in which
615 * to report the result.
616 * @param titleResId resource id for the String to display for the title of this set
617 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700618 * @param title String to display for the title of this set of preferences.
619 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000620 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100621 Fragment resultTo, int resultRequestCode, int titleResId,
622 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700623 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100624 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
625 }
626
627 /**
628 * Start a new instance of the activity, showing only the given fragment.
629 * When launched in this mode, the given preference fragment will be instantiated and fill the
630 * entire activity.
631 *
632 * @param context The context.
633 * @param fragmentName The name of the fragment to display.
634 * @param args Optional arguments to supply to the fragment.
635 * @param resultTo Option fragment that should receive the result of the activity launch.
636 * @param resultRequestCode If resultTo is non-null, this is the request code in which
637 * to report the result.
638 * @param titleResPackageName Optional package name for the resource id of the title.
639 * @param titleResId resource id for the String to display for the title of this set
640 * of preferences.
641 * @param title String to display for the title of this set of preferences.
642 */
643 public static void startWithFragment(Context context, String fragmentName, Bundle args,
644 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
645 CharSequence title) {
646 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
647 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700648 }
649
650 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100651 Fragment resultTo, int resultRequestCode, int titleResId,
652 CharSequence title, boolean isShortcut) {
653 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
654 null /* titleResPackageName */, titleResId, title, isShortcut);
655 if (resultTo == null) {
656 context.startActivity(intent);
657 } else {
658 resultTo.startActivityForResult(intent, resultRequestCode);
659 }
660 }
661
662 public static void startWithFragment(Context context, String fragmentName, Bundle args,
663 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
664 CharSequence title, boolean isShortcut) {
665 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
666 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700667 if (resultTo == null) {
668 context.startActivity(intent);
669 } else {
670 resultTo.startActivityForResult(intent, resultRequestCode);
671 }
672 }
673
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100674 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100675 int titleResId, CharSequence title, boolean isShortcut,
676 UserHandle userHandle) {
677 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
678 null /* titleResPackageName */, titleResId, title, isShortcut);
679 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
680 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
681 context.startActivityAsUser(intent, userHandle);
682 }
683
684 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
685 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
686 UserHandle userHandle) {
687 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
688 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100689 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
690 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100691 context.startActivityAsUser(intent, userHandle);
692 }
693
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700694 /**
695 * Build an Intent to launch a new activity showing the selected fragment.
696 * The implementation constructs an Intent that re-launches the current activity with the
697 * appropriate arguments to display the fragment.
698 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700699 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700700 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000701 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700702 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100703 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700704 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700705 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700706 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700707 * @return Returns an Intent that can be launched to display the given
708 * fragment.
709 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000710 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100711 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
712 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700713 Intent intent = new Intent(Intent.ACTION_MAIN);
714 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000715 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700716 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100717 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
718 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700719 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700720 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700721 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700722 return intent;
723 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100724
725 /**
726 * Returns the managed profile of the current user or null if none found.
727 */
728 public static UserHandle getManagedProfile(UserManager userManager) {
729 List<UserHandle> userProfiles = userManager.getUserProfiles();
730 final int count = userProfiles.size();
731 for (int i = 0; i < count; i++) {
732 final UserHandle profile = userProfiles.get(i);
733 if (profile.getIdentifier() == userManager.getUserHandle()) {
734 continue;
735 }
736 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
737 if (userInfo.isManagedProfile()) {
738 return profile;
739 }
740 }
741 return null;
742 }
743
744 /**
745 * Returns true if the current profile is a managed one.
746 */
747 public static boolean isManagedProfile(UserManager userManager) {
748 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
749 return currentUser.isManagedProfile();
750 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100751
752 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500753 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100754 *
755 * <p> The adapter can be used to populate a spinner that switches between the Settings
756 * app on the different profiles.
757 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500758 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100759 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500760 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100761 Context context) {
762 List<UserHandle> userProfiles = userManager.getUserProfiles();
763 if (userProfiles.size() < 2) {
764 return null;
765 }
766
767 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
768 // The first option should be the current profile
769 userProfiles.remove(myUserHandle);
770 userProfiles.add(0, myUserHandle);
771
Jason Monk2ebc8a02015-02-13 15:23:19 -0500772 return createUserAdapter(userManager, context, userProfiles);
773 }
774
775 public static UserAdapter createUserAdapter(UserManager userManager,
776 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100777 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
778 final int count = userProfiles.size();
779 for (int i = 0; i < count; i++) {
780 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
781 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500782 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100783 }
784
785 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100786 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100787 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100788 * The target user can be either the current user, the user that launched this activity or
789 * the user contained as an extra in the arguments or intent extras.
790 *
791 * Note: This is secure in the sense that it only returns a target user different to the current
792 * one if the app launching this activity is the Settings app itself, running in the same user
793 * 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 +0100794 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100795 public static UserHandle getSecureTargetUser(IBinder activityToken,
796 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
797 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
798 IActivityManager am = ActivityManagerNative.getDefault();
799 try {
800 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
801 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
802
803 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
804 am.getLaunchedFromUid(activityToken)));
805 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
806 // Check it's secure
807 if (isProfileOf(um, launchedFromUser)) {
808 return launchedFromUser;
809 }
810 }
811 UserHandle extrasUser = intentExtras != null
812 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
813 if (extrasUser != null && !extrasUser.equals(currentUser)) {
814 // Check it's secure
815 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
816 return extrasUser;
817 }
818 }
819 UserHandle argumentsUser = arguments != null
820 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
821 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
822 // Check it's secure
823 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
824 return argumentsUser;
825 }
826 }
827 } catch (RemoteException e) {
828 // Should not happen
829 Log.v(TAG, "Could not talk to activity manager.", e);
830 }
831 return currentUser;
832 }
833
834 /**
835 * Returns the target user for a Settings activity.
836 *
837 * The target user can be either the current user, the user that launched this activity or
838 * the user contained as an extra in the arguments or intent extras.
839 *
840 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
841 * possible.
842 *
843 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
844 */
845 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
846 @Nullable Bundle intentExtras) {
847 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
848 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100849 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100850 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
851 am.getLaunchedFromUid(activityToken)));
852 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
853 return launchedFromUser;
854 }
855 UserHandle extrasUser = intentExtras != null
856 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
857 if (extrasUser != null && !extrasUser.equals(currentUser)) {
858 return extrasUser;
859 }
860 UserHandle argumentsUser = arguments != null
861 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
862 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
863 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100864 }
865 } catch (RemoteException e) {
866 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100867 Log.v(TAG, "Could not talk to activity manager.", e);
868 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100869 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100870 return currentUser;
871 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100872
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100873 /**
874 * Returns true if the user provided is in the same profiles group as the current user.
875 */
876 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
877 if (um == null || otherUser == null) return false;
878 return (UserHandle.myUserId() == otherUser.getIdentifier())
879 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100880 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530881
Andres Moralesce249fe2014-07-07 16:58:16 -0700882
883 /**
884 * Returns whether or not this device is able to be OEM unlocked.
885 */
886 static boolean isOemUnlockEnabled(Context context) {
887 PersistentDataBlockManager manager =(PersistentDataBlockManager)
888 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
889 return manager.getOemUnlockEnabled();
890 }
891
892 /**
893 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
894 * devices allow users to flash other OSes to them.
895 */
896 static void setOemUnlockEnabled(Context context, boolean enabled) {
897 PersistentDataBlockManager manager =(PersistentDataBlockManager)
898 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
899 manager.setOemUnlockEnabled(enabled);
900 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100901
902 /**
903 * Returns a circular icon for a user.
904 */
905 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000906 if (user.isManagedProfile()) {
907 // We use predefined values for managed profiles
908 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
909 com.android.internal.R.drawable.ic_corp_icon);
910 return CircleFramedDrawable.getInstance(context, b);
911 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100912 if (user.iconPath != null) {
913 Bitmap icon = um.getUserIcon(user.id);
914 if (icon != null) {
915 return CircleFramedDrawable.getInstance(context, icon);
916 }
917 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000918 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
919 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100920 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700921
922 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000923 * Returns a label for the user, in the form of "User: user name" or "Work profile".
924 */
925 public static String getUserLabel(Context context, UserInfo info) {
926 if (info.isManagedProfile()) {
927 // We use predefined values for managed profiles
928 return context.getString(R.string.managed_user_title);
929 }
930 String name = info != null ? info.name : null;
931 if (name == null && info != null) {
932 name = Integer.toString(info.id);
933 } else if (info == null) {
934 name = context.getString(R.string.unknown);
935 }
936 return context.getResources().getString(R.string.running_process_item_user_label, name);
937 }
938
939 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700940 * Return whether or not the user should have a SIM Cards option in Settings.
941 * TODO: Change back to returning true if count is greater than one after testing.
942 * TODO: See bug 16533525.
943 */
944 public static boolean showSimCardTile(Context context) {
945 final TelephonyManager tm =
946 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
947
PauloftheWestdbd03822014-12-04 11:56:35 -0800948 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700949 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200950
951 /**
952 * Determine whether a package is a "system package", in which case certain things (like
953 * disabling notifications or disabling the package altogether) should be disallowed.
954 */
955 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
956 if (sSystemSignature == null) {
957 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
958 }
959 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
960 }
961
962 private static Signature[] sSystemSignature;
963
964 private static Signature getFirstSignature(PackageInfo pkg) {
965 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
966 return pkg.signatures[0];
967 }
968 return null;
969 }
970
971 private static Signature getSystemSignature(PackageManager pm) {
972 try {
973 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
974 return getFirstSignature(sys);
975 } catch (NameNotFoundException e) {
976 }
977 return null;
978 }
979
Elliott Hughes7253df32014-09-02 17:10:14 -0700980 /**
981 * Returns elapsed time for the given millis, in the following format:
982 * 2d 5h 40m 29s
983 * @param context the application context
984 * @param millis the elapsed time in milli seconds
985 * @param withSeconds include seconds?
986 * @return the formatted elapsed time
987 */
988 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
989 StringBuilder sb = new StringBuilder();
990 int seconds = (int) Math.floor(millis / 1000);
991 if (!withSeconds) {
992 // Round up.
993 seconds += 30;
994 }
995
996 int days = 0, hours = 0, minutes = 0;
997 if (seconds >= SECONDS_PER_DAY) {
998 days = seconds / SECONDS_PER_DAY;
999 seconds -= days * SECONDS_PER_DAY;
1000 }
1001 if (seconds >= SECONDS_PER_HOUR) {
1002 hours = seconds / SECONDS_PER_HOUR;
1003 seconds -= hours * SECONDS_PER_HOUR;
1004 }
1005 if (seconds >= SECONDS_PER_MINUTE) {
1006 minutes = seconds / SECONDS_PER_MINUTE;
1007 seconds -= minutes * SECONDS_PER_MINUTE;
1008 }
1009 if (withSeconds) {
1010 if (days > 0) {
1011 sb.append(context.getString(R.string.battery_history_days,
1012 days, hours, minutes, seconds));
1013 } else if (hours > 0) {
1014 sb.append(context.getString(R.string.battery_history_hours,
1015 hours, minutes, seconds));
1016 } else if (minutes > 0) {
1017 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1018 } else {
1019 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1020 }
1021 } else {
1022 if (days > 0) {
1023 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1024 days, hours, minutes));
1025 } else if (hours > 0) {
1026 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1027 hours, minutes));
1028 } else {
1029 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1030 }
1031 }
1032 return sb.toString();
1033 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001034
1035 /**
Amith Yamasani45f86232014-11-19 17:12:46 -08001036 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1037 * @param userManager Instance of UserManager
1038 * @param checkUser The user to check the existence of.
1039 * @return UserInfo of the user or null for non-existent user.
1040 */
1041 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1042 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1043 final int checkUserId = checkUser.getIdentifier();
1044 for (UserInfo user : users) {
1045 if (user.id == checkUserId) {
1046 return user;
1047 }
1048 }
1049 return null;
1050 }
1051
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001052 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1053 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1054 com.android.internal.R.styleable.Preference,
1055 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1056 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1057 0);
1058 a.recycle();
1059 return inflater.inflate(resId, parent, false);
1060 }
1061
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001062 /**
1063 * Return if we are running low on storage space or not.
1064 *
1065 * @param context The context
1066 * @return true if we are running low on storage space
1067 */
1068 public static boolean isLowStorage(Context context) {
1069 final StorageManager sm = StorageManager.from(context);
1070 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1071 }
1072
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001073 /**
1074 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1075 *
1076 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1077 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1078 */
1079 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1080 Bitmap bitmap = null;
1081 // Try finding the corresponding bitmap in the dark bitmap cache
1082 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1083 if (bitmap == null) {
1084 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1085 // Save it to cache
1086 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1087 }
1088 return bitmap;
1089 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001090
1091 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1092 try {
1093 if (usbManager != null) {
1094 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1095 }
1096 } catch (RemoteException e) {
1097 Log.e(TAG, "mUsbManager.hasDefaults", e);
1098 }
1099 return false;
1100 }
1101
1102 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1103 // Get list of preferred activities
1104 List<ComponentName> prefActList = new ArrayList<>();
1105 // Intent list cannot be null. so pass empty list
1106 List<IntentFilter> intentList = new ArrayList<>();
1107 pm.getPreferredActivities(intentList, prefActList, packageName);
1108 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1109 return prefActList.size() > 0;
1110 }
1111
1112 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1113 IUsbManager usbManager, PackageManager pm, Context context) {
1114 String packageName = appEntry.info.packageName;
1115 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1116 || hasUsbDefaults(usbManager, packageName);
1117 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
1118 boolean hasDomainURLsPreference =
1119 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
1120 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
1121 return context.getString(hasPreferred || hasDomainURLsPreference
1122 ? R.string.launch_defaults_some
1123 : R.string.launch_defaults_none);
1124 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001125
1126 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1127 boolean animate) {
1128 setViewShown(loading, !done, animate);
1129 setViewShown(doneLoading, done, animate);
1130 }
1131
1132 private static void setViewShown(final View view, boolean shown, boolean animate) {
1133 if (animate) {
1134 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1135 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1136 if (shown) {
1137 view.setVisibility(View.VISIBLE);
1138 } else {
1139 animation.setAnimationListener(new AnimationListener() {
1140 @Override
1141 public void onAnimationStart(Animation animation) {
1142 }
1143
1144 @Override
1145 public void onAnimationRepeat(Animation animation) {
1146 }
1147
1148 @Override
1149 public void onAnimationEnd(Animation animation) {
1150 view.setVisibility(View.INVISIBLE);
1151 }
1152 });
1153 }
1154 view.startAnimation(animation);
1155 } else {
1156 view.clearAnimation();
1157 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1158 }
1159 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001160
1161 /**
1162 * Returns the application info of the currently installed MDM package.
1163 */
1164 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1165 DevicePolicyManager dpm =
1166 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1167 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1168 if (mdmPackage == null) {
1169 return null;
1170 }
1171 String mdmPackageName = mdmPackage.getPackageName();
1172 try {
1173 IPackageManager ipm = AppGlobals.getPackageManager();
1174 ApplicationInfo mdmApplicationInfo =
1175 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1176 return mdmApplicationInfo;
1177 } catch (RemoteException e) {
1178 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1179 + ", userId " + profileId, e);
1180 return null;
1181 }
1182 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001183
1184 public static boolean isBandwidthControlEnabled() {
1185 final INetworkManagementService netManager = INetworkManagementService.Stub
1186 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1187 try {
1188 return netManager.isBandwidthControlEnabled();
1189 } catch (RemoteException e) {
1190 return false;
1191 }
1192 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001193}