Util.java revision 4a12eec56ad1c5a7e89168b205363a3ced7e26b6
1/*
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
17package com.android.camera;
18
19import android.annotation.TargetApi;
20import android.app.Activity;
21import android.app.AlertDialog;
22import android.app.admin.DevicePolicyManager;
23import android.content.ActivityNotFoundException;
24import 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;
40import android.os.Build;
41import android.os.ParcelFileDescriptor;
42import android.telephony.TelephonyManager;
43import android.util.DisplayMetrics;
44import android.util.FloatMath;
45import android.util.Log;
46import android.view.Display;
47import android.view.OrientationEventListener;
48import android.view.Surface;
49import android.view.View;
50import android.view.WindowManager;
51import android.view.animation.AlphaAnimation;
52import android.view.animation.Animation;
53
54import java.io.Closeable;
55import java.io.IOException;
56import java.lang.reflect.Method;
57import java.text.SimpleDateFormat;
58import java.util.Date;
59import java.util.List;
60import java.util.StringTokenizer;
61
62/**
63 * Collection of utility functions used in this package.
64 */
65public class Util {
66    private static final String TAG = "Util";
67
68    // Orientation hysteresis amount used in rounding, in degrees
69    public static final int ORIENTATION_HYSTERESIS = 5;
70
71    public static final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
72
73    // Private intent extras. Test only.
74    private static final String EXTRAS_CAMERA_FACING =
75            "android.intent.extras.CAMERA_FACING";
76
77    private static float sPixelDensity = 1;
78    private static ImageFileNamer sImageFileNamer;
79
80    private Util() {
81    }
82
83    public static void initialize(Context context) {
84        DisplayMetrics metrics = new DisplayMetrics();
85        WindowManager wm = (WindowManager)
86                context.getSystemService(Context.WINDOW_SERVICE);
87        wm.getDefaultDisplay().getMetrics(metrics);
88        sPixelDensity = metrics.density;
89        sImageFileNamer = new ImageFileNamer(
90                context.getString(R.string.image_file_name_format));
91    }
92
93    public static int dpToPixel(int dp) {
94        return Math.round(sPixelDensity * dp);
95    }
96
97    // Rotates the bitmap by the specified degree.
98    // If a new bitmap is created, the original bitmap is recycled.
99    public static Bitmap rotate(Bitmap b, int degrees) {
100        return rotateAndMirror(b, degrees, false);
101    }
102
103    // Rotates and/or mirrors the bitmap. If a new bitmap is created, the
104    // original bitmap is recycled.
105    public static Bitmap rotateAndMirror(Bitmap b, int degrees, boolean mirror) {
106        if ((degrees != 0 || mirror) && b != null) {
107            Matrix m = new Matrix();
108            // Mirror first.
109            // horizontal flip + rotation = -rotation + horizontal flip
110            if (mirror) {
111                m.postScale(-1, 1);
112                degrees = (degrees + 360) % 360;
113                if (degrees == 0 || degrees == 180) {
114                    m.postTranslate(b.getWidth(), 0);
115                } else if (degrees == 90 || degrees == 270) {
116                    m.postTranslate(b.getHeight(), 0);
117                } else {
118                    throw new IllegalArgumentException("Invalid degrees=" + degrees);
119                }
120            }
121            if (degrees != 0) {
122                // clockwise
123                m.postRotate(degrees,
124                        (float) b.getWidth() / 2, (float) b.getHeight() / 2);
125            }
126
127            try {
128                Bitmap b2 = Bitmap.createBitmap(
129                        b, 0, 0, b.getWidth(), b.getHeight(), m, true);
130                if (b != b2) {
131                    b.recycle();
132                    b = b2;
133                }
134            } catch (OutOfMemoryError ex) {
135                // We have no memory to rotate. Return the original bitmap.
136            }
137        }
138        return b;
139    }
140
141    /*
142     * Compute the sample size as a function of minSideLength
143     * and maxNumOfPixels.
144     * minSideLength is used to specify that minimal width or height of a
145     * bitmap.
146     * maxNumOfPixels is used to specify the maximal size in pixels that is
147     * tolerable in terms of memory usage.
148     *
149     * The function returns a sample size based on the constraints.
150     * Both size and minSideLength can be passed in as -1
151     * which indicates no care of the corresponding constraint.
152     * The functions prefers returning a sample size that
153     * generates a smaller bitmap, unless minSideLength = -1.
154     *
155     * Also, the function rounds up the sample size to a power of 2 or multiple
156     * of 8 because BitmapFactory only honors sample size this way.
157     * For example, BitmapFactory downsamples an image by 2 even though the
158     * request is 3. So we round up the sample size to avoid OOM.
159     */
160    public static int computeSampleSize(BitmapFactory.Options options,
161            int minSideLength, int maxNumOfPixels) {
162        int initialSize = computeInitialSampleSize(options, minSideLength,
163                maxNumOfPixels);
164
165        int roundedSize;
166        if (initialSize <= 8) {
167            roundedSize = 1;
168            while (roundedSize < initialSize) {
169                roundedSize <<= 1;
170            }
171        } else {
172            roundedSize = (initialSize + 7) / 8 * 8;
173        }
174
175        return roundedSize;
176    }
177
178    private static int computeInitialSampleSize(BitmapFactory.Options options,
179            int minSideLength, int maxNumOfPixels) {
180        double w = options.outWidth;
181        double h = options.outHeight;
182
183        int lowerBound = (maxNumOfPixels < 0) ? 1 :
184                (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
185        int upperBound = (minSideLength < 0) ? 128 :
186                (int) Math.min(Math.floor(w / minSideLength),
187                Math.floor(h / minSideLength));
188
189        if (upperBound < lowerBound) {
190            // return the larger one when there is no overlapping zone.
191            return lowerBound;
192        }
193
194        if (maxNumOfPixels < 0 && minSideLength < 0) {
195            return 1;
196        } else if (minSideLength < 0) {
197            return lowerBound;
198        } else {
199            return upperBound;
200        }
201    }
202
203    public static Bitmap makeBitmap(byte[] jpegData, int maxNumOfPixels) {
204        try {
205            BitmapFactory.Options options = new BitmapFactory.Options();
206            options.inJustDecodeBounds = true;
207            BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
208                    options);
209            if (options.mCancel || options.outWidth == -1
210                    || options.outHeight == -1) {
211                return null;
212            }
213            options.inSampleSize = computeSampleSize(
214                    options, -1, maxNumOfPixels);
215            options.inJustDecodeBounds = false;
216
217            options.inDither = false;
218            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
219            return BitmapFactory.decodeByteArray(jpegData, 0, jpegData.length,
220                    options);
221        } catch (OutOfMemoryError ex) {
222            Log.e(TAG, "Got oom exception ", ex);
223            return null;
224        }
225    }
226
227    public static void closeSilently(Closeable c) {
228        if (c == null) return;
229        try {
230            c.close();
231        } catch (Throwable t) {
232            // do nothing
233        }
234    }
235
236    public static void Assert(boolean cond) {
237        if (!cond) {
238            throw new AssertionError();
239        }
240    }
241
242    public static CameraManager.CameraProxy openCamera(Activity activity, int cameraId)
243            throws CameraHardwareException, CameraDisabledException {
244        // Check if device policy has disabled the camera.
245        DevicePolicyManager dpm = (DevicePolicyManager) activity.getSystemService(
246                Context.DEVICE_POLICY_SERVICE);
247        if (dpm.getCameraDisabled(null)) {
248            throw new CameraDisabledException();
249        }
250
251        try {
252            return CameraHolder.instance().open(cameraId);
253        } catch (CameraHardwareException e) {
254            // In eng build, we throw the exception so that test tool
255            // can detect it and report it
256            if ("eng".equals(Build.TYPE)) {
257                throw new RuntimeException("openCamera failed", e);
258            } else {
259                throw e;
260            }
261        }
262    }
263
264    public static void showErrorAndFinish(final Activity activity, int msgId) {
265        DialogInterface.OnClickListener buttonListener =
266                new DialogInterface.OnClickListener() {
267            @Override
268            public void onClick(DialogInterface dialog, int which) {
269                activity.finish();
270            }
271        };
272        new AlertDialog.Builder(activity)
273                .setCancelable(false)
274                .setIconAttribute(android.R.attr.alertDialogIcon)
275                .setTitle(R.string.camera_error_title)
276                .setMessage(msgId)
277                .setNeutralButton(R.string.dialog_ok, buttonListener)
278                .show();
279    }
280
281    public static <T> T checkNotNull(T object) {
282        if (object == null) throw new NullPointerException();
283        return object;
284    }
285
286    public static boolean equals(Object a, Object b) {
287        return (a == b) || (a == null ? false : a.equals(b));
288    }
289
290    public static int nextPowerOf2(int n) {
291        n -= 1;
292        n |= n >>> 16;
293        n |= n >>> 8;
294        n |= n >>> 4;
295        n |= n >>> 2;
296        n |= n >>> 1;
297        return n + 1;
298    }
299
300    public static float distance(float x, float y, float sx, float sy) {
301        float dx = x - sx;
302        float dy = y - sy;
303        return FloatMath.sqrt(dx * dx + dy * dy);
304    }
305
306    public static int clamp(int x, int min, int max) {
307        if (x > max) return max;
308        if (x < min) return min;
309        return x;
310    }
311
312    public static int getDisplayRotation(Activity activity) {
313        int rotation = activity.getWindowManager().getDefaultDisplay()
314                .getRotation();
315        switch (rotation) {
316            case Surface.ROTATION_0: return 0;
317            case Surface.ROTATION_90: return 90;
318            case Surface.ROTATION_180: return 180;
319            case Surface.ROTATION_270: return 270;
320        }
321        return 0;
322    }
323
324    public static int getDisplayOrientation(int degrees, int cameraId) {
325        // See android.hardware.Camera.setDisplayOrientation for
326        // documentation.
327        Camera.CameraInfo info = new Camera.CameraInfo();
328        Camera.getCameraInfo(cameraId, info);
329        int result;
330        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
331            result = (info.orientation + degrees) % 360;
332            result = (360 - result) % 360;  // compensate the mirror
333        } else {  // back-facing
334            result = (info.orientation - degrees + 360) % 360;
335        }
336        return result;
337    }
338
339    public static int getCameraOrientation(int cameraId) {
340        Camera.CameraInfo info = new Camera.CameraInfo();
341        Camera.getCameraInfo(cameraId, info);
342        return info.orientation;
343    }
344
345    public static int roundOrientation(int orientation, int orientationHistory) {
346        boolean changeOrientation = false;
347        if (orientationHistory == OrientationEventListener.ORIENTATION_UNKNOWN) {
348            changeOrientation = true;
349        } else {
350            int dist = Math.abs(orientation - orientationHistory);
351            dist = Math.min( dist, 360 - dist );
352            changeOrientation = ( dist >= 45 + ORIENTATION_HYSTERESIS );
353        }
354        if (changeOrientation) {
355            return ((orientation + 45) / 90 * 90) % 360;
356        }
357        return orientationHistory;
358    }
359
360    @SuppressWarnings("deprecation")
361    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
362    private static Point getDefaultDisplaySize(Activity activity, Point size) {
363        Display d = activity.getWindowManager().getDefaultDisplay();
364        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
365            d.getSize(size);
366        } else {
367            size.set(d.getWidth(), d.getHeight());
368        }
369        return size;
370    }
371
372    public static Size getOptimalPreviewSize(Activity currentActivity,
373            List<Size> sizes, double targetRatio) {
374        // Use a very small tolerance because we want an exact match.
375        final double ASPECT_TOLERANCE = 0.001;
376        if (sizes == null) return null;
377
378        Size optimalSize = null;
379        double minDiff = Double.MAX_VALUE;
380
381        // Because of bugs of overlay and layout, we sometimes will try to
382        // layout the viewfinder in the portrait orientation and thus get the
383        // wrong size of preview surface. When we change the preview size, the
384        // new overlay will be created before the old one closed, which causes
385        // an exception. For now, just get the screen size.
386        Point point = getDefaultDisplaySize(currentActivity, new Point());
387        int targetHeight = Math.min(point.x, point.y);
388
389        // Try to find an size match aspect ratio and size
390        for (Size size : sizes) {
391            double ratio = (double) size.width / size.height;
392            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
393            if (Math.abs(size.height - targetHeight) < minDiff) {
394                optimalSize = size;
395                minDiff = Math.abs(size.height - targetHeight);
396            }
397        }
398
399        // Cannot find the one match the aspect ratio. This should not happen.
400        // Ignore the requirement.
401        if (optimalSize == null) {
402            Log.w(TAG, "No preview size match the aspect ratio");
403            minDiff = Double.MAX_VALUE;
404            for (Size size : sizes) {
405                if (Math.abs(size.height - targetHeight) < minDiff) {
406                    optimalSize = size;
407                    minDiff = Math.abs(size.height - targetHeight);
408                }
409            }
410        }
411        return optimalSize;
412    }
413
414    // Returns the largest picture size which matches the given aspect ratio.
415    public static Size getOptimalVideoSnapshotPictureSize(
416            List<Size> sizes, double targetRatio) {
417        // Use a very small tolerance because we want an exact match.
418        final double ASPECT_TOLERANCE = 0.001;
419        if (sizes == null) return null;
420
421        Size optimalSize = null;
422
423        // Try to find a size matches aspect ratio and has the largest width
424        for (Size size : sizes) {
425            double ratio = (double) size.width / size.height;
426            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
427            if (optimalSize == null || size.width > optimalSize.width) {
428                optimalSize = size;
429            }
430        }
431
432        // Cannot find one that matches the aspect ratio. This should not happen.
433        // Ignore the requirement.
434        if (optimalSize == null) {
435            Log.w(TAG, "No picture size match the aspect ratio");
436            for (Size size : sizes) {
437                if (optimalSize == null || size.width > optimalSize.width) {
438                    optimalSize = size;
439                }
440            }
441        }
442        return optimalSize;
443    }
444
445    public static void dumpParameters(Parameters parameters) {
446        String flattened = parameters.flatten();
447        StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
448        Log.d(TAG, "Dump all camera parameters:");
449        while (tokenizer.hasMoreElements()) {
450            Log.d(TAG, tokenizer.nextToken());
451        }
452    }
453
454    /**
455     * Returns whether the device is voice-capable (meaning, it can do MMS).
456     */
457    public static boolean isMmsCapable(Context context) {
458        TelephonyManager telephonyManager = (TelephonyManager)
459                context.getSystemService(Context.TELEPHONY_SERVICE);
460        if (telephonyManager == null) {
461            return false;
462        }
463
464        try {
465            Class<?> partypes[] = new Class[0];
466            Method sIsVoiceCapable = TelephonyManager.class.getMethod(
467                    "isVoiceCapable", partypes);
468
469            Object arglist[] = new Object[0];
470            Object retobj = sIsVoiceCapable.invoke(telephonyManager, arglist);
471            return (Boolean) retobj;
472        } catch (java.lang.reflect.InvocationTargetException ite) {
473            // Failure, must be another device.
474            // Assume that it is voice capable.
475        } catch (IllegalAccessException iae) {
476            // Failure, must be an other device.
477            // Assume that it is voice capable.
478        } catch (NoSuchMethodException nsme) {
479        }
480        return true;
481    }
482
483    // This is for test only. Allow the camera to launch the specific camera.
484    public static int getCameraFacingIntentExtras(Activity currentActivity) {
485        int cameraId = -1;
486
487        int intentCameraId =
488                currentActivity.getIntent().getIntExtra(Util.EXTRAS_CAMERA_FACING, -1);
489
490        if (isFrontCameraIntent(intentCameraId)) {
491            // Check if the front camera exist
492            int frontCameraId = CameraHolder.instance().getFrontCameraId();
493            if (frontCameraId != -1) {
494                cameraId = frontCameraId;
495            }
496        } else if (isBackCameraIntent(intentCameraId)) {
497            // Check if the back camera exist
498            int backCameraId = CameraHolder.instance().getBackCameraId();
499            if (backCameraId != -1) {
500                cameraId = backCameraId;
501            }
502        }
503        return cameraId;
504    }
505
506    private static boolean isFrontCameraIntent(int intentCameraId) {
507        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
508    }
509
510    private static boolean isBackCameraIntent(int intentCameraId) {
511        return (intentCameraId == android.hardware.Camera.CameraInfo.CAMERA_FACING_BACK);
512    }
513
514    private static int sLocation[] = new int[2];
515
516    // This method is not thread-safe.
517    public static boolean pointInView(float x, float y, View v) {
518        v.getLocationInWindow(sLocation);
519        return x >= sLocation[0] && x < (sLocation[0] + v.getWidth())
520                && y >= sLocation[1] && y < (sLocation[1] + v.getHeight());
521    }
522
523    public static int[] getRelativeLocation(View reference, View view) {
524        reference.getLocationInWindow(sLocation);
525        int referenceX = sLocation[0];
526        int referenceY = sLocation[1];
527        view.getLocationInWindow(sLocation);
528        sLocation[0] -= referenceX;
529        sLocation[1] -= referenceY;
530        return sLocation;
531    }
532
533    public static boolean isUriValid(Uri uri, ContentResolver resolver) {
534        if (uri == null) return false;
535
536        try {
537            ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
538            if (pfd == null) {
539                Log.e(TAG, "Fail to open URI. URI=" + uri);
540                return false;
541            }
542            pfd.close();
543        } catch (IOException ex) {
544            return false;
545        }
546        return true;
547    }
548
549    public static void viewUri(Uri uri, Context context) {
550        if (!isUriValid(uri, context.getContentResolver())) {
551            Log.e(TAG, "Uri invalid. uri=" + uri);
552            return;
553        }
554
555        try {
556            context.startActivity(new Intent(Util.REVIEW_ACTION, uri));
557        } catch (ActivityNotFoundException ex) {
558            try {
559                context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
560            } catch (ActivityNotFoundException e) {
561                Log.e(TAG, "review image fail. uri=" + uri, e);
562            }
563        }
564    }
565
566    public static void dumpRect(RectF rect, String msg) {
567        Log.v(TAG, msg + "=(" + rect.left + "," + rect.top
568                + "," + rect.right + "," + rect.bottom + ")");
569    }
570
571    public static void rectFToRect(RectF rectF, Rect rect) {
572        rect.left = Math.round(rectF.left);
573        rect.top = Math.round(rectF.top);
574        rect.right = Math.round(rectF.right);
575        rect.bottom = Math.round(rectF.bottom);
576    }
577
578    public static void prepareMatrix(Matrix matrix, boolean mirror, int displayOrientation,
579            int viewWidth, int viewHeight) {
580        // Need mirror for front camera.
581        matrix.setScale(mirror ? -1 : 1, 1);
582        // This is the value for android.hardware.Camera.setDisplayOrientation.
583        matrix.postRotate(displayOrientation);
584        // Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
585        // UI coordinates range from (0, 0) to (width, height).
586        matrix.postScale(viewWidth / 2000f, viewHeight / 2000f);
587        matrix.postTranslate(viewWidth / 2f, viewHeight / 2f);
588    }
589
590    public static String createJpegName(long dateTaken) {
591        synchronized (sImageFileNamer) {
592            return sImageFileNamer.generateName(dateTaken);
593        }
594    }
595
596    public static void broadcastNewPicture(Context context, Uri uri) {
597        context.sendBroadcast(new Intent(android.hardware.Camera.ACTION_NEW_PICTURE, uri));
598        // Keep compatibility
599        context.sendBroadcast(new Intent("com.android.camera.NEW_PICTURE", uri));
600    }
601
602    public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
603        if (view.getVisibility() == View.VISIBLE) return;
604
605        view.setVisibility(View.VISIBLE);
606        Animation animation = new AlphaAnimation(startAlpha, endAlpha);
607        animation.setDuration(duration);
608        view.startAnimation(animation);
609    }
610
611    public static void fadeIn(View view) {
612        fadeIn(view, 0F, 1F, 400);
613
614        // We disabled the button in fadeOut(), so enable it here.
615        view.setEnabled(true);
616    }
617
618    public static void fadeOut(View view) {
619        if (view.getVisibility() != View.VISIBLE) return;
620
621        // Since the button is still clickable before fade-out animation
622        // ends, we disable the button first to block click.
623        view.setEnabled(false);
624        Animation animation = new AlphaAnimation(1F, 0F);
625        animation.setDuration(400);
626        view.startAnimation(animation);
627        view.setVisibility(View.GONE);
628    }
629
630    public static int getJpegRotation(int cameraId, int orientation) {
631        // See android.hardware.Camera.Parameters.setRotation for
632        // documentation.
633        int rotation = 0;
634        if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
635            CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId];
636            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
637                rotation = (info.orientation - orientation + 360) % 360;
638            } else {  // back-facing camera
639                rotation = (info.orientation + orientation) % 360;
640            }
641        }
642        return rotation;
643    }
644
645    public static void setGpsParameters(Parameters parameters, Location loc) {
646        // Clear previous GPS location from the parameters.
647        parameters.removeGpsData();
648
649        // We always encode GpsTimeStamp
650        parameters.setGpsTimestamp(System.currentTimeMillis() / 1000);
651
652        // Set GPS location.
653        if (loc != null) {
654            double lat = loc.getLatitude();
655            double lon = loc.getLongitude();
656            boolean hasLatLon = (lat != 0.0d) || (lon != 0.0d);
657
658            if (hasLatLon) {
659                Log.d(TAG, "Set gps location");
660                parameters.setGpsLatitude(lat);
661                parameters.setGpsLongitude(lon);
662                parameters.setGpsProcessingMethod(loc.getProvider().toUpperCase());
663                if (loc.hasAltitude()) {
664                    parameters.setGpsAltitude(loc.getAltitude());
665                } else {
666                    // for NETWORK_PROVIDER location provider, we may have
667                    // no altitude information, but the driver needs it, so
668                    // we fake one.
669                    parameters.setGpsAltitude(0);
670                }
671                if (loc.getTime() != 0) {
672                    // Location.getTime() is UTC in milliseconds.
673                    // gps-timestamp is UTC in seconds.
674                    long utcTimeSeconds = loc.getTime() / 1000;
675                    parameters.setGpsTimestamp(utcTimeSeconds);
676                }
677            } else {
678                loc = null;
679            }
680        }
681    }
682
683    private static class ImageFileNamer {
684        private SimpleDateFormat mFormat;
685
686        // The date (in milliseconds) used to generate the last name.
687        private long mLastDate;
688
689        // Number of names generated for the same second.
690        private int mSameSecondCount;
691
692        public ImageFileNamer(String format) {
693            mFormat = new SimpleDateFormat(format);
694        }
695
696        public String generateName(long dateTaken) {
697            Date date = new Date(dateTaken);
698            String result = mFormat.format(date);
699
700            // If the last name was generated for the same second,
701            // we append _1, _2, etc to the name.
702            if (dateTaken / 1000 == mLastDate / 1000) {
703                mSameSecondCount++;
704                result += "_" + mSameSecondCount;
705            } else {
706                mLastDate = dateTaken;
707                mSameSecondCount = 0;
708            }
709
710            return result;
711        }
712    }
713}
714