blob: 1a9b9a16ccde9340a7e2324f4a1d6cc15d952431 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Sunny Goyalfafca522014-11-03 11:30:01 -080019import android.annotation.TargetApi;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020020import android.app.Activity;
Sunny Goyal594d76d2014-11-06 10:12:54 -080021import android.app.SearchManager;
22import android.appwidget.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020024import android.content.ActivityNotFoundException;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070025import android.content.ComponentName;
Winson Chungaafa03c2010-06-11 17:34:16 -070026import android.content.Context;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020027import android.content.Intent;
Sunny Goyalc5c60ad2014-07-14 12:02:01 -070028import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageInfo;
30import android.content.pm.PackageManager;
31import android.content.pm.PackageManager.NameNotFoundException;
32import android.content.pm.ResolveInfo;
Winson Chungaafa03c2010-06-11 17:34:16 -070033import android.content.res.Resources;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080034import android.graphics.Bitmap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Canvas;
Sunny Goyal95abbb32014-08-04 10:53:22 -070036import android.graphics.Color;
Winson Chungc763c4e2013-07-19 13:49:06 -070037import android.graphics.Matrix;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080038import android.graphics.Paint;
Joe Onoratobf15cb42009-08-07 14:33:40 -070039import android.graphics.PaintFlagsDrawFilter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.graphics.Rect;
Winson Chungaafa03c2010-06-11 17:34:16 -070041import android.graphics.drawable.BitmapDrawable;
42import android.graphics.drawable.Drawable;
43import android.graphics.drawable.PaintDrawable;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -070044import android.os.Build;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020045import android.util.Log;
Sunny Goyal0fe505b2014-08-06 09:55:36 -070046import android.util.Pair;
Sunny Goyal95abbb32014-08-04 10:53:22 -070047import android.util.SparseArray;
Winson Chungc763c4e2013-07-19 13:49:06 -070048import android.view.View;
Michael Jurkaa805e1a2013-08-22 15:00:33 +020049import android.widget.Toast;
Winson Chungc763c4e2013-07-19 13:49:06 -070050
51import java.util.ArrayList;
Sunny Goyal08f72612015-01-05 13:41:43 -080052import java.util.Comparator;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080053
54/**
55 * Various utilities shared amongst the Launcher's classes.
56 */
Mathew Inwood72fbec12013-11-19 15:45:07 +000057public final class Utilities {
Joe Onorato1291a8c2009-09-15 15:07:25 -040058 private static final String TAG = "Launcher.Utilities";
59
The Android Open Source Project31dd5032009-03-03 19:32:27 -080060 private static int sIconWidth = -1;
61 private static int sIconHeight = -1;
62
The Android Open Source Project31dd5032009-03-03 19:32:27 -080063 private static final Rect sOldBounds = new Rect();
Romain Guy89911d22009-09-28 18:48:49 -070064 private static final Canvas sCanvas = new Canvas();
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065
66 static {
67 sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
68 Paint.FILTER_BITMAP_FLAG));
69 }
Joe Onorato6665c0f2009-09-02 15:27:24 -070070 static int sColors[] = { 0xffff0000, 0xff00ff00, 0xff0000ff };
71 static int sColorIndex = 0;
72
Adam Cohen63f1ec02014-08-12 09:23:13 -070073 static int[] sLoc0 = new int[2];
74 static int[] sLoc1 = new int[2];
Michael Jurka7ad868b2013-12-12 15:04:25 +010075
76 // To turn on these properties, type
77 // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
78 static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
79 public static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
80
Joe Onorato6665c0f2009-09-02 15:27:24 -070081 /**
Winson Chung0dbd7342013-10-13 22:46:20 -070082 * Returns a FastBitmapDrawable with the icon, accurately sized.
83 */
Sunny Goyalffe83f12014-08-14 17:39:34 -070084 public static FastBitmapDrawable createIconDrawable(Bitmap icon) {
Winson Chung0dbd7342013-10-13 22:46:20 -070085 FastBitmapDrawable d = new FastBitmapDrawable(icon);
Winson Chung54000492013-10-14 16:29:29 -070086 d.setFilterBitmap(true);
Winson Chung0dbd7342013-10-13 22:46:20 -070087 resizeIconDrawable(d);
88 return d;
89 }
90
91 /**
92 * Resizes an icon drawable to the correct icon size.
93 */
94 static void resizeIconDrawable(Drawable icon) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -070095 icon.setBounds(0, 0, sIconWidth, sIconHeight);
Winson Chung0dbd7342013-10-13 22:46:20 -070096 }
97
Sunny Goyal4bbf4192014-11-11 12:23:59 -080098 public static boolean isPropertyEnabled(String propertyName) {
Michael Jurka7ad868b2013-12-12 15:04:25 +010099 return Log.isLoggable(propertyName, Log.VERBOSE);
100 }
101
102 public static boolean isRotationEnabled(Context c) {
103 boolean enableRotation = sForceEnableRotation ||
104 c.getResources().getBoolean(R.bool.allow_rotation);
105 return enableRotation;
106 }
107
Winson Chung0dbd7342013-10-13 22:46:20 -0700108 /**
Kenny Guyd794a3f2014-09-16 15:17:58 +0100109 * Indicates if the device is running LMP or higher.
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700110 */
Kenny Guyd794a3f2014-09-16 15:17:58 +0100111 public static boolean isLmpOrAbove() {
Brian Parfett1bc1ae62014-12-12 12:30:00 -0800112 return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
Sandeep Siddhartha2efc7d92014-05-16 17:21:15 -0700113 }
114
115 /**
Sunny Goyalb50cc8c2014-10-06 16:23:56 -0700116 * Returns a bitmap suitable for the all apps view. If the package or the resource do not
117 * exist, it returns null.
118 */
119 static Bitmap createIconBitmap(String packageName, String resourceName, IconCache cache,
120 Context context) {
121 PackageManager packageManager = context.getPackageManager();
122 // the resource
123 try {
124 Resources resources = packageManager.getResourcesForApplication(packageName);
125 if (resources != null) {
126 final int id = resources.getIdentifier(resourceName, null, null);
127 return createIconBitmap(
128 resources.getDrawableForDensity(id, cache.getFullResIconDpi()), context);
129 }
130 } catch (Exception e) {
131 // Icon not found.
132 }
133 return null;
134 }
135
136 /**
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700137 * Returns a bitmap which is of the appropriate size to be displayed as an icon
Michael Jurka931dc972011-08-05 15:08:15 -0700138 */
139 static Bitmap createIconBitmap(Bitmap icon, Context context) {
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700140 synchronized (sCanvas) { // we share the statics :-(
141 if (sIconWidth == -1) {
142 initStatics(context);
143 }
Michael Jurka931dc972011-08-05 15:08:15 -0700144 }
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700145 if (sIconWidth == icon.getWidth() && sIconHeight == icon.getHeight()) {
146 return icon;
147 }
148 return createIconBitmap(new BitmapDrawable(context.getResources(), icon), context);
Michael Jurka931dc972011-08-05 15:08:15 -0700149 }
150
151 /**
152 * Returns a bitmap suitable for the all apps view.
Joe Onorato6665c0f2009-09-02 15:27:24 -0700153 */
Mathew Inwood72fbec12013-11-19 15:45:07 +0000154 public static Bitmap createIconBitmap(Drawable icon, Context context) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700155 synchronized (sCanvas) { // we share the statics :-(
156 if (sIconWidth == -1) {
157 initStatics(context);
158 }
159
160 int width = sIconWidth;
161 int height = sIconHeight;
162
Joe Onorato6665c0f2009-09-02 15:27:24 -0700163 if (icon instanceof PaintDrawable) {
164 PaintDrawable painter = (PaintDrawable) icon;
165 painter.setIntrinsicWidth(width);
166 painter.setIntrinsicHeight(height);
167 } else if (icon instanceof BitmapDrawable) {
168 // Ensure the bitmap has a density.
169 BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
170 Bitmap bitmap = bitmapDrawable.getBitmap();
171 if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
172 bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
173 }
174 }
175 int sourceWidth = icon.getIntrinsicWidth();
176 int sourceHeight = icon.getIntrinsicHeight();
Michael Jurka931dc972011-08-05 15:08:15 -0700177 if (sourceWidth > 0 && sourceHeight > 0) {
Winson Chung5f8afe62013-08-12 16:19:28 -0700178 // Scale the icon proportionally to the icon dimensions
179 final float ratio = (float) sourceWidth / sourceHeight;
180 if (sourceWidth > sourceHeight) {
181 height = (int) (width / ratio);
182 } else if (sourceHeight > sourceWidth) {
183 width = (int) (height * ratio);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700184 }
185 }
186
187 // no intrinsic size --> use default size
Sunny Goyal2fce90c2014-10-07 12:01:58 -0700188 int textureWidth = sIconWidth;
189 int textureHeight = sIconHeight;
Joe Onorato6665c0f2009-09-02 15:27:24 -0700190
191 final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
192 Bitmap.Config.ARGB_8888);
193 final Canvas canvas = sCanvas;
194 canvas.setBitmap(bitmap);
195
196 final int left = (textureWidth-width) / 2;
197 final int top = (textureHeight-height) / 2;
198
Michael Jurka3a9fced2012-04-13 14:44:29 -0700199 @SuppressWarnings("all") // suppress dead code warning
200 final boolean debug = false;
201 if (debug) {
Joe Onorato6665c0f2009-09-02 15:27:24 -0700202 // draw a big box for the icon for debugging
203 canvas.drawColor(sColors[sColorIndex]);
204 if (++sColorIndex >= sColors.length) sColorIndex = 0;
205 Paint debugPaint = new Paint();
206 debugPaint.setColor(0xffcccc00);
207 canvas.drawRect(left, top, left+width, top+height, debugPaint);
208 }
209
210 sOldBounds.set(icon.getBounds());
211 icon.setBounds(left, top, left+width, top+height);
212 icon.draw(canvas);
213 icon.setBounds(sOldBounds);
Adam Cohenaaf473c2011-08-03 12:02:47 -0700214 canvas.setBitmap(null);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700215
216 return bitmap;
217 }
218 }
219
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800220 /**
Winson Chungc763c4e2013-07-19 13:49:06 -0700221 * Given a coordinate relative to the descendant, find the coordinate in a parent view's
222 * coordinates.
223 *
224 * @param descendant The descendant to which the passed coordinate is relative.
225 * @param root The root view to make the coordinates relative to.
226 * @param coord The coordinate that we want mapped.
227 * @param includeRootScroll Whether or not to account for the scroll of the descendant:
228 * sometimes this is relevant as in a child's coordinates within the descendant.
229 * @return The factor by which this descendant is scaled relative to this DragLayer. Caution
230 * this scale factor is assumed to be equal in X and Y, and so if at any point this
231 * assumption fails, we will need to return a pair of scale factors.
232 */
233 public static float getDescendantCoordRelativeToParent(View descendant, View root,
234 int[] coord, boolean includeRootScroll) {
235 ArrayList<View> ancestorChain = new ArrayList<View>();
236
237 float[] pt = {coord[0], coord[1]};
238
239 View v = descendant;
240 while(v != root && v != null) {
241 ancestorChain.add(v);
242 v = (View) v.getParent();
243 }
244 ancestorChain.add(root);
245
246 float scale = 1.0f;
247 int count = ancestorChain.size();
248 for (int i = 0; i < count; i++) {
249 View v0 = ancestorChain.get(i);
Winson Chungc763c4e2013-07-19 13:49:06 -0700250 // For TextViews, scroll has a meaning which relates to the text position
251 // which is very strange... ignore the scroll.
252 if (v0 != descendant || includeRootScroll) {
253 pt[0] -= v0.getScrollX();
254 pt[1] -= v0.getScrollY();
255 }
256
257 v0.getMatrix().mapPoints(pt);
258 pt[0] += v0.getLeft();
259 pt[1] += v0.getTop();
260 scale *= v0.getScaleX();
261 }
262
263 coord[0] = (int) Math.round(pt[0]);
264 coord[1] = (int) Math.round(pt[1]);
265 return scale;
266 }
267
268 /**
269 * Inverse of {@link #getDescendantCoordRelativeToSelf(View, int[])}.
270 */
271 public static float mapCoordInSelfToDescendent(View descendant, View root,
272 int[] coord) {
273 ArrayList<View> ancestorChain = new ArrayList<View>();
274
275 float[] pt = {coord[0], coord[1]};
276
277 View v = descendant;
278 while(v != root) {
279 ancestorChain.add(v);
280 v = (View) v.getParent();
281 }
282 ancestorChain.add(root);
283
284 float scale = 1.0f;
285 Matrix inverse = new Matrix();
286 int count = ancestorChain.size();
287 for (int i = count - 1; i >= 0; i--) {
288 View ancestor = ancestorChain.get(i);
289 View next = i > 0 ? ancestorChain.get(i-1) : null;
290
291 pt[0] += ancestor.getScrollX();
292 pt[1] += ancestor.getScrollY();
293
294 if (next != null) {
295 pt[0] -= next.getLeft();
296 pt[1] -= next.getTop();
297 next.getMatrix().invert(inverse);
298 inverse.mapPoints(pt);
299 scale *= next.getScaleX();
300 }
301 }
302
303 coord[0] = (int) Math.round(pt[0]);
304 coord[1] = (int) Math.round(pt[1]);
305 return scale;
306 }
307
Jason Monk02dd7ae2014-04-15 15:23:31 -0400308 /**
309 * Utility method to determine whether the given point, in local coordinates,
310 * is inside the view, where the area of the view is expanded by the slop factor.
311 * This method is called while processing touch-move events to determine if the event
312 * is still within the view.
313 */
314 public static boolean pointInView(View v, float localX, float localY, float slop) {
315 return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) &&
316 localY < (v.getHeight() + slop);
317 }
318
Joe Onorato6665c0f2009-09-02 15:27:24 -0700319 private static void initStatics(Context context) {
320 final Resources resources = context.getResources();
Michael Jurkac9a96192010-11-01 11:52:08 -0700321 sIconWidth = sIconHeight = (int) resources.getDimension(R.dimen.app_icon_size);
Joe Onorato6665c0f2009-09-02 15:27:24 -0700322 }
323
Winson Chung5f8afe62013-08-12 16:19:28 -0700324 public static void setIconSize(int widthPx) {
325 sIconWidth = sIconHeight = widthPx;
Winson Chung97d85d22011-04-13 11:27:36 -0700326 }
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200327
Winson Chung3a6e7f32013-10-09 15:50:52 -0700328 public static void scaleRect(Rect r, float scale) {
329 if (scale != 1.0f) {
330 r.left = (int) (r.left * scale + 0.5f);
331 r.top = (int) (r.top * scale + 0.5f);
332 r.right = (int) (r.right * scale + 0.5f);
333 r.bottom = (int) (r.bottom * scale + 0.5f);
334 }
335 }
336
Adam Cohen63f1ec02014-08-12 09:23:13 -0700337 public static int[] getCenterDeltaInScreenSpace(View v0, View v1, int[] delta) {
338 v0.getLocationInWindow(sLoc0);
339 v1.getLocationInWindow(sLoc1);
340
341 sLoc0[0] += (v0.getMeasuredWidth() * v0.getScaleX()) / 2;
342 sLoc0[1] += (v0.getMeasuredHeight() * v0.getScaleY()) / 2;
343 sLoc1[0] += (v1.getMeasuredWidth() * v1.getScaleX()) / 2;
344 sLoc1[1] += (v1.getMeasuredHeight() * v1.getScaleY()) / 2;
345
346 if (delta == null) {
347 delta = new int[2];
348 }
349
350 delta[0] = sLoc1[0] - sLoc0[0];
351 delta[1] = sLoc1[1] - sLoc0[1];
352
353 return delta;
354 }
355
Winson Chung3a6e7f32013-10-09 15:50:52 -0700356 public static void scaleRectAboutCenter(Rect r, float scale) {
357 int cx = r.centerX();
358 int cy = r.centerY();
359 r.offset(-cx, -cy);
360 Utilities.scaleRect(r, scale);
361 r.offset(cx, cy);
362 }
363
Michael Jurkaa805e1a2013-08-22 15:00:33 +0200364 public static void startActivityForResultSafely(
365 Activity activity, Intent intent, int requestCode) {
366 try {
367 activity.startActivityForResult(intent, requestCode);
368 } catch (ActivityNotFoundException e) {
369 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
370 } catch (SecurityException e) {
371 Toast.makeText(activity, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
372 Log.e(TAG, "Launcher does not have the permission to launch " + intent +
373 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
374 "or use the exported attribute for this activity.", e);
375 }
376 }
Sunny Goyalc5c60ad2014-07-14 12:02:01 -0700377
378 static boolean isSystemApp(Context context, Intent intent) {
379 PackageManager pm = context.getPackageManager();
380 ComponentName cn = intent.getComponent();
381 String packageName = null;
382 if (cn == null) {
383 ResolveInfo info = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
384 if ((info != null) && (info.activityInfo != null)) {
385 packageName = info.activityInfo.packageName;
386 }
387 } else {
388 packageName = cn.getPackageName();
389 }
390 if (packageName != null) {
391 try {
392 PackageInfo info = pm.getPackageInfo(packageName, 0);
393 return (info != null) && (info.applicationInfo != null) &&
394 ((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
395 } catch (NameNotFoundException e) {
396 return false;
397 }
398 } else {
399 return false;
400 }
401 }
Sunny Goyal95abbb32014-08-04 10:53:22 -0700402
403 /**
404 * This picks a dominant color, looking for high-saturation, high-value, repeated hues.
405 * @param bitmap The bitmap to scan
406 * @param samples The approximate max number of samples to use.
407 */
408 static int findDominantColorByHue(Bitmap bitmap, int samples) {
409 final int height = bitmap.getHeight();
410 final int width = bitmap.getWidth();
411 int sampleStride = (int) Math.sqrt((height * width) / samples);
412 if (sampleStride < 1) {
413 sampleStride = 1;
414 }
415
416 // This is an out-param, for getting the hsv values for an rgb
417 float[] hsv = new float[3];
418
419 // First get the best hue, by creating a histogram over 360 hue buckets,
420 // where each pixel contributes a score weighted by saturation, value, and alpha.
421 float[] hueScoreHistogram = new float[360];
422 float highScore = -1;
423 int bestHue = -1;
424
425 for (int y = 0; y < height; y += sampleStride) {
426 for (int x = 0; x < width; x += sampleStride) {
427 int argb = bitmap.getPixel(x, y);
428 int alpha = 0xFF & (argb >> 24);
429 if (alpha < 0x80) {
430 // Drop mostly-transparent pixels.
431 continue;
432 }
433 // Remove the alpha channel.
434 int rgb = argb | 0xFF000000;
435 Color.colorToHSV(rgb, hsv);
436 // Bucket colors by the 360 integer hues.
437 int hue = (int) hsv[0];
438 if (hue < 0 || hue >= hueScoreHistogram.length) {
439 // Defensively avoid array bounds violations.
440 continue;
441 }
442 float score = hsv[1] * hsv[2];
443 hueScoreHistogram[hue] += score;
444 if (hueScoreHistogram[hue] > highScore) {
445 highScore = hueScoreHistogram[hue];
446 bestHue = hue;
447 }
448 }
449 }
450
451 SparseArray<Float> rgbScores = new SparseArray<Float>();
452 int bestColor = 0xff000000;
453 highScore = -1;
454 // Go back over the RGB colors that match the winning hue,
455 // creating a histogram of weighted s*v scores, for up to 100*100 [s,v] buckets.
456 // The highest-scoring RGB color wins.
457 for (int y = 0; y < height; y += sampleStride) {
458 for (int x = 0; x < width; x += sampleStride) {
459 int rgb = bitmap.getPixel(x, y) | 0xff000000;
460 Color.colorToHSV(rgb, hsv);
461 int hue = (int) hsv[0];
462 if (hue == bestHue) {
463 float s = hsv[1];
464 float v = hsv[2];
465 int bucket = (int) (s * 100) + (int) (v * 10000);
466 // Score by cumulative saturation * value.
467 float score = s * v;
468 Float oldTotal = rgbScores.get(bucket);
469 float newTotal = oldTotal == null ? score : oldTotal + score;
470 rgbScores.put(bucket, newTotal);
471 if (newTotal > highScore) {
472 highScore = newTotal;
473 // All the colors in the winning bucket are very similar. Last in wins.
474 bestColor = rgb;
475 }
476 }
477 }
478 }
479 return bestColor;
480 }
Sunny Goyal0fe505b2014-08-06 09:55:36 -0700481
482 /*
483 * Finds a system apk which had a broadcast receiver listening to a particular action.
484 * @param action intent action used to find the apk
485 * @return a pair of apk package name and the resources.
486 */
487 static Pair<String, Resources> findSystemApk(String action, PackageManager pm) {
488 final Intent intent = new Intent(action);
489 for (ResolveInfo info : pm.queryBroadcastReceivers(intent, 0)) {
490 if (info.activityInfo != null &&
491 (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
492 final String packageName = info.activityInfo.packageName;
493 try {
494 final Resources res = pm.getResourcesForApplication(packageName);
495 return Pair.create(packageName, res);
496 } catch (NameNotFoundException e) {
497 Log.w(TAG, "Failed to find resources for " + packageName);
498 }
499 }
500 }
501 return null;
502 }
Sunny Goyalfafca522014-11-03 11:30:01 -0800503
504 @TargetApi(Build.VERSION_CODES.KITKAT)
505 public static boolean isViewAttachedToWindow(View v) {
506 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
507 return v.isAttachedToWindow();
508 } else {
509 // A proxy call which returns null, if the view is not attached to the window.
510 return v.getKeyDispatcherState() != null;
511 }
512 }
Sunny Goyal594d76d2014-11-06 10:12:54 -0800513
514 /**
515 * Returns a widget with category {@link AppWidgetProviderInfo#WIDGET_CATEGORY_SEARCHBOX}
516 * provided by the same package which is set to be global search activity.
517 * If widgetCategory is not supported, or no such widget is found, returns the first widget
518 * provided by the package.
519 */
520 @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
521 public static AppWidgetProviderInfo getSearchWidgetProvider(Context context) {
522 SearchManager searchManager =
523 (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
524 ComponentName searchComponent = searchManager.getGlobalSearchActivity();
525 if (searchComponent == null) return null;
526 String providerPkg = searchComponent.getPackageName();
527
528 AppWidgetProviderInfo defaultWidgetForSearchPackage = null;
529
530 AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
531 for (AppWidgetProviderInfo info : appWidgetManager.getInstalledProviders()) {
532 if (info.provider.getPackageName().equals(providerPkg)) {
533 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
534 if ((info.widgetCategory & AppWidgetProviderInfo.WIDGET_CATEGORY_SEARCHBOX) != 0) {
535 return info;
536 } else if (defaultWidgetForSearchPackage == null) {
537 defaultWidgetForSearchPackage = info;
538 }
539 } else {
540 return info;
541 }
542 }
543 }
544 return defaultWidgetForSearchPackage;
545 }
Sunny Goyal08f72612015-01-05 13:41:43 -0800546
547 public static final Comparator<ItemInfo> RANK_COMPARATOR = new Comparator<ItemInfo>() {
548
549 @Override
550 public int compare(ItemInfo lhs, ItemInfo rhs) {
551 return lhs.rank - rhs.rank;
552 }
553 };
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800554}