blob: d3d515e51891013794cc46011d0935ecac438637 [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import static android.content.Intent.EXTRA_USER;
20
21import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070022import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010023import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010025import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070026import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070027import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010028import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010029import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080030import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070031import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070033import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080035import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080036import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010037import android.content.pm.IPackageManager;
Dan Sandlerb58b5122014-09-02 18:31:49 +020038import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080039import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070040import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070041import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020042import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070043import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020044import android.content.res.Resources;
45import android.content.res.Resources.NotFoundException;
Jason Monkb5aa73f2015-03-31 12:59:33 -040046import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070048import android.graphics.Bitmap;
49import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020050import android.graphics.drawable.Drawable;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080051import android.hardware.usb.IUsbManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080052import android.net.ConnectivityManager;
53import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070054import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070055import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020056import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010057import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040058import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010059import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040060import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070061import android.os.UserHandle;
62import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080063import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080064import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070065import android.preference.PreferenceFrameLayout;
66import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070067import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070068import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070069import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070070import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070071import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070072import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080073import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080074import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070075import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020076import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010077import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000078import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000079import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070080import android.view.View;
81import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040082import android.view.animation.Animation;
83import android.view.animation.Animation.AnimationListener;
84import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070085import android.widget.ListView;
86import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010087
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010088import com.android.internal.util.UserIcons;
Jason Monk2ebc8a02015-02-13 15:23:19 -050089import com.android.settings.UserAdapter.UserDetails;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080090import com.android.settings.applications.ApplicationsState;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070091import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010092import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070093
Amith Yamasaniae47ef42012-09-16 17:53:35 -070094import java.io.IOException;
95import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080096import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070097import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010098import java.util.ArrayList;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080099import java.util.Collections;
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800100import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700101import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900102import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800103
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700104public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100105 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100106
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800107 /**
108 * Set the preference's title to the matching activity's label.
109 */
110 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
111
112 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900113 * The opacity level of a disabled icon.
114 */
115 public static final float DISABLED_ALPHA = 0.4f;
116
117 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700118 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
119 * 1 is most bad (red), the last value is least bad (green).
120 */
121 public static final int[] BADNESS_COLORS = new int[] {
122 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
123 0xfffabf2c, 0xff679e37, 0xff0a7f42
124 };
125
126 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200127 * Name of the meta-data item that should be set in the AndroidManifest.xml
128 * to specify the icon that should be displayed for the preference.
129 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500130 public static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200131
132 /**
133 * Name of the meta-data item that should be set in the AndroidManifest.xml
134 * to specify the title that should be displayed for the preference.
135 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500136 public static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200137
138 /**
139 * Name of the meta-data item that should be set in the AndroidManifest.xml
140 * to specify the summary text that should be displayed for the preference.
141 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500142 public static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200143
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100144 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
145
Elliott Hughes7253df32014-09-02 17:10:14 -0700146 private static final int SECONDS_PER_MINUTE = 60;
147 private static final int SECONDS_PER_HOUR = 60 * 60;
148 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
149
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000150 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
151
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200152 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800153 * Finds a matching activity for a preference's intent. If a matching
154 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800155 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800156 * @param context The context.
157 * @param parentPreferenceGroup The preference group that contains the
158 * preference whose intent is being resolved.
159 * @param preferenceKey The key of the preference whose intent is being
160 * resolved.
161 * @param flags 0 or one or more of
162 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
163 * .
164 * @return Whether an activity was found. If false, the preference was
165 * removed.
166 */
167 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
168 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800169
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800170 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
171 if (preference == null) {
172 return false;
173 }
Ying Wanga7188322010-01-04 18:45:10 -0800174
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800175 Intent intent = preference.getIntent();
176 if (intent != null) {
177 // Find the activity that is in the system image
178 PackageManager pm = context.getPackageManager();
179 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
180 int listSize = list.size();
181 for (int i = 0; i < listSize; i++) {
182 ResolveInfo resolveInfo = list.get(i);
183 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
184 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800185
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800186 // Replace the intent with this specific activity
187 preference.setIntent(new Intent().setClassName(
188 resolveInfo.activityInfo.packageName,
189 resolveInfo.activityInfo.name));
190
191 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
192 // Set the preference title to the activity's label
193 preference.setTitle(resolveInfo.loadLabel(pm));
194 }
Ying Wanga7188322010-01-04 18:45:10 -0800195
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800196 return true;
197 }
198 }
199 }
200
201 // Did not find a matching activity, so remove the preference
202 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800203
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900204 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800205 }
Ying Wanga7188322010-01-04 18:45:10 -0800206
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700207 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700208 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700209
210 Intent intent = tile.intent;
211 if (intent != null) {
212 // Find the activity that is in the system image
213 PackageManager pm = context.getPackageManager();
Jason Monk2ebc8a02015-02-13 15:23:19 -0500214 List<ResolveInfo> list = tile.userHandle.size() != 0
215 ? pm.queryIntentActivitiesAsUser(intent, PackageManager.GET_META_DATA,
216 tile.userHandle.get(0).getIdentifier())
217 : pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700218 int listSize = list.size();
219 for (int i = 0; i < listSize; i++) {
220 ResolveInfo resolveInfo = list.get(i);
221 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
222 != 0) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500223 int icon = 0;
224 CharSequence title = null;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700225 String summary = null;
226
227 // Get the activity's meta-data
228 try {
229 Resources res = pm.getResourcesForApplication(
230 resolveInfo.activityInfo.packageName);
231 Bundle metaData = resolveInfo.activityInfo.metaData;
232
233 if (res != null && metaData != null) {
Jason Monk2ebc8a02015-02-13 15:23:19 -0500234 if (metaData.containsKey(META_DATA_PREFERENCE_ICON)) {
235 icon = metaData.getInt(META_DATA_PREFERENCE_ICON);
236 }
237 if (metaData.containsKey(META_DATA_PREFERENCE_TITLE)) {
238 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
239 }
240 if (metaData.containsKey(META_DATA_PREFERENCE_SUMMARY)) {
241 summary = res.getString(
242 metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
243 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700244 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500245 } catch (NameNotFoundException | NotFoundException e) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700246 // Ignore
247 }
248
249 // Set the preference title to the activity's label if no
250 // meta-data is found
251 if (TextUtils.isEmpty(title)) {
252 title = resolveInfo.loadLabel(pm).toString();
253 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500254 if (icon == 0) {
255 icon = resolveInfo.activityInfo.icon;
256 }
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700257
258 // Set icon, title and summary for the preference
Jason Monk2ebc8a02015-02-13 15:23:19 -0500259 tile.iconRes = icon;
260 tile.iconPkg = resolveInfo.activityInfo.packageName;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700261 tile.title = title;
262 tile.summary = summary;
263 // Replace the intent with this specific activity
264 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
265 resolveInfo.activityInfo.name);
266
267 return true;
268 }
269 }
270 }
271
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700272 return false;
273 }
274
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200275 /**
Ying Wanga7188322010-01-04 18:45:10 -0800276 * Returns true if Monkey is running.
277 */
278 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700279 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800280 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700281
282 /**
283 * Returns whether the device is voice-capable (meaning, it is also a phone).
284 */
285 public static boolean isVoiceCapable(Context context) {
286 TelephonyManager telephony =
287 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
288 return telephony != null && telephony.isVoiceCapable();
289 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800290
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700291 public static boolean isWifiOnly(Context context) {
292 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
293 Context.CONNECTIVITY_SERVICE);
294 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800295 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800296
297 /**
298 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
299 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900300 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800301 */
302 public static String getWifiIpAddresses(Context context) {
303 ConnectivityManager cm = (ConnectivityManager)
304 context.getSystemService(Context.CONNECTIVITY_SERVICE);
305 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700306 return formatIpAddresses(prop);
307 }
308
309 /**
310 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
311 * addresses.
312 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900313 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700314 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900315 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700316 LinkProperties prop = cm.getActiveLinkProperties();
317 return formatIpAddresses(prop);
318 }
319
320 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800321 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900322 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800323 // If there are no entries, return null
324 if (!iter.hasNext()) return null;
325 // Concatenate all available addresses, comma separated
326 String addresses = "";
327 while (iter.hasNext()) {
328 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900329 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800330 }
331 return addresses;
332 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900333
334 public static Locale createLocaleFromString(String localeStr) {
335 // TODO: is there a better way to actually construct a locale that will match?
336 // The main problem is, on top of Java specs, locale.toString() and
337 // new Locale(locale.toString()).toString() do not return equal() strings in
338 // many cases, because the constructor takes the only string as the language
339 // code. So : new Locale("en", "US").toString() => "en_US"
340 // And : new Locale("en_US").toString() => "en_us"
341 if (null == localeStr)
342 return Locale.getDefault();
343 String[] brokenDownLocale = localeStr.split("_", 3);
344 // split may not return a 0-length array.
345 if (1 == brokenDownLocale.length) {
346 return new Locale(brokenDownLocale[0]);
347 } else if (2 == brokenDownLocale.length) {
348 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
349 } else {
350 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
351 }
352 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700353
Elliott Hughes7253df32014-09-02 17:10:14 -0700354 /** Formats the ratio of amount/total as a percentage. */
355 public static String formatPercentage(long amount, long total) {
356 return formatPercentage(((double) amount) / total);
357 }
358
359 /** Formats an integer from 0..100 as a percentage. */
360 public static String formatPercentage(int percentage) {
361 return formatPercentage(((double) percentage) / 100.0);
362 }
363
364 /** Formats a double from 0.0..1.0 as a percentage. */
365 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700366 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700367 }
368
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900369 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
370 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
371 }
372
Amith Yamasania4379d62011-07-22 10:34:58 -0700373 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700374 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700375 }
376
377 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900378 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
379 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700380 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700381 }
382
383 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
384 final Intent intent = batteryChangedIntent;
385
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900386 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
387 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
388 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700389 String statusString;
390 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700391 int resId;
392 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
393 resId = R.string.battery_info_status_charging_ac;
394 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
395 resId = R.string.battery_info_status_charging_usb;
396 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
397 resId = R.string.battery_info_status_charging_wireless;
398 } else {
399 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700400 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700401 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700402 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
403 statusString = res.getString(R.string.battery_info_status_discharging);
404 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
405 statusString = res.getString(R.string.battery_info_status_not_charging);
406 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
407 statusString = res.getString(R.string.battery_info_status_full);
408 } else {
409 statusString = res.getString(R.string.battery_info_status_unknown);
410 }
411
412 return statusString;
413 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700414
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800415 public static void forcePrepareCustomPreferencesList(
416 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
417 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
418 list.setClipToPadding(false);
419 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
420 }
421
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700422 /**
423 * Prepare a custom preferences layout, moving padding to {@link ListView}
424 * when outside scrollbars are requested. Usually used to display
425 * {@link ListView} and {@link TabWidget} with correct padding.
426 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700427 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800428 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700429 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700430 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700431 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700432 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700433 final int paddingBottom = res.getDimensionPixelSize(
434 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700435
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700436 if (parent instanceof PreferenceFrameLayout) {
437 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
438
439 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
440 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
441 } else {
442 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
443 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700444 }
445 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700446
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700447 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700448 final Resources res = view.getResources();
449 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700450
451 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
452 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700453 final int paddingBottom = res.getDimensionPixelSize(
454 com.android.internal.R.dimen.preference_fragment_padding_bottom);
455
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700456 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700457 }
458
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700459 /**
460 * Return string resource that best describes combination of tethering
461 * options available on this device.
462 */
463 public static int getTetheringLabel(ConnectivityManager cm) {
464 String[] usbRegexs = cm.getTetherableUsbRegexs();
465 String[] wifiRegexs = cm.getTetherableWifiRegexs();
466 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
467
468 boolean usbAvailable = usbRegexs.length != 0;
469 boolean wifiAvailable = wifiRegexs.length != 0;
470 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
471
472 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
473 return R.string.tether_settings_title_all;
474 } else if (wifiAvailable && usbAvailable) {
475 return R.string.tether_settings_title_all;
476 } else if (wifiAvailable && bluetoothAvailable) {
477 return R.string.tether_settings_title_all;
478 } else if (wifiAvailable) {
479 return R.string.tether_settings_title_wifi;
480 } else if (usbAvailable && bluetoothAvailable) {
481 return R.string.tether_settings_title_usb_bluetooth;
482 } else if (usbAvailable) {
483 return R.string.tether_settings_title_usb;
484 } else {
485 return R.string.tether_settings_title_bluetooth;
486 }
487 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700488
489 /* Used by UserSettings as well. Call this on a non-ui thread. */
490 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
491 Uri contactUri = Profile.CONTENT_URI;
492
493 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
494 context.getContentResolver(),
495 contactUri, true);
496 // If there's no profile photo, assign a default avatar
497 if (avatarDataStream == null) {
498 return false;
499 }
500 int userId = user != null ? user.id : UserHandle.myUserId();
501 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700502 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
503 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700504 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700505 avatarDataStream.close();
506 } catch (IOException ioe) { }
507 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700508 }
509
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700510 public static String getMeProfileName(Context context, boolean full) {
511 if (full) {
512 return getProfileDisplayName(context);
513 } else {
514 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700515 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700516 }
517
518 private static String getShorterNameIfPossible(Context context) {
519 final String given = getLocalProfileGivenName(context);
520 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
521 }
522
523 private static String getLocalProfileGivenName(Context context) {
524 final ContentResolver cr = context.getContentResolver();
525
526 // Find the raw contact ID for the local ME profile raw contact.
527 final long localRowProfileId;
528 final Cursor localRawProfile = cr.query(
529 Profile.CONTENT_RAW_CONTACTS_URI,
530 new String[] {RawContacts._ID},
531 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
532 RawContacts.ACCOUNT_NAME + " IS NULL",
533 null, null);
534 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700535
536 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700537 if (!localRawProfile.moveToFirst()) {
538 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700539 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700540 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700541 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700542 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700543 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700544
545 // Find the structured name for the raw contact.
546 final Cursor structuredName = cr.query(
547 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
548 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
549 CommonDataKinds.StructuredName.FAMILY_NAME},
550 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
551 null, null);
552 if (structuredName == null) return null;
553
554 try {
555 if (!structuredName.moveToFirst()) {
556 return null;
557 }
558 String partialName = structuredName.getString(0);
559 if (TextUtils.isEmpty(partialName)) {
560 partialName = structuredName.getString(1);
561 }
562 return partialName;
563 } finally {
564 structuredName.close();
565 }
566 }
567
568 private static final String getProfileDisplayName(Context context) {
569 final ContentResolver cr = context.getContentResolver();
570 final Cursor profile = cr.query(Profile.CONTENT_URI,
571 new String[] {Profile.DISPLAY_NAME}, null, null, null);
572 if (profile == null) return null;
573
574 try {
575 if (!profile.moveToFirst()) {
576 return null;
577 }
578 return profile.getString(0);
579 } finally {
580 profile.close();
581 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700582 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700583
584 /** Not global warming, it's global change warning. */
585 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
586 final Runnable positiveAction) {
587 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
588 builder.setTitle(titleResId);
589 builder.setMessage(R.string.global_change_warning);
590 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
591 @Override
592 public void onClick(DialogInterface dialog, int which) {
593 positiveAction.run();
594 }
595 });
596 builder.setNegativeButton(android.R.string.cancel, null);
597
598 return builder.create();
599 }
600
601 public static boolean hasMultipleUsers(Context context) {
602 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
603 .getUsers().size() > 1;
604 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700605
606 /**
607 * Start a new instance of the activity, showing only the given fragment.
608 * When launched in this mode, the given preference fragment will be instantiated and fill the
609 * entire activity.
610 *
611 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000612 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700613 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700614 * @param resultTo Option fragment that should receive the result of the activity launch.
615 * @param resultRequestCode If resultTo is non-null, this is the request code in which
616 * to report the result.
617 * @param titleResId resource id for the String to display for the title of this set
618 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700619 * @param title String to display for the title of this set of preferences.
620 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000621 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100622 Fragment resultTo, int resultRequestCode, int titleResId,
623 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700624 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100625 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
626 }
627
628 /**
629 * Start a new instance of the activity, showing only the given fragment.
630 * When launched in this mode, the given preference fragment will be instantiated and fill the
631 * entire activity.
632 *
633 * @param context The context.
634 * @param fragmentName The name of the fragment to display.
635 * @param args Optional arguments to supply to the fragment.
636 * @param resultTo Option fragment that should receive the result of the activity launch.
637 * @param resultRequestCode If resultTo is non-null, this is the request code in which
638 * to report the result.
639 * @param titleResPackageName Optional package name for the resource id of the title.
640 * @param titleResId resource id for the String to display for the title of this set
641 * of preferences.
642 * @param title String to display for the title of this set of preferences.
643 */
644 public static void startWithFragment(Context context, String fragmentName, Bundle args,
645 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
646 CharSequence title) {
647 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
648 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700649 }
650
651 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100652 Fragment resultTo, int resultRequestCode, int titleResId,
653 CharSequence title, boolean isShortcut) {
654 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
655 null /* titleResPackageName */, titleResId, title, isShortcut);
656 if (resultTo == null) {
657 context.startActivity(intent);
658 } else {
659 resultTo.startActivityForResult(intent, resultRequestCode);
660 }
661 }
662
663 public static void startWithFragment(Context context, String fragmentName, Bundle args,
664 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
665 CharSequence title, boolean isShortcut) {
666 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
667 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700668 if (resultTo == null) {
669 context.startActivity(intent);
670 } else {
671 resultTo.startActivityForResult(intent, resultRequestCode);
672 }
673 }
674
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100675 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100676 int titleResId, CharSequence title, boolean isShortcut,
677 UserHandle userHandle) {
678 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
679 null /* titleResPackageName */, titleResId, title, isShortcut);
680 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
681 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
682 context.startActivityAsUser(intent, userHandle);
683 }
684
685 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
686 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
687 UserHandle userHandle) {
688 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
689 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100690 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
691 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100692 context.startActivityAsUser(intent, userHandle);
693 }
694
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700695 /**
696 * Build an Intent to launch a new activity showing the selected fragment.
697 * The implementation constructs an Intent that re-launches the current activity with the
698 * appropriate arguments to display the fragment.
699 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700700 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700701 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000702 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700703 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100704 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700705 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700706 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700707 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700708 * @return Returns an Intent that can be launched to display the given
709 * fragment.
710 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000711 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100712 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
713 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700714 Intent intent = new Intent(Intent.ACTION_MAIN);
715 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000716 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700717 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100718 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
719 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700720 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700721 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700722 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700723 return intent;
724 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100725
726 /**
727 * Returns the managed profile of the current user or null if none found.
728 */
729 public static UserHandle getManagedProfile(UserManager userManager) {
730 List<UserHandle> userProfiles = userManager.getUserProfiles();
731 final int count = userProfiles.size();
732 for (int i = 0; i < count; i++) {
733 final UserHandle profile = userProfiles.get(i);
734 if (profile.getIdentifier() == userManager.getUserHandle()) {
735 continue;
736 }
737 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
738 if (userInfo.isManagedProfile()) {
739 return profile;
740 }
741 }
742 return null;
743 }
744
745 /**
746 * Returns true if the current profile is a managed one.
747 */
748 public static boolean isManagedProfile(UserManager userManager) {
749 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
750 return currentUser.isManagedProfile();
751 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100752
753 /**
Jason Monk2ebc8a02015-02-13 15:23:19 -0500754 * Creates a {@link UserAdapter} if there is more than one profile on the device.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100755 *
756 * <p> The adapter can be used to populate a spinner that switches between the Settings
757 * app on the different profiles.
758 *
Jason Monk2ebc8a02015-02-13 15:23:19 -0500759 * @return a {@link UserAdapter} or null if there is only one profile.
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100760 */
Jason Monk2ebc8a02015-02-13 15:23:19 -0500761 public static UserAdapter createUserSpinnerAdapter(UserManager userManager,
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100762 Context context) {
763 List<UserHandle> userProfiles = userManager.getUserProfiles();
764 if (userProfiles.size() < 2) {
765 return null;
766 }
767
768 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
769 // The first option should be the current profile
770 userProfiles.remove(myUserHandle);
771 userProfiles.add(0, myUserHandle);
772
Jason Monk2ebc8a02015-02-13 15:23:19 -0500773 return createUserAdapter(userManager, context, userProfiles);
774 }
775
776 public static UserAdapter createUserAdapter(UserManager userManager,
777 Context context, List<UserHandle> userProfiles) {
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100778 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
779 final int count = userProfiles.size();
780 for (int i = 0; i < count; i++) {
781 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
782 }
Jason Monk2ebc8a02015-02-13 15:23:19 -0500783 return new UserAdapter(context, userDetails);
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100784 }
785
786 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100787 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100788 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100789 * The target user can be either the current user, the user that launched this activity or
790 * the user contained as an extra in the arguments or intent extras.
791 *
792 * Note: This is secure in the sense that it only returns a target user different to the current
793 * one if the app launching this activity is the Settings app itself, running in the same user
794 * 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 +0100795 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100796 public static UserHandle getSecureTargetUser(IBinder activityToken,
797 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
798 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
799 IActivityManager am = ActivityManagerNative.getDefault();
800 try {
801 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
802 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
803
804 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
805 am.getLaunchedFromUid(activityToken)));
806 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
807 // Check it's secure
808 if (isProfileOf(um, launchedFromUser)) {
809 return launchedFromUser;
810 }
811 }
812 UserHandle extrasUser = intentExtras != null
813 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
814 if (extrasUser != null && !extrasUser.equals(currentUser)) {
815 // Check it's secure
816 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
817 return extrasUser;
818 }
819 }
820 UserHandle argumentsUser = arguments != null
821 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
822 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
823 // Check it's secure
824 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
825 return argumentsUser;
826 }
827 }
828 } catch (RemoteException e) {
829 // Should not happen
830 Log.v(TAG, "Could not talk to activity manager.", e);
831 }
832 return currentUser;
833 }
834
835 /**
836 * Returns the target user for a Settings activity.
837 *
838 * The target user can be either the current user, the user that launched this activity or
839 * the user contained as an extra in the arguments or intent extras.
840 *
841 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
842 * possible.
843 *
844 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
845 */
846 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
847 @Nullable Bundle intentExtras) {
848 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
849 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100850 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100851 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
852 am.getLaunchedFromUid(activityToken)));
853 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
854 return launchedFromUser;
855 }
856 UserHandle extrasUser = intentExtras != null
857 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
858 if (extrasUser != null && !extrasUser.equals(currentUser)) {
859 return extrasUser;
860 }
861 UserHandle argumentsUser = arguments != null
862 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
863 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
864 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100865 }
866 } catch (RemoteException e) {
867 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100868 Log.v(TAG, "Could not talk to activity manager.", e);
869 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100870 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100871 return currentUser;
872 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100873
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100874 /**
875 * Returns true if the user provided is in the same profiles group as the current user.
876 */
877 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
878 if (um == null || otherUser == null) return false;
879 return (UserHandle.myUserId() == otherUser.getIdentifier())
880 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100881 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530882
Andres Moralesce249fe2014-07-07 16:58:16 -0700883
884 /**
885 * Returns whether or not this device is able to be OEM unlocked.
886 */
887 static boolean isOemUnlockEnabled(Context context) {
888 PersistentDataBlockManager manager =(PersistentDataBlockManager)
889 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
890 return manager.getOemUnlockEnabled();
891 }
892
893 /**
894 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
895 * devices allow users to flash other OSes to them.
896 */
897 static void setOemUnlockEnabled(Context context, boolean enabled) {
898 PersistentDataBlockManager manager =(PersistentDataBlockManager)
899 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
900 manager.setOemUnlockEnabled(enabled);
901 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100902
903 /**
904 * Returns a circular icon for a user.
905 */
906 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000907 if (user.isManagedProfile()) {
908 // We use predefined values for managed profiles
909 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
910 com.android.internal.R.drawable.ic_corp_icon);
911 return CircleFramedDrawable.getInstance(context, b);
912 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100913 if (user.iconPath != null) {
914 Bitmap icon = um.getUserIcon(user.id);
915 if (icon != null) {
916 return CircleFramedDrawable.getInstance(context, icon);
917 }
918 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000919 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
920 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100921 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700922
923 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000924 * Returns a label for the user, in the form of "User: user name" or "Work profile".
925 */
926 public static String getUserLabel(Context context, UserInfo info) {
927 if (info.isManagedProfile()) {
928 // We use predefined values for managed profiles
929 return context.getString(R.string.managed_user_title);
930 }
931 String name = info != null ? info.name : null;
932 if (name == null && info != null) {
933 name = Integer.toString(info.id);
934 } else if (info == null) {
935 name = context.getString(R.string.unknown);
936 }
937 return context.getResources().getString(R.string.running_process_item_user_label, name);
938 }
939
940 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700941 * Return whether or not the user should have a SIM Cards option in Settings.
942 * TODO: Change back to returning true if count is greater than one after testing.
943 * TODO: See bug 16533525.
944 */
945 public static boolean showSimCardTile(Context context) {
946 final TelephonyManager tm =
947 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
948
PauloftheWestdbd03822014-12-04 11:56:35 -0800949 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700950 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200951
952 /**
953 * Determine whether a package is a "system package", in which case certain things (like
954 * disabling notifications or disabling the package altogether) should be disallowed.
955 */
956 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
957 if (sSystemSignature == null) {
958 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
959 }
960 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
961 }
962
963 private static Signature[] sSystemSignature;
964
965 private static Signature getFirstSignature(PackageInfo pkg) {
966 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
967 return pkg.signatures[0];
968 }
969 return null;
970 }
971
972 private static Signature getSystemSignature(PackageManager pm) {
973 try {
974 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
975 return getFirstSignature(sys);
976 } catch (NameNotFoundException e) {
977 }
978 return null;
979 }
980
Elliott Hughes7253df32014-09-02 17:10:14 -0700981 /**
982 * Returns elapsed time for the given millis, in the following format:
983 * 2d 5h 40m 29s
984 * @param context the application context
985 * @param millis the elapsed time in milli seconds
986 * @param withSeconds include seconds?
987 * @return the formatted elapsed time
988 */
989 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
990 StringBuilder sb = new StringBuilder();
991 int seconds = (int) Math.floor(millis / 1000);
992 if (!withSeconds) {
993 // Round up.
994 seconds += 30;
995 }
996
997 int days = 0, hours = 0, minutes = 0;
998 if (seconds >= SECONDS_PER_DAY) {
999 days = seconds / SECONDS_PER_DAY;
1000 seconds -= days * SECONDS_PER_DAY;
1001 }
1002 if (seconds >= SECONDS_PER_HOUR) {
1003 hours = seconds / SECONDS_PER_HOUR;
1004 seconds -= hours * SECONDS_PER_HOUR;
1005 }
1006 if (seconds >= SECONDS_PER_MINUTE) {
1007 minutes = seconds / SECONDS_PER_MINUTE;
1008 seconds -= minutes * SECONDS_PER_MINUTE;
1009 }
1010 if (withSeconds) {
1011 if (days > 0) {
1012 sb.append(context.getString(R.string.battery_history_days,
1013 days, hours, minutes, seconds));
1014 } else if (hours > 0) {
1015 sb.append(context.getString(R.string.battery_history_hours,
1016 hours, minutes, seconds));
1017 } else if (minutes > 0) {
1018 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
1019 } else {
1020 sb.append(context.getString(R.string.battery_history_seconds, seconds));
1021 }
1022 } else {
1023 if (days > 0) {
1024 sb.append(context.getString(R.string.battery_history_days_no_seconds,
1025 days, hours, minutes));
1026 } else if (hours > 0) {
1027 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1028 hours, minutes));
1029 } else {
1030 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1031 }
1032 }
1033 return sb.toString();
1034 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001035
1036 /**
Amith Yamasani45f86232014-11-19 17:12:46 -08001037 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1038 * @param userManager Instance of UserManager
1039 * @param checkUser The user to check the existence of.
1040 * @return UserInfo of the user or null for non-existent user.
1041 */
1042 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1043 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1044 final int checkUserId = checkUser.getIdentifier();
1045 for (UserInfo user : users) {
1046 if (user.id == checkUserId) {
1047 return user;
1048 }
1049 }
1050 return null;
1051 }
1052
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001053 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1054 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1055 com.android.internal.R.styleable.Preference,
1056 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1057 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1058 0);
1059 a.recycle();
1060 return inflater.inflate(resId, parent, false);
1061 }
1062
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001063 /**
1064 * Return if we are running low on storage space or not.
1065 *
1066 * @param context The context
1067 * @return true if we are running low on storage space
1068 */
1069 public static boolean isLowStorage(Context context) {
1070 final StorageManager sm = StorageManager.from(context);
1071 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1072 }
1073
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001074 /**
1075 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1076 *
1077 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1078 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1079 */
1080 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1081 Bitmap bitmap = null;
1082 // Try finding the corresponding bitmap in the dark bitmap cache
1083 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1084 if (bitmap == null) {
1085 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1086 // Save it to cache
1087 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1088 }
1089 return bitmap;
1090 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -08001091
1092 public static boolean hasUsbDefaults(IUsbManager usbManager, String packageName) {
1093 try {
1094 if (usbManager != null) {
1095 return usbManager.hasDefaults(packageName, UserHandle.myUserId());
1096 }
1097 } catch (RemoteException e) {
1098 Log.e(TAG, "mUsbManager.hasDefaults", e);
1099 }
1100 return false;
1101 }
1102
1103 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
1104 // Get list of preferred activities
1105 List<ComponentName> prefActList = new ArrayList<>();
1106 // Intent list cannot be null. so pass empty list
1107 List<IntentFilter> intentList = new ArrayList<>();
1108 pm.getPreferredActivities(intentList, prefActList, packageName);
1109 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
1110 return prefActList.size() > 0;
1111 }
1112
1113 public static CharSequence getLaunchByDeafaultSummary(ApplicationsState.AppEntry appEntry,
1114 IUsbManager usbManager, PackageManager pm, Context context) {
1115 String packageName = appEntry.info.packageName;
1116 boolean hasPreferred = hasPreferredActivities(pm, packageName)
1117 || hasUsbDefaults(usbManager, packageName);
1118 int status = pm.getIntentVerificationStatus(packageName, UserHandle.myUserId());
1119 boolean hasDomainURLsPreference =
1120 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) ||
1121 (status == PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER);
1122 return context.getString(hasPreferred || hasDomainURLsPreference
1123 ? R.string.launch_defaults_some
1124 : R.string.launch_defaults_none);
1125 }
Jason Monkb5aa73f2015-03-31 12:59:33 -04001126
1127 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
1128 boolean animate) {
1129 setViewShown(loading, !done, animate);
1130 setViewShown(doneLoading, done, animate);
1131 }
1132
1133 private static void setViewShown(final View view, boolean shown, boolean animate) {
1134 if (animate) {
1135 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
1136 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
1137 if (shown) {
1138 view.setVisibility(View.VISIBLE);
1139 } else {
1140 animation.setAnimationListener(new AnimationListener() {
1141 @Override
1142 public void onAnimationStart(Animation animation) {
1143 }
1144
1145 @Override
1146 public void onAnimationRepeat(Animation animation) {
1147 }
1148
1149 @Override
1150 public void onAnimationEnd(Animation animation) {
1151 view.setVisibility(View.INVISIBLE);
1152 }
1153 });
1154 }
1155 view.startAnimation(animation);
1156 } else {
1157 view.clearAnimation();
1158 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
1159 }
1160 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001161
1162 /**
1163 * Returns the application info of the currently installed MDM package.
1164 */
1165 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
1166 DevicePolicyManager dpm =
1167 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
1168 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
1169 if (mdmPackage == null) {
1170 return null;
1171 }
1172 String mdmPackageName = mdmPackage.getPackageName();
1173 try {
1174 IPackageManager ipm = AppGlobals.getPackageManager();
1175 ApplicationInfo mdmApplicationInfo =
1176 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
1177 return mdmApplicationInfo;
1178 } catch (RemoteException e) {
1179 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
1180 + ", userId " + profileId, e);
1181 return null;
1182 }
1183 }
Jason Monkb45e27b2015-05-20 13:35:43 -04001184
1185 public static boolean isBandwidthControlEnabled() {
1186 final INetworkManagementService netManager = INetworkManagementService.Stub
1187 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1188 try {
1189 return netManager.isBandwidthControlEnabled();
1190 } catch (RemoteException e) {
1191 return false;
1192 }
1193 }
Sudheer Shankabc956302015-04-09 12:19:53 +01001194}