blob: f442f2210bbbae50e80018a67814b2f7954a6a1e [file] [log] [blame]
Michael Kolb8872c232013-01-29 10:33:22 -08001/*
2 * Copyright (C) 2009 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
Angus Kongb50b5cb2013-08-09 14:55:20 -070017package com.android.camera.util;
Michael Kolb8872c232013-01-29 10:33:22 -080018
Michael Kolb8872c232013-01-29 10:33:22 -080019import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.admin.DevicePolicyManager;
22import android.content.ActivityNotFoundException;
Sascha Haeberlingfae11a12013-08-15 14:29:49 -070023import android.content.ComponentName;
Michael Kolb8872c232013-01-29 10:33:22 -080024import android.content.ContentResolver;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.graphics.Bitmap;
29import android.graphics.BitmapFactory;
30import android.graphics.Matrix;
31import android.graphics.Point;
32import android.graphics.Rect;
33import android.graphics.RectF;
34import android.hardware.Camera;
35import android.hardware.Camera.CameraInfo;
36import android.hardware.Camera.Parameters;
37import android.hardware.Camera.Size;
38import android.location.Location;
39import android.net.Uri;
Angus Kong4f795b82013-09-16 14:25:35 -070040import android.os.Handler;
Michael Kolb8872c232013-01-29 10:33:22 -080041import android.os.ParcelFileDescriptor;
42import android.telephony.TelephonyManager;
43import android.util.DisplayMetrics;
Michael Kolb8872c232013-01-29 10:33:22 -080044import android.util.Log;
45import android.util.TypedValue;
Michael Kolb8872c232013-01-29 10:33:22 -080046import android.view.OrientationEventListener;
47import android.view.Surface;
48import android.view.View;
49import android.view.WindowManager;
50import android.view.animation.AlphaAnimation;
51import android.view.animation.Animation;
Angus Kongb40738a2013-06-03 14:55:34 -070052import android.widget.Toast;
Michael Kolb8872c232013-01-29 10:33:22 -080053
Sascha Haeberlingb7639c62013-09-09 14:42:43 -070054import com.android.camera.CameraActivity;
Angus Kongb50b5cb2013-08-09 14:55:20 -070055import com.android.camera.CameraDisabledException;
Angus Kongb50b5cb2013-08-09 14:55:20 -070056import com.android.camera.CameraHolder;
57import com.android.camera.CameraManager;
Sascha Haeberling37f36112013-08-06 14:31:52 -070058import com.android.camera2.R;
Michael Kolb8872c232013-01-29 10:33:22 -080059
Sascha Haeberling638e6f02013-09-18 14:28:51 -070060import java.io.Closeable;
61import java.io.IOException;
62import java.lang.reflect.Method;
63import java.text.SimpleDateFormat;
64import java.util.Date;
65import java.util.List;
66import java.util.Locale;
67import java.util.StringTokenizer;
68
Michael Kolb8872c232013-01-29 10:33:22 -080069/**
70 * Collection of utility functions used in this package.
71 */
Angus Kongb50b5cb2013-08-09 14:55:20 -070072public class CameraUtil {
Michael Kolb8872c232013-01-29 10:33:22 -080073 private static final String TAG = "Util";
74
ztenghui16a35202013-09-23 11:35:36 -070075 // For calculate the best fps range for still image capture.
76 private final static int MAX_PREVIEW_FPS_TIMES_1000 = 400000;
77 private final static int PREFERRED_PREVIEW_FPS_TIMES_1000 = 30000;
78
Angus Kongb50b5cb2013-08-09 14:55:20 -070079 // For creating crop intents.
80 public static final String KEY_RETURN_DATA = "return-data";
81 public static final String KEY_SHOW_WHEN_LOCKED = "showWhenLocked";
82
Michael Kolb8872c232013-01-29 10:33:22 -080083 // Orientation hysteresis amount used in rounding, in degrees
84 public static final int ORIENTATION_HYSTERESIS = 5;
85
86 public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
87 // See android.hardware.Camera.ACTION_NEW_PICTURE.
88 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE";
89 // See android.hardware.Camera.ACTION_NEW_VIDEO.
90 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO";
91
Dan Aminzadefca1c5e2013-08-14 17:36:56 -070092 // Broadcast Action: The camera application has become active in picture-taking mode.
93 public static final String ACTION_CAMERA_STARTED = "com.android.camera.action.CAMERA_STARTED";
94 // Broadcast Action: The camera application is no longer in active picture-taking mode.
95 public static final String ACTION_CAMERA_STOPPED = "com.android.camera.action.CAMERA_STOPPED";
96 // When the camera application is active in picture-taking mode, it listens for this intent,
97 // which upon receipt will trigger the shutter to capture a new picture, as if the user had
98 // pressed the shutter button.
99 public static final String ACTION_CAMERA_SHUTTER_CLICK =
100 "com.android.camera.action.SHUTTER_CLICK";
101
Michael Kolb8872c232013-01-29 10:33:22 -0800102 // Fields from android.hardware.Camera.Parameters
103 public static final String FOCUS_MODE_CONTINUOUS_PICTURE = "continuous-picture";
104 public static final String RECORDING_HINT = "recording-hint";
105 private static final String AUTO_EXPOSURE_LOCK_SUPPORTED = "auto-exposure-lock-supported";
106 private static final String AUTO_WHITE_BALANCE_LOCK_SUPPORTED = "auto-whitebalance-lock-supported";
107 private static final String VIDEO_SNAPSHOT_SUPPORTED = "video-snapshot-supported";
108 public static final String SCENE_MODE_HDR = "hdr";
109 public static final String TRUE = "true";
110 public static final String FALSE = "false";
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700111
112 // Fields for the show-on-maps-functionality
113 private static final String MAPS_PACKAGE_NAME = "com.google.android.apps.maps";
114 private static final String MAPS_CLASS_NAME = "com.google.android.maps.MapsActivity";
115
116 /** Has to be in sync with the receiving MovieActivity. */
117 public static final String KEY_TREAT_UP_AS_BACK = "treat-up-as-back";
Michael Kolb8872c232013-01-29 10:33:22 -0800118
119 public static boolean isSupported(String value, List<String> supported) {
120 return supported == null ? false : supported.indexOf(value) >= 0;
121 }
122
123 public static boolean isAutoExposureLockSupported(Parameters params) {
124 return TRUE.equals(params.get(AUTO_EXPOSURE_LOCK_SUPPORTED));
125 }
126
127 public static boolean isAutoWhiteBalanceLockSupported(Parameters params) {
128 return TRUE.equals(params.get(AUTO_WHITE_BALANCE_LOCK_SUPPORTED));
129 }
130
131 public static boolean isVideoSnapshotSupported(Parameters params) {
132 return TRUE.equals(params.get(VIDEO_SNAPSHOT_SUPPORTED));
133 }
134
135 public static boolean isCameraHdrSupported(Parameters params) {
136 List<String> supported = params.getSupportedSceneModes();
137 return (supported != null) && supported.contains(SCENE_MODE_HDR);
138 }
139
Michael Kolb8872c232013-01-29 10:33:22 -0800140 public static boolean isMeteringAreaSupported(Parameters params) {
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700141 return params.getMaxNumMeteringAreas() > 0;
Michael Kolb8872c232013-01-29 10:33:22 -0800142 }
143
Michael Kolb8872c232013-01-29 10:33:22 -0800144 public static boolean isFocusAreaSupported(Parameters params) {
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700145 return (params.getMaxNumFocusAreas() > 0
146 && isSupported(Parameters.FOCUS_MODE_AUTO,
147 params.getSupportedFocusModes()));
Michael Kolb8872c232013-01-29 10:33:22 -0800148 }
149
150 // Private intent extras. Test only.
151 private static final String EXTRAS_CAMERA_FACING =
152 "android.intent.extras.CAMERA_FACING";
153
154 private static float sPixelDensity = 1;
155 private static ImageFileNamer sImageFileNamer;
156
Angus Kongb50b5cb2013-08-09 14:55:20 -0700157 private CameraUtil() {
Michael Kolb8872c232013-01-29 10:33:22 -0800158 }
159
160 public static void initialize(Context context) {
161 DisplayMetrics metrics = new DisplayMetrics();
162 WindowManager wm = (WindowManager)
163 context.getSystemService(Context.WINDOW_SERVICE);
164 wm.getDefaultDisplay().getMetrics(metrics);
165 sPixelDensity = metrics.density;
166 sImageFileNamer = new ImageFileNamer(
167 context.getString(R.string.image_file_name_format));
168 }
169
170 public static int dpToPixel(int dp) {
171 return Math.round(sPixelDensity * dp);
172 }
173
174 // Rotates the bitmap by the specified degree.
175 // If a new bitmap is created, the original bitmap is recycled.
176 public static Bitmap rotate(Bitmap b, int degrees) {
177 return rotateAndMirror(b, degrees, false);
178 }
179
180 // Rotates and/or mirrors the bitmap. If a new bitmap is created, the
181 // original bitmap is recycled.
182 public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
183 if ((degrees != 0 || mirror) && b != null) {
184 Matrix m = new Matrix();
185 // Mirror first.
186 // horizontal flip + rotation = -rotation + horizontal flip
187 if (mirror) {
188 m.postScale(-1, 1);
189 degrees = (degrees + 360) % 360;
190 if (degrees == 0 || degrees == 180) {
191 m.postTranslate(b.getWidth(), 0);
192 } else if (degrees == 90 || degrees == 270) {
193 m.postTranslate(b.getHeight(), 0);
194 } else {
195 throw new IllegalArgumentException("Invalid degrees=" + degrees);
196 }
197 }
198 if (degrees != 0) {
199 // clockwise
200 m.postRotate(degrees,
201 (float) b.getWidth() / 2, (float) b.getHeight() / 2);
202 }
203
204 try {
205 Bitmap b2 = Bitmap.createBitmap(
206 b, 0, 0, b.getWidth(), b.getHeight(), m, true);
207 if (b != b2) {
208 b.recycle();
209 b = b2;
210 }
211 } catch (OutOfMemoryError ex) {
212 // We have no memory to rotate. Return the original bitmap.
213 }
214 }
215 return b;
216 }
217
218 /*
219 * Compute the sample size as a function of minSideLength
220 * and maxNumOfPixels.
221 * minSideLength is used to specify that minimal width or height of a
222 * bitmap.
223 * maxNumOfPixels is used to specify the maximal size in pixels that is
224 * tolerable in terms of memory usage.
225 *
226 * The function returns a sample size based on the constraints.
227 * Both size and minSideLength can be passed in as -1
228 * which indicates no care of the corresponding constraint.
229 * The functions prefers returning a sample size that
230 * generates a smaller bitmap, unless minSideLength = -1.
231 *
232 * Also, the function rounds up the sample size to a power of 2 or multiple
233 * of 8 because BitmapFactory only honors sample size this way.
234 * For example, BitmapFactory downsamples an image by 2 even though the
235 * request is 3. So we round up the sample size to avoid OOM.
236 */
237 public static int computeSampleSize(BitmapFactory.Options options,
238 int minSideLength, int maxNumOfPixels) {
239 int initialSize = computeInitialSampleSize(options, minSideLength,
240 maxNumOfPixels);
241
242 int roundedSize;
243 if (initialSize <= 8) {
244 roundedSize = 1;
245 while (roundedSize < initialSize) {
246 roundedSize <<= 1;
247 }
248 } else {
249 roundedSize = (initialSize + 7) / 8 * 8;
250 }
251
252 return roundedSize;
253 }
254
255 private static int computeInitialSampleSize(BitmapFactory.Options options,
256 int minSideLength, int maxNumOfPixels) {
257 double w = options.outWidth;
258 double h = options.outHeight;
259
260 int lowerBound = (maxNumOfPixels < 0) ? 1 :
261 (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
262 int upperBound = (minSideLength < 0) ? 128 :
263 (int) Math.min(Math.floor(w / minSideLength),
264 Math.floor(h / minSideLength));
265
266 if (upperBound < lowerBound) {
267 // return the larger one when there is no overlapping zone.
268 return lowerBound;
269 }
270
271 if (maxNumOfPixels < 0 && minSideLength < 0) {
272 return 1;
273 } else if (minSideLength < 0) {
274 return lowerBound;
275 } else {
276 return upperBound;
277 }
278 }
279
280 public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
281 try {
282 BitmapFactory.Options options = new BitmapFactory.Options();
283 options.inJustDecodeBounds = true;
284 BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
285 options);
286 if (options.mCancel || options.outWidth == -1
287 || options.outHeight == -1) {
288 return null;
289 }
290 options.inSampleSize = computeSampleSize(
291 options, -1, maxNumOfPixels);
292 options.inJustDecodeBounds = false;
293
294 options.inDither = false;
295 options.inPreferredConfig = Bitmap.Config.ARGB_8888;
296 return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
297 options);
298 } catch (OutOfMemoryError ex) {
299 Log.e(TAG, "Got oom exception ", ex);
300 return null;
301 }
302 }
303
304 public static void closeSilently(Closeable c) {
305 if (c == null) return;
306 try {
307 c.close();
308 } catch (Throwable t) {
309 // do nothing
310 }
311 }
312
313 public static void Assert(boolean cond) {
314 if (!cond) {
315 throw new AssertionError();
316 }
317 }
318
Michael Kolb8872c232013-01-29 10:33:22 -0800319 private static void throwIfCameraDisabled(Activity activity) throws CameraDisabledException {
320 // Check if device policy has disabled the camera.
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700321 DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(
322 Context.DEVICE_POLICY_SERVICE);
323 if (dpm.getCameraDisabled(null)) {
324 throw new CameraDisabledException();
Michael Kolb8872c232013-01-29 10:33:22 -0800325 }
326 }
327
Angus Kong9ef99252013-07-18 18:04:19 -0700328 public static CameraManager.CameraProxy openCamera(
Angus Kong4f795b82013-09-16 14:25:35 -0700329 Activity activity, final int cameraId,
330 Handler handler, final CameraManager.CameraOpenErrorCallback cb) {
Michael Kolb8872c232013-01-29 10:33:22 -0800331 try {
Angus Kong4f795b82013-09-16 14:25:35 -0700332 throwIfCameraDisabled(activity);
333 return CameraHolder.instance().open(handler, cameraId, cb);
334 } catch (CameraDisabledException ex) {
335 handler.post(new Runnable() {
336 @Override
337 public void run() {
338 cb.onCameraDisabled(cameraId);
339 }
340 });
Michael Kolb8872c232013-01-29 10:33:22 -0800341 }
Angus Kong4f795b82013-09-16 14:25:35 -0700342 return null;
Michael Kolb8872c232013-01-29 10:33:22 -0800343 }
344
345 public static void showErrorAndFinish(final Activity activity, int msgId) {
346 DialogInterface.OnClickListener buttonListener =
347 new DialogInterface.OnClickListener() {
348 @Override
349 public void onClick(DialogInterface dialog, int which) {
350 activity.finish();
351 }
352 };
353 TypedValue out = new TypedValue();
354 activity.getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);
355 new AlertDialog.Builder(activity)
356 .setCancelable(false)
357 .setTitle(R.string.camera_error_title)
358 .setMessage(msgId)
359 .setNeutralButton(R.string.dialog_ok, buttonListener)
360 .setIcon(out.resourceId)
361 .show();
362 }
363
364 public static <T> T checkNotNull(T object) {
365 if (object == null) throw new NullPointerException();
366 return object;
367 }
368
369 public static boolean equals(Object a, Object b) {
370 return (a == b) || (a == null ? false : a.equals(b));
371 }
372
373 public static int nextPowerOf2(int n) {
374 n -= 1;
375 n |= n >>> 16;
376 n |= n >>> 8;
377 n |= n >>> 4;
378 n |= n >>> 2;
379 n |= n >>> 1;
380 return n + 1;
381 }
382
383 public static float distance(float x, float y, float sx, float sy) {
384 float dx = x - sx;
385 float dy = y - sy;
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700386 return (float) Math.sqrt(dx * dx + dy * dy);
Michael Kolb8872c232013-01-29 10:33:22 -0800387 }
388
389 public static int clamp(int x, int min, int max) {
390 if (x > max) return max;
391 if (x < min) return min;
392 return x;
393 }
394
395 public static int getDisplayRotation(Activity activity) {
396 int rotation = activity.getWindowManager().getDefaultDisplay()
397 .getRotation();
398 switch (rotation) {
399 case Surface.ROTATION_0: return 0;
400 case Surface.ROTATION_90: return 90;
401 case Surface.ROTATION_180: return 180;
402 case Surface.ROTATION_270: return 270;
403 }
404 return 0;
405 }
406
407 public static int getDisplayOrientation(int degrees, int cameraId) {
408 // See android.hardware.Camera.setDisplayOrientation for
409 // documentation.
410 Camera.CameraInfo info = new Camera.CameraInfo();
411 Camera.getCameraInfo(cameraId, info);
412 int result;
413 if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
414 result = (info.orientation + degrees) % 360;
415 result = (360 - result) % 360; // compensate the mirror
416 } else { // back-facing
417 result = (info.orientation - degrees + 360) % 360;
418 }
419 return result;
420 }
421
422 public static int getCameraOrientation(int cameraId) {
423 Camera.CameraInfo info = new Camera.CameraInfo();
424 Camera.getCameraInfo(cameraId, info);
425 return info.orientation;
426 }
427
428 public static int roundOrientation(int orientation, int orientationHistory) {
429 boolean changeOrientation = false;
430 if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
431 changeOrientation = true;
432 } else {
433 int dist = Math.abs(orientation - orientationHistory);
434 dist = Math.min( dist, 360 - dist );
435 changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS );
436 }
437 if (changeOrientation) {
438 return ((orientation + 45) / 90 * 90) % 360;
439 }
440 return orientationHistory;
441 }
442
Michael Kolb8872c232013-01-29 10:33:22 -0800443 private static Point getDefaultDisplaySize(Activity activity, Point size) {
Sascha Haeberling638e6f02013-09-18 14:28:51 -0700444 activity.getWindowManager().getDefaultDisplay().getSize(size);
Michael Kolb8872c232013-01-29 10:33:22 -0800445 return size;
446 }
447
448 public static Size getOptimalPreviewSize(Activity currentActivity,
449 List<Size> sizes, double targetRatio) {
Michael Kolb8872c232013-01-29 10:33:22 -0800450
Ruben Brunk714d4d02013-10-09 16:01:16 -0700451 Point[] points = new Point[sizes.size()];
452
453 int index = 0;
454 for (Size s : sizes) {
455 points[index++] = new Point(s.width, s.height);
456 }
457
458 int optimalPickIndex = getOptimalPreviewSize(currentActivity, points, targetRatio);
459 return (optimalPickIndex == -1) ? null : sizes.get(optimalPickIndex);
460 }
461
462 public static int getOptimalPreviewSize(Activity currentActivity,
463 Point[] sizes, double targetRatio) {
464 // Use a very small tolerance because we want an exact match.
465 final double ASPECT_TOLERANCE = 0.01;
466 if (sizes == null) return -1;
467
468 int optimalSizeIndex = -1;
Michael Kolb8872c232013-01-29 10:33:22 -0800469 double minDiff = Double.MAX_VALUE;
470
471 // Because of bugs of overlay and layout, we sometimes will try to
472 // layout the viewfinder in the portrait orientation and thus get the
473 // wrong size of preview surface. When we change the preview size, the
474 // new overlay will be created before the old one closed, which causes
475 // an exception. For now, just get the screen size.
476 Point point = getDefaultDisplaySize(currentActivity, new Point());
477 int targetHeight = Math.min(point.x, point.y);
478 // Try to find an size match aspect ratio and size
Ruben Brunk714d4d02013-10-09 16:01:16 -0700479 for (int i = 0; i < sizes.length; i++) {
480 Point size = sizes[i];
481 double ratio = (double) size.x / size.y;
Michael Kolb8872c232013-01-29 10:33:22 -0800482 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
Ruben Brunk714d4d02013-10-09 16:01:16 -0700483 if (Math.abs(size.y - targetHeight) < minDiff) {
484 optimalSizeIndex = i;
485 minDiff = Math.abs(size.y - targetHeight);
Michael Kolb8872c232013-01-29 10:33:22 -0800486 }
487 }
488 // Cannot find the one match the aspect ratio. This should not happen.
489 // Ignore the requirement.
Ruben Brunk714d4d02013-10-09 16:01:16 -0700490 if (optimalSizeIndex == -1) {
Michael Kolb8872c232013-01-29 10:33:22 -0800491 Log.w(TAG, "No preview size match the aspect ratio");
492 minDiff = Double.MAX_VALUE;
Ruben Brunk714d4d02013-10-09 16:01:16 -0700493 for (int i = 0; i < sizes.length; i++) {
494 Point size = sizes[i];
495 if (Math.abs(size.y - targetHeight) < minDiff) {
496 optimalSizeIndex = i;
497 minDiff = Math.abs(size.y - targetHeight);
Michael Kolb8872c232013-01-29 10:33:22 -0800498 }
499 }
500 }
Ruben Brunk714d4d02013-10-09 16:01:16 -0700501 return optimalSizeIndex;
Michael Kolb8872c232013-01-29 10:33:22 -0800502 }
503
504 // Returns the largest picture size which matches the given aspect ratio.
505 public static Size getOptimalVideoSnapshotPictureSize(
506 List<Size> sizes, double targetRatio) {
507 // Use a very small tolerance because we want an exact match.
508 final double ASPECT_TOLERANCE = 0.001;
509 if (sizes == null) return null;
510
511 Size optimalSize = null;
512
513 // Try to find a size matches aspect ratio and has the largest width
514 for (Size size : sizes) {
515 double ratio = (double) size.width / size.height;
516 if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
517 if (optimalSize == null || size.width > optimalSize.width) {
518 optimalSize = size;
519 }
520 }
521
522 // Cannot find one that matches the aspect ratio. This should not happen.
523 // Ignore the requirement.
524 if (optimalSize == null) {
525 Log.w(TAG, "No picture size match the aspect ratio");
526 for (Size size : sizes) {
527 if (optimalSize == null || size.width > optimalSize.width) {
528 optimalSize = size;
529 }
530 }
531 }
532 return optimalSize;
533 }
534
535 public static void dumpParameters(Parameters parameters) {
536 String flattened = parameters.flatten();
537 StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
538 Log.d(TAG, "Dump all camera parameters:");
539 while (tokenizer.hasMoreElements()) {
540 Log.d(TAG, tokenizer.nextToken());
541 }
542 }
543
544 /**
545 * Returns whether the device is voice-capable (meaning, it can do MMS).
546 */
547 public static boolean isMmsCapable(Context context) {
548 TelephonyManager telephonyManager = (TelephonyManager)
549 context.getSystemService(Context.TELEPHONY_SERVICE);
550 if (telephonyManager == null) {
551 return false;
552 }
553
554 try {
555 Class<?> partypes[] = new Class[0];
556 Method sIsVoiceCapable = TelephonyManager.class.getMethod(
557 "isVoiceCapable", partypes);
558
559 Object arglist[] = new Object[0];
560 Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
561 return (Boolean) retobj;
562 } catch (java.lang.reflect.InvocationTargetException ite) {
563 // Failure, must be another device.
564 // Assume that it is voice capable.
565 } catch (IllegalAccessException iae) {
566 // Failure, must be an other device.
567 // Assume that it is voice capable.
568 } catch (NoSuchMethodException nsme) {
569 }
570 return true;
571 }
572
573 // This is for test only. Allow the camera to launch the specific camera.
574 public static int getCameraFacingIntentExtras(Activity currentActivity) {
575 int cameraId = -1;
576
577 int intentCameraId =
Angus Kongb50b5cb2013-08-09 14:55:20 -0700578 currentActivity.getIntent().getIntExtra(CameraUtil.EXTRAS_CAMERA_FACING, -1);
Michael Kolb8872c232013-01-29 10:33:22 -0800579
580 if (isFrontCameraIntent(intentCameraId)) {
581 // Check if the front camera exist
582 int frontCameraId = CameraHolder.instance().getFrontCameraId();
583 if (frontCameraId != -1) {
584 cameraId = frontCameraId;
585 }
586 } else if (isBackCameraIntent(intentCameraId)) {
587 // Check if the back camera exist
588 int backCameraId = CameraHolder.instance().getBackCameraId();
589 if (backCameraId != -1) {
590 cameraId = backCameraId;
591 }
592 }
593 return cameraId;
594 }
595
596 private static boolean isFrontCameraIntent(int intentCameraId) {
597 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
598 }
599
600 private static boolean isBackCameraIntent(int intentCameraId) {
601 return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
602 }
603
604 private static int sLocation[] = new int[2];
605
606 // This method is not thread-safe.
607 public static boolean pointInView(float x, float y, View v) {
608 v.getLocationInWindow(sLocation);
609 return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())
610 && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());
611 }
612
613 public static int[] getRelativeLocation(View reference, View view) {
614 reference.getLocationInWindow(sLocation);
615 int referenceX = sLocation[0];
616 int referenceY = sLocation[1];
617 view.getLocationInWindow(sLocation);
618 sLocation[0] -= referenceX;
619 sLocation[1] -= referenceY;
620 return sLocation;
621 }
622
623 public static boolean isUriValid(Uri uri, ContentResolver resolver) {
624 if (uri == null) return false;
625
626 try {
627 ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
628 if (pfd == null) {
629 Log.e(TAG, "Fail to open URI. URI=" + uri);
630 return false;
631 }
632 pfd.close();
633 } catch (IOException ex) {
634 return false;
635 }
636 return true;
637 }
638
Michael Kolb8872c232013-01-29 10:33:22 -0800639 public static void dumpRect(RectF rect, String msg) {
640 Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
641 + "," + rect.right + "," + rect.bottom + ")");
642 }
643
644 public static void rectFToRect(RectF rectF, Rect rect) {
645 rect.left = Math.round(rectF.left);
646 rect.top = Math.round(rectF.top);
647 rect.right = Math.round(rectF.right);
648 rect.bottom = Math.round(rectF.bottom);
649 }
650
651 public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
652 int viewWidth, int viewHeight) {
653 // Need mirror for front camera.
654 matrix.setScale(mirror ? -1 : 1, 1);
655 // This is the value for android.hardware.Camera.setDisplayOrientation.
656 matrix.postRotate(displayOrientation);
657 // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
658 // UI coordinates range from (0, 0) to (width, height).
659 matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
660 matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
661 }
662
663 public static String createJpegName(long dateTaken) {
664 synchronized (sImageFileNamer) {
665 return sImageFileNamer.generateName(dateTaken);
666 }
667 }
668
669 public static void broadcastNewPicture(Context context, Uri uri) {
670 context.sendBroadcast(new Intent(ACTION_NEW_PICTURE, uri));
671 // Keep compatibility
672 context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
673 }
674
675 public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
676 if (view.getVisibility() == View.VISIBLE) return;
677
678 view.setVisibility(View.VISIBLE);
679 Animation animation = new AlphaAnimation(startAlpha, endAlpha);
680 animation.setDuration(duration);
681 view.startAnimation(animation);
682 }
683
684 public static void fadeIn(View view) {
685 fadeIn(view, 0F, 1F, 400);
686
687 // We disabled the button in fadeOut(), so enable it here.
688 view.setEnabled(true);
689 }
690
691 public static void fadeOut(View view) {
692 if (view.getVisibility() != View.VISIBLE) return;
693
694 // Since the button is still clickable before fade-out animation
695 // ends, we disable the button first to block click.
696 view.setEnabled(false);
697 Animation animation = new AlphaAnimation(1F, 0F);
698 animation.setDuration(400);
699 view.startAnimation(animation);
700 view.setVisibility(View.GONE);
701 }
702
703 public static int getJpegRotation(int cameraId, int orientation) {
704 // See android.hardware.Camera.Parameters.setRotation for
705 // documentation.
706 int rotation = 0;
707 if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
708 CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId];
709 if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
710 rotation = (info.orientation - orientation + 360) % 360;
711 } else { // back-facing camera
712 rotation = (info.orientation + orientation) % 360;
713 }
714 }
715 return rotation;
716 }
717
Sascha Haeberling37f36112013-08-06 14:31:52 -0700718 /**
719 * Down-samples a jpeg byte array.
720 * @param data a byte array of jpeg data
721 * @param downSampleFactor down-sample factor
722 * @return decoded and down-sampled bitmap
723 */
724 public static Bitmap downSample(final byte[] data, int downSampleFactor) {
725 final BitmapFactory.Options opts = new BitmapFactory.Options();
726 // Downsample the image
727 opts.inSampleSize = downSampleFactor;
728 return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
729 }
730
Michael Kolb8872c232013-01-29 10:33:22 -0800731 public static void setGpsParameters(Parameters parameters, Location loc) {
732 // Clear previous GPS location from the parameters.
733 parameters.removeGpsData();
734
735 // We always encode GpsTimeStamp
736 parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
737
738 // Set GPS location.
739 if (loc != null) {
740 double lat = loc.getLatitude();
741 double lon = loc.getLongitude();
742 boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
743
744 if (hasLatLon) {
745 Log.d(TAG, "Set gps location");
746 parameters.setGpsLatitude(lat);
747 parameters.setGpsLongitude(lon);
748 parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
749 if (loc.hasAltitude()) {
750 parameters.setGpsAltitude(loc.getAltitude());
751 } else {
752 // for NETWORK_PROVIDER location provider, we may have
753 // no altitude information, but the driver needs it, so
754 // we fake one.
755 parameters.setGpsAltitude(0);
756 }
757 if (loc.getTime() != 0) {
758 // Location.getTime() is UTC in milliseconds.
759 // gps-timestamp is UTC in seconds.
760 long utcTimeSeconds = loc.getTime() / 1000;
761 parameters.setGpsTimestamp(utcTimeSeconds);
762 }
763 } else {
764 loc = null;
765 }
766 }
767 }
768
ztenghui16a35202013-09-23 11:35:36 -0700769 /**
770 * For still image capture, we need to get the right fps range such that the
771 * camera can slow down the framerate to allow for less-noisy/dark
772 * viewfinder output in dark conditions.
773 *
774 * @param params Camera's parameters.
775 * @return null if no appropiate fps range can't be found. Otherwise, return
776 * the right range.
777 */
778 public static int[] getPhotoPreviewFpsRange(Parameters params) {
779 List<int[]> frameRates = params.getSupportedPreviewFpsRange();
780 if (frameRates.size() == 0) {
781 Log.e(TAG, "No suppoted frame rates returned!");
782 return null;
783 }
784
785 // Find the lowest min rate in supported ranges who can cover 30fps.
786 int lowestMinRate = MAX_PREVIEW_FPS_TIMES_1000;
787 for (int[] rate : frameRates) {
788 int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX];
789 int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX];
790 if (maxFps >= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
791 minFps <= PREFERRED_PREVIEW_FPS_TIMES_1000 &&
792 minFps < lowestMinRate) {
793 lowestMinRate = minFps;
794 }
795 }
796
797 // Find all the modes with the lowest min rate found above, the pick the
798 // one with highest max rate.
799 int resultIndex = -1;
800 int highestMaxRate = 0;
801 for (int i = 0; i < frameRates.size(); i++) {
802 int[] rate = frameRates.get(i);
803 int minFps = rate[Parameters.PREVIEW_FPS_MIN_INDEX];
804 int maxFps = rate[Parameters.PREVIEW_FPS_MAX_INDEX];
805 if (minFps == lowestMinRate && highestMaxRate < maxFps) {
806 highestMaxRate = maxFps;
807 resultIndex = i;
808 }
809 }
810
811 if (resultIndex >= 0) {
812 return frameRates.get(resultIndex);
813 }
814 Log.e(TAG, "Can't find an appropiate frame rate range!");
815 return null;
816 }
Angus Kongd82eae22013-06-11 12:00:15 -0700817
818 public static int[] getMaxPreviewFpsRange(Parameters params) {
819 List<int[]> frameRates = params.getSupportedPreviewFpsRange();
820 if (frameRates != null && frameRates.size() > 0) {
821 // The list is sorted. Return the last element.
822 return frameRates.get(frameRates.size() - 1);
823 }
824 return new int[0];
825 }
826
Michael Kolb8872c232013-01-29 10:33:22 -0800827 private static class ImageFileNamer {
828 private SimpleDateFormat mFormat;
829
830 // The date (in milliseconds) used to generate the last name.
831 private long mLastDate;
832
833 // Number of names generated for the same second.
834 private int mSameSecondCount;
835
836 public ImageFileNamer(String format) {
837 mFormat = new SimpleDateFormat(format);
838 }
839
840 public String generateName(long dateTaken) {
841 Date date = new Date(dateTaken);
842 String result = mFormat.format(date);
843
844 // If the last name was generated for the same second,
845 // we append _1, _2, etc to the name.
846 if (dateTaken / 1000 == mLastDate / 1000) {
847 mSameSecondCount++;
848 result += "_" + mSameSecondCount;
849 } else {
850 mLastDate = dateTaken;
851 mSameSecondCount = 0;
852 }
853
854 return result;
855 }
856 }
Angus Kongb40738a2013-06-03 14:55:34 -0700857
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700858 public static void playVideo(Activity activity, Uri uri, String title) {
Angus Kongb40738a2013-06-03 14:55:34 -0700859 try {
ztenghui98b2a282013-10-11 17:15:40 -0700860 boolean isSecureCamera = ((CameraActivity)activity).isSecureCamera();
861 if (!isSecureCamera) {
862 Intent intent = new Intent(Intent.ACTION_VIEW)
863 .setDataAndType(uri, "video/*")
864 .putExtra(Intent.EXTRA_TITLE, title)
865 .putExtra(KEY_TREAT_UP_AS_BACK, true);
866 activity.startActivityForResult(intent, CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);
867 } else {
868 // In order not to send out any intent to be intercepted and
869 // show the lock screen immediately, we just let the secure
870 // camera activity finish.
871 activity.finish();
872 }
Angus Kongb40738a2013-06-03 14:55:34 -0700873 } catch (ActivityNotFoundException e) {
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700874 Toast.makeText(activity, activity.getString(R.string.video_err),
Angus Kongb40738a2013-06-03 14:55:34 -0700875 Toast.LENGTH_SHORT).show();
876 }
877 }
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700878
879 /**
880 * Starts GMM with the given location shown. If this fails, and GMM could
881 * not be found, we use a geo intent as a fallback.
882 *
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700883 * @param activity the activity to use for launching the Maps intent.
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700884 * @param latLong a 2-element array containing {latitude/longitude}.
885 */
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700886 public static void showOnMap(Activity activity, double[] latLong) {
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700887 try {
888 // We don't use "geo:latitude,longitude" because it only centers
889 // the MapView to the specified location, but we need a marker
890 // for further operations (routing to/from).
891 // The q=(lat, lng) syntax is suggested by geo-team.
892 String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?f=q&q=(%f,%f)",
893 latLong[0], latLong[1]);
894 ComponentName compName = new ComponentName(MAPS_PACKAGE_NAME,
895 MAPS_CLASS_NAME);
896 Intent mapsIntent = new Intent(Intent.ACTION_VIEW,
897 Uri.parse(uri)).setComponent(compName);
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700898 activity.startActivityForResult(mapsIntent,
899 CameraActivity.REQ_CODE_DONT_SWITCH_TO_PREVIEW);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700900 } catch (ActivityNotFoundException e) {
901 // Use the "geo intent" if no GMM is installed
902 Log.e(TAG, "GMM activity not found!", e);
903 String url = String.format(Locale.ENGLISH, "geo:%f,%f", latLong[0], latLong[1]);
904 Intent mapsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
Sascha Haeberlingb7639c62013-09-09 14:42:43 -0700905 activity.startActivity(mapsIntent);
Sascha Haeberlingfae11a12013-08-15 14:29:49 -0700906 }
907 }
Angus Kong7d2388d2013-09-18 23:56:01 -0700908
Angus Kongb21215a2013-09-20 18:41:46 -0700909 /**
910 * Dumps the stack trace.
911 *
912 * @param level How many levels of the stack are dumped. 0 means all.
913 * @return A {@link java.lang.String} of all the output with newline
914 * between each.
915 */
Angus Kong7d2388d2013-09-18 23:56:01 -0700916 public static String dumpStackTrace(int level) {
917 StackTraceElement[] elems = Thread.currentThread().getStackTrace();
918 // Ignore the first 3 elements.
Angus Kongb21215a2013-09-20 18:41:46 -0700919 level = (level == 0 ? elems.length : Math.min(level + 3, elems.length));
Angus Kong7d2388d2013-09-18 23:56:01 -0700920 String ret = new String();
921 for (int i = 3; i < level; i++) {
Angus Kongb21215a2013-09-20 18:41:46 -0700922 ret = ret + "\t" + elems[i].toString() + '\n';
Angus Kong7d2388d2013-09-18 23:56:01 -0700923 }
924 return ret;
925 }
Angus Kong690dc472013-09-21 14:48:51 -0700926
927 /**
928 * Launches apps supporting action {@link Intent.ACTION_MAIN} of category
929 * {@link Intent.CATEGORY_APP_GALLERY}. Note that
930 * {@link Intent.CATEGORY_APP_GALLERY} is only available on API level 15+.
931 *
932 * @param ctx The {@link android.content.Context} to launch the app.
933 * @return {@code true} on success.
934 */
935 public static boolean launchGallery(Context ctx) {
936 if (ApiHelper.HAS_APP_GALLERY) {
937 ctx.startActivity(Intent.makeMainSelectorActivity(
938 Intent.ACTION_MAIN, Intent.CATEGORY_APP_GALLERY));
939 return true;
940 }
941 return false;
942 }
Michael Kolb8872c232013-01-29 10:33:22 -0800943}