blob: 468d568a1b3877319e80f8db35a6b83f4b734a09 [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070020import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010021import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070022import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010023import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070025import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010026import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010027import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080028import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070029import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080030import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070031import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080033import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010035import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070036import android.content.pm.IntentFilterVerificationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070039import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070040import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020041import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.content.res.Resources;
44import android.content.res.Resources.NotFoundException;
Jason Monkb5aa73f2015-03-31 12:59:33 -040045import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070046import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070047import android.graphics.Bitmap;
48import android.graphics.BitmapFactory;
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;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070062import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070064import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070065import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070066import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070067import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070068import android.service.persistentdata.PersistentDataBlockManager;
Jason Monk39b46742015-09-10 15:52:51 -040069import android.support.v7.preference.Preference;
70import android.support.v7.preference.PreferenceGroup;
Amith Yamasani60133dd2010-09-11 14:17:31 -070071import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040072import android.text.Spannable;
73import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020074import android.text.TextUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040075import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070076import android.util.ArraySet;
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 Meglio63bbb8e2014-04-23 16:44:30 -070090import com.android.settings.dashboard.DashboardTile;
Tony Mantler67cd6ab2015-06-08 14:41:02 -070091import com.android.settingslib.applications.ApplicationsState;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070092
Amith Yamasaniae47ef42012-09-16 17:53:35 -070093import java.io.IOException;
94import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080095import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070096import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010097import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080098import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070099import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900100import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800101
Tony Mantler67cd6ab2015-06-08 14:41:02 -0700102import static android.content.Intent.EXTRA_USER;
103
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
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700461 /* Used by UserSettings as well. Call this on a non-ui thread. */
462 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
463 Uri contactUri = Profile.CONTENT_URI;
464
465 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
466 context.getContentResolver(),
467 contactUri, true);
468 // If there's no profile photo, assign a default avatar
469 if (avatarDataStream == null) {
470 return false;
471 }
472 int userId = user != null ? user.id : UserHandle.myUserId();
473 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700474 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
475 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700476 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700477 avatarDataStream.close();
478 } catch (IOException ioe) { }
479 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700480 }
481
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700482 public static String getMeProfileName(Context context, boolean full) {
483 if (full) {
484 return getProfileDisplayName(context);
485 } else {
486 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700487 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700488 }
489
490 private static String getShorterNameIfPossible(Context context) {
491 final String given = getLocalProfileGivenName(context);
492 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
493 }
494
495 private static String getLocalProfileGivenName(Context context) {
496 final ContentResolver cr = context.getContentResolver();
497
498 // Find the raw contact ID for the local ME profile raw contact.
499 final long localRowProfileId;
500 final Cursor localRawProfile = cr.query(
501 Profile.CONTENT_RAW_CONTACTS_URI,
502 new String[] {RawContacts._ID},
503 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
504 RawContacts.ACCOUNT_NAME + " IS NULL",
505 null, null);
506 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700507
508 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700509 if (!localRawProfile.moveToFirst()) {
510 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700511 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700512 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700513 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700514 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700515 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700516
517 // Find the structured name for the raw contact.
518 final Cursor structuredName = cr.query(
519 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
520 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
521 CommonDataKinds.StructuredName.FAMILY_NAME},
522 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
523 null, null);
524 if (structuredName == null) return null;
525
526 try {
527 if (!structuredName.moveToFirst()) {
528 return null;
529 }
530 String partialName = structuredName.getString(0);
531 if (TextUtils.isEmpty(partialName)) {
532 partialName = structuredName.getString(1);
533 }
534 return partialName;
535 } finally {
536 structuredName.close();
537 }
538 }
539
540 private static final String getProfileDisplayName(Context context) {
541 final ContentResolver cr = context.getContentResolver();
542 final Cursor profile = cr.query(Profile.CONTENT_URI,
543 new String[] {Profile.DISPLAY_NAME}, null, null, null);
544 if (profile == null) return null;
545
546 try {
547 if (!profile.moveToFirst()) {
548 return null;
549 }
550 return profile.getString(0);
551 } finally {
552 profile.close();
553 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700554 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700555
556 /** Not global warming, it's global change warning. */
557 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
558 final Runnable positiveAction) {
559 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
560 builder.setTitle(titleResId);
561 builder.setMessage(R.string.global_change_warning);
562 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
563 @Override
564 public void onClick(DialogInterface dialog, int which) {
565 positiveAction.run();
566 }
567 });
568 builder.setNegativeButton(android.R.string.cancel, null);
569
570 return builder.create();
571 }
572
573 public static boolean hasMultipleUsers(Context context) {
574 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
575 .getUsers().size() > 1;
576 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700577
578 /**
579 * Start a new instance of the activity, showing only the given fragment.
580 * When launched in this mode, the given preference fragment will be instantiated and fill the
581 * entire activity.
582 *
583 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000584 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700585 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700586 * @param resultTo Option fragment that should receive the result of the activity launch.
587 * @param resultRequestCode If resultTo is non-null, this is the request code in which
588 * to report the result.
589 * @param titleResId resource id for the String to display for the title of this set
590 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700591 * @param title String to display for the title of this set of preferences.
592 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000593 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100594 Fragment resultTo, int resultRequestCode, int titleResId,
595 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700596 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100597 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
598 }
599
600 /**
601 * Start a new instance of the activity, showing only the given fragment.
602 * When launched in this mode, the given preference fragment will be instantiated and fill the
603 * entire activity.
604 *
605 * @param context The context.
606 * @param fragmentName The name of the fragment to display.
607 * @param args Optional arguments to supply to the fragment.
608 * @param resultTo Option fragment that should receive the result of the activity launch.
609 * @param resultRequestCode If resultTo is non-null, this is the request code in which
610 * to report the result.
611 * @param titleResPackageName Optional package name for the resource id of the title.
612 * @param titleResId resource id for the String to display for the title of this set
613 * of preferences.
614 * @param title String to display for the title of this set of preferences.
615 */
616 public static void startWithFragment(Context context, String fragmentName, Bundle args,
617 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
618 CharSequence title) {
619 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
620 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700621 }
622
623 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, boolean isShortcut) {
626 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
627 null /* titleResPackageName */, titleResId, title, isShortcut);
628 if (resultTo == null) {
629 context.startActivity(intent);
630 } else {
631 resultTo.startActivityForResult(intent, resultRequestCode);
632 }
633 }
634
635 public static void startWithFragment(Context context, String fragmentName, Bundle args,
636 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
637 CharSequence title, boolean isShortcut) {
638 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
639 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700640 if (resultTo == null) {
641 context.startActivity(intent);
642 } else {
643 resultTo.startActivityForResult(intent, resultRequestCode);
644 }
645 }
646
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100647 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100648 int titleResId, CharSequence title, boolean isShortcut,
649 UserHandle userHandle) {
650 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
651 null /* titleResPackageName */, titleResId, title, isShortcut);
652 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
653 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
654 context.startActivityAsUser(intent, userHandle);
655 }
656
657 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
658 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
659 UserHandle userHandle) {
660 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
661 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100662 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
663 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100664 context.startActivityAsUser(intent, userHandle);
665 }
666
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700667 /**
668 * Build an Intent to launch a new activity showing the selected fragment.
669 * The implementation constructs an Intent that re-launches the current activity with the
670 * appropriate arguments to display the fragment.
671 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700672 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700673 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000674 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700675 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100676 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700677 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700678 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700679 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700680 * @return Returns an Intent that can be launched to display the given
681 * fragment.
682 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000683 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100684 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
685 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700686 Intent intent = new Intent(Intent.ACTION_MAIN);
687 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000688 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700689 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100690 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
691 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700692 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700693 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700694 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700695 return intent;
696 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100697
698 /**
699 * Returns the managed profile of the current user or null if none found.
700 */
701 public static UserHandle getManagedProfile(UserManager userManager) {
702 List<UserHandle> userProfiles = userManager.getUserProfiles();
703 final int count = userProfiles.size();
704 for (int i = 0; i < count; i++) {
705 final UserHandle profile = userProfiles.get(i);
706 if (profile.getIdentifier() == userManager.getUserHandle()) {
707 continue;
708 }
709 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
710 if (userInfo.isManagedProfile()) {
711 return profile;
712 }
713 }
714 return null;
715 }
716
717 /**
718 * Returns true if the current profile is a managed one.
719 */
720 public static boolean isManagedProfile(UserManager userManager) {
721 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
722 return currentUser.isManagedProfile();
723 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100724
725 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500726 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100727 *
728 * <p> The adapter can be used to populate a spinner that switches between the Settings
729 * app on the different profiles.
730 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500731 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100732 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500733 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100734 Context context) {
735 List<UserHandle> userProfiles = userManager.getUserProfiles();
736 if (userProfiles.size() < 2) {
737 return null;
738 }
739
740 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
741 // The first option should be the current profile
742 userProfiles.remove(myUserHandle);
743 userProfiles.add(0, myUserHandle);
744
Jason Monk2ebc8a02015-02-13 15:23:19 -0500745 return createUserAdapter(userManager, context, userProfiles);
746 }
747
748 public static UserAdapter createUserAdapter(UserManager userManager,
749 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100750 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
751 final int count = userProfiles.size();
752 for (int i = 0; i < count; i++) {
753 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
754 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500755 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100756 }
757
758 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100759 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100760 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100761 * The target user can be either the current user, the user that launched this activity or
762 * the user contained as an extra in the arguments or intent extras.
763 *
764 * Note: This is secure in the sense that it only returns a target user different to the current
765 * one if the app launching this activity is the Settings app itself, running in the same user
766 * 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 +0100767 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100768 public static UserHandle getSecureTargetUser(IBinder activityToken,
769 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
770 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
771 IActivityManager am = ActivityManagerNative.getDefault();
772 try {
773 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
774 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
775
776 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
777 am.getLaunchedFromUid(activityToken)));
778 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
779 // Check it's secure
780 if (isProfileOf(um, launchedFromUser)) {
781 return launchedFromUser;
782 }
783 }
784 UserHandle extrasUser = intentExtras != null
785 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
786 if (extrasUser != null && !extrasUser.equals(currentUser)) {
787 // Check it's secure
788 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
789 return extrasUser;
790 }
791 }
792 UserHandle argumentsUser = arguments != null
793 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
794 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
795 // Check it's secure
796 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
797 return argumentsUser;
798 }
799 }
800 } catch (RemoteException e) {
801 // Should not happen
802 Log.v(TAG, "Could not talk to activity manager.", e);
803 }
804 return currentUser;
805 }
806
807 /**
808 * Returns the target user for a Settings activity.
809 *
810 * The target user can be either the current user, the user that launched this activity or
811 * the user contained as an extra in the arguments or intent extras.
812 *
813 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
814 * possible.
815 *
816 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
817 */
818 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
819 @Nullable Bundle intentExtras) {
820 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
821 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100822 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100823 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
824 am.getLaunchedFromUid(activityToken)));
825 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
826 return launchedFromUser;
827 }
828 UserHandle extrasUser = intentExtras != null
829 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
830 if (extrasUser != null && !extrasUser.equals(currentUser)) {
831 return extrasUser;
832 }
833 UserHandle argumentsUser = arguments != null
834 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
835 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
836 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100837 }
838 } catch (RemoteException e) {
839 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100840 Log.v(TAG, "Could not talk to activity manager.", e);
841 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100842 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100843 return currentUser;
844 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100845
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100846 /**
847 * Returns true if the user provided is in the same profiles group as the current user.
848 */
849 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
850 if (um == null || otherUser == null) return false;
851 return (UserHandle.myUserId() == otherUser.getIdentifier())
852 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100853 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530854
Andres Moralesce249fe2014-07-07 16:58:16 -0700855
856 /**
857 * Returns whether or not this device is able to be OEM unlocked.
858 */
859 static boolean isOemUnlockEnabled(Context context) {
860 PersistentDataBlockManager manager =(PersistentDataBlockManager)
861 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
862 return manager.getOemUnlockEnabled();
863 }
864
865 /**
866 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
867 * devices allow users to flash other OSes to them.
868 */
869 static void setOemUnlockEnabled(Context context, boolean enabled) {
870 PersistentDataBlockManager manager =(PersistentDataBlockManager)
871 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
872 manager.setOemUnlockEnabled(enabled);
873 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100874
875 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700876 * Return whether or not the user should have a SIM Cards option in Settings.
877 * TODO: Change back to returning true if count is greater than one after testing.
878 * TODO: See bug 16533525.
879 */
880 public static boolean showSimCardTile(Context context) {
881 final TelephonyManager tm =
882 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
883
PauloftheWestdbd03822014-12-04 11:56:35 -0800884 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700885 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200886
887 /**
888 * Determine whether a package is a "system package", in which case certain things (like
889 * disabling notifications or disabling the package altogether) should be disallowed.
890 */
891 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
892 if (sSystemSignature == null) {
893 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
894 }
895 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
896 }
897
898 private static Signature[] sSystemSignature;
899
900 private static Signature getFirstSignature(PackageInfo pkg) {
901 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
902 return pkg.signatures[0];
903 }
904 return null;
905 }
906
907 private static Signature getSystemSignature(PackageManager pm) {
908 try {
909 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
910 return getFirstSignature(sys);
911 } catch (NameNotFoundException e) {
912 }
913 return null;
914 }
915
Elliott Hughes7253df32014-09-02 17:10:14 -0700916 /**
917 * Returns elapsed time for the given millis, in the following format:
918 * 2d 5h 40m 29s
919 * @param context the application context
920 * @param millis the elapsed time in milli seconds
921 * @param withSeconds include seconds?
922 * @return the formatted elapsed time
923 */
924 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
925 StringBuilder sb = new StringBuilder();
926 int seconds = (int) Math.floor(millis / 1000);
927 if (!withSeconds) {
928 // Round up.
929 seconds += 30;
930 }
931
932 int days = 0, hours = 0, minutes = 0;
933 if (seconds >= SECONDS_PER_DAY) {
934 days = seconds / SECONDS_PER_DAY;
935 seconds -= days * SECONDS_PER_DAY;
936 }
937 if (seconds >= SECONDS_PER_HOUR) {
938 hours = seconds / SECONDS_PER_HOUR;
939 seconds -= hours * SECONDS_PER_HOUR;
940 }
941 if (seconds >= SECONDS_PER_MINUTE) {
942 minutes = seconds / SECONDS_PER_MINUTE;
943 seconds -= minutes * SECONDS_PER_MINUTE;
944 }
945 if (withSeconds) {
946 if (days > 0) {
947 sb.append(context.getString(R.string.battery_history_days,
948 days, hours, minutes, seconds));
949 } else if (hours > 0) {
950 sb.append(context.getString(R.string.battery_history_hours,
951 hours, minutes, seconds));
952 } else if (minutes > 0) {
953 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
954 } else {
955 sb.append(context.getString(R.string.battery_history_seconds, seconds));
956 }
957 } else {
958 if (days > 0) {
959 sb.append(context.getString(R.string.battery_history_days_no_seconds,
960 days, hours, minutes));
961 } else if (hours > 0) {
962 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
963 hours, minutes));
964 } else {
965 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
966 }
967 }
968 return sb.toString();
969 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800970
971 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800972 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
973 * @param userManager Instance of UserManager
974 * @param checkUser The user to check the existence of.
975 * @return UserInfo of the user or null for non-existent user.
976 */
977 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
978 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
979 final int checkUserId = checkUser.getIdentifier();
980 for (UserInfo user : users) {
981 if (user.id == checkUserId) {
982 return user;
983 }
984 }
985 return null;
986 }
987
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000988 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
989 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
990 com.android.internal.R.styleable.Preference,
991 com.android.internal.R.attr.preferenceCategoryStyle, 0);
992 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
993 0);
994 a.recycle();
995 return inflater.inflate(resId, parent, false);
996 }
997
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800998 /**
999 * Return if we are running low on storage space or not.
1000 *
1001 * @param context The context
1002 * @return true if we are running low on storage space
1003 */
1004 public static boolean isLowStorage(Context context) {
1005 final StorageManager sm = StorageManager.from(context);
1006 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1007 }
1008
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001009 /**
1010 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1011 *
1012 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1013 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1014 */
1015 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1016 Bitmap bitmap = null;
1017 // Try finding the corresponding bitmap in the dark bitmap cache
1018 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1019 if (bitmap == null) {
1020 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1021 // Save it to cache
1022 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1023 }
1024 return bitmap;
1025 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001026
1027 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1028 try {
1029 if (usbManager != null) {
1030 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1031 }
1032 } catch (RemoteException e) {
1033 Log.e(TAG, "mUsbManager.hasDefaults", e);
1034 }
1035 return false;
1036 }
1037
1038 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1039 // Get list of preferred activities
1040 List<ComponentName> prefActList = new ArrayList<>();
1041 // Intent list cannot be null. so pass empty list
1042 List<IntentFilter> intentList = new ArrayList<>();
1043 pm.getPreferredActivities(intentList, prefActList, packageName);
1044 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1045 return prefActList.size() > 0;
1046 }
1047
Christopher Tatea08a2252015-07-01 16:52:43 -07001048 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
1049 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
1050 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
1051
1052 ArraySet<String> result = new ArraySet<>();
1053 if (iviList.size() > 0) {
1054 for (IntentFilterVerificationInfo ivi : iviList) {
1055 for (String host : ivi.getDomains()) {
1056 result.add(host);
1057 }
1058 }
1059 }
1060 if (filters != null && filters.size() > 0) {
1061 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -07001062 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1063 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1064 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -07001065 result.addAll(filter.getHostsList());
1066 }
1067 }
1068 }
1069 return result;
1070 }
1071
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001072 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1073 IUsbManager usbManager, PackageManager pm, Context context) {
1074 String packageName = appEntry.info.packageName;
1075 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1076 || hasUsbDefaults(usbManager, packageName);
1077 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
Christopher Tate90de3be2015-09-08 15:41:08 -07001078 // consider a visible current link-handling state to be any explicitly designated behavior
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001079 boolean hasDomainURLsPreference =
Christopher Tate90de3be2015-09-08 15:41:08 -07001080 status != PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001081 return context.getString(hasPreferred || hasDomainURLsPreference
1082 ? R.string.launch_defaults_some
1083 : R.string.launch_defaults_none);
1084 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001085
1086 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1087 boolean animate) {
1088 setViewShown(loading, !done, animate);
1089 setViewShown(doneLoading, done, animate);
1090 }
1091
1092 private static void setViewShown(final View view, boolean shown, boolean animate) {
1093 if (animate) {
1094 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1095 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1096 if (shown) {
1097 view.setVisibility(View.VISIBLE);
1098 } else {
1099 animation.setAnimationListener(new AnimationListener() {
1100 @Override
1101 public void onAnimationStart(Animation animation) {
1102 }
1103
1104 @Override
1105 public void onAnimationRepeat(Animation animation) {
1106 }
1107
1108 @Override
1109 public void onAnimationEnd(Animation animation) {
1110 view.setVisibility(View.INVISIBLE);
1111 }
1112 });
1113 }
1114 view.startAnimation(animation);
1115 } else {
1116 view.clearAnimation();
1117 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1118 }
1119 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001120
1121 /**
1122 * Returns the application info of the currently installed MDM package.
1123 */
1124 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1125 DevicePolicyManager dpm =
1126 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1127 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1128 if (mdmPackage == null) {
1129 return null;
1130 }
1131 String mdmPackageName = mdmPackage.getPackageName();
1132 try {
1133 IPackageManager ipm = AppGlobals.getPackageManager();
1134 ApplicationInfo mdmApplicationInfo =
1135 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1136 return mdmApplicationInfo;
1137 } catch (RemoteException e) {
1138 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1139 + ", userId " + profileId, e);
1140 return null;
1141 }
1142 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001143
1144 public static boolean isBandwidthControlEnabled() {
1145 final INetworkManagementService netManager = INetworkManagementService.Stub
1146 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1147 try {
1148 return netManager.isBandwidthControlEnabled();
1149 } catch (RemoteException e) {
1150 return false;
1151 }
1152 }
Julia Reynoldsce25af42015-07-08 16:56:31 -04001153
1154 /**
1155 * Returns an accessible SpannableString.
1156 * @param displayText the text to display
1157 * @param accessibileText the text text-to-speech engines should read
1158 */
1159 public static SpannableString createAccessibleSequence(CharSequence displayText,
1160 String accessibileText) {
1161 SpannableString str = new SpannableString(displayText);
1162 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
1163 displayText.length(),
1164 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1165 return str;
1166 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001167
Clara Bayarrife432e82015-10-12 12:07:02 +01001168 /**
1169 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
1170 * belongs to the current user.
1171 *
1172 * @throws SecurityException if the given userId does not belong to the current user group.
1173 */
1174 public static int getSameOwnerUserId(Context context, Bundle bundle) {
1175 if (bundle == null) {
1176 return getEffectiveUserId(context);
1177 }
1178 int userId = bundle.getInt(ChooseLockGeneric.KEY_USER_ID, UserHandle.myUserId());
1179 return getSameOwnerUserId(context, userId);
1180 }
1181
1182 /**
1183 * Returns the given user id if it belongs to the current user.
1184 *
1185 * @throws SecurityException if the given userId does not belong to the current user group.
1186 */
1187 public static int getSameOwnerUserId(Context context, int userId) {
1188 UserManager um = UserManager.get(context);
1189 if (um != null) {
1190 if (um.getUserProfiles().contains(new UserHandle(userId))) {
1191 return userId;
1192 } else {
1193 throw new SecurityException("Given user id " + userId + " does not belong to user "
1194 + UserHandle.myUserId());
1195 }
1196 }
1197 return getEffectiveUserId(context);
1198 }
1199
Andres Morales7bdffd82015-08-04 16:55:00 -07001200 public static int getEffectiveUserId(Context context) {
1201 UserManager um = UserManager.get(context);
1202 if (um != null) {
1203 return um.getCredentialOwnerProfile(UserHandle.myUserId());
1204 } else {
1205 Log.e(TAG, "Unable to acquire UserManager");
1206 return UserHandle.myUserId();
1207 }
1208 }
1209}
1210