GlobalScreenshot.java revision 3745a3da759a9510554c8d2c59f09185e52ed403
1/*
2 * Copyright (C) 2011 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.systemui.screenshot;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ValueAnimator;
23import android.animation.ValueAnimator.AnimatorUpdateListener;
24import android.app.Notification;
25import android.app.Notification.BigPictureStyle;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.content.ContentResolver;
29import android.content.ContentValues;
30import android.content.Context;
31import android.content.Intent;
32import android.content.res.Resources;
33import android.graphics.Bitmap;
34import android.graphics.Canvas;
35import android.graphics.ColorMatrix;
36import android.graphics.ColorMatrixColorFilter;
37import android.graphics.Matrix;
38import android.graphics.Paint;
39import android.graphics.PixelFormat;
40import android.graphics.PointF;
41import android.graphics.RectF;
42import android.media.MediaActionSound;
43import android.net.Uri;
44import android.os.AsyncTask;
45import android.os.Environment;
46import android.os.Process;
47import android.provider.MediaStore;
48import android.util.DisplayMetrics;
49import android.view.Display;
50import android.view.LayoutInflater;
51import android.view.MotionEvent;
52import android.view.Surface;
53import android.view.View;
54import android.view.ViewGroup;
55import android.view.WindowManager;
56import android.view.animation.Interpolator;
57import android.widget.ImageView;
58
59import com.android.systemui.R;
60
61import java.io.File;
62import java.io.OutputStream;
63import java.text.SimpleDateFormat;
64import java.util.Date;
65
66/**
67 * POD used in the AsyncTask which saves an image in the background.
68 */
69class SaveImageInBackgroundData {
70    Context context;
71    Bitmap image;
72    Uri imageUri;
73    Runnable finisher;
74    int iconSize;
75    int result;
76}
77
78/**
79 * An AsyncTask that saves an image to the media store in the background.
80 */
81class SaveImageInBackgroundTask extends AsyncTask<SaveImageInBackgroundData, Void,
82        SaveImageInBackgroundData> {
83    private static final String SCREENSHOTS_DIR_NAME = "Screenshots";
84    private static final String SCREENSHOT_FILE_NAME_TEMPLATE = "Screenshot_%s.png";
85    private static final String SCREENSHOT_FILE_PATH_TEMPLATE = "%s/%s/%s";
86
87    private int mNotificationId;
88    private NotificationManager mNotificationManager;
89    private Notification.Builder mNotificationBuilder;
90    private String mImageFileName;
91    private String mImageFilePath;
92    private long mImageTime;
93    private BigPictureStyle mNotificationStyle;
94
95    // WORKAROUND: We want the same notification across screenshots that we update so that we don't
96    // spam a user's notification drawer.  However, we only show the ticker for the saving state
97    // and if the ticker text is the same as the previous notification, then it will not show. So
98    // for now, we just add and remove a space from the ticker text to trigger the animation when
99    // necessary.
100    private static boolean mTickerAddSpace;
101
102    SaveImageInBackgroundTask(Context context, SaveImageInBackgroundData data,
103            NotificationManager nManager, int nId) {
104        Resources r = context.getResources();
105
106        // Prepare all the output metadata
107        mImageTime = System.currentTimeMillis();
108        String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(mImageTime));
109        String imageDir = Environment.getExternalStoragePublicDirectory(
110                Environment.DIRECTORY_PICTURES).getAbsolutePath();
111        mImageFileName = String.format(SCREENSHOT_FILE_NAME_TEMPLATE, imageDate);
112        mImageFilePath = String.format(SCREENSHOT_FILE_PATH_TEMPLATE, imageDir,
113                SCREENSHOTS_DIR_NAME, mImageFileName);
114
115        // Create the large notification icon
116        int imageWidth = data.image.getWidth();
117        int imageHeight = data.image.getHeight();
118        int iconSize = data.iconSize;
119
120        final int shortSide = imageWidth < imageHeight ? imageWidth : imageHeight;
121        Bitmap preview = Bitmap.createBitmap(shortSide, shortSide, data.image.getConfig());
122        Canvas c = new Canvas(preview);
123        Paint paint = new Paint();
124        ColorMatrix desat = new ColorMatrix();
125        desat.setSaturation(0.25f);
126        paint.setColorFilter(new ColorMatrixColorFilter(desat));
127        Matrix matrix = new Matrix();
128        matrix.postTranslate((shortSide - imageWidth) / 2,
129                            (shortSide - imageHeight) / 2);
130        c.drawBitmap(data.image, matrix, paint);
131        c.drawColor(0x40FFFFFF);
132
133        Bitmap croppedIcon = Bitmap.createScaledBitmap(preview, iconSize, iconSize, true);
134
135        // Show the intermediate notification
136        mTickerAddSpace = !mTickerAddSpace;
137        mNotificationId = nId;
138        mNotificationManager = nManager;
139        mNotificationBuilder = new Notification.Builder(context)
140            .setTicker(r.getString(R.string.screenshot_saving_ticker)
141                    + (mTickerAddSpace ? " " : ""))
142            .setContentTitle(r.getString(R.string.screenshot_saving_title))
143            .setContentText(r.getString(R.string.screenshot_saving_text))
144            .setSmallIcon(R.drawable.stat_notify_image)
145            .setWhen(System.currentTimeMillis());
146
147        mNotificationStyle = new Notification.BigPictureStyle()
148            .bigPicture(preview);
149        mNotificationBuilder.setStyle(mNotificationStyle);
150
151        Notification n = mNotificationBuilder.build();
152        n.flags |= Notification.FLAG_NO_CLEAR;
153        mNotificationManager.notify(nId, n);
154
155        // On the tablet, the large icon makes the notification appear as if it is clickable (and
156        // on small devices, the large icon is not shown) so defer showing the large icon until
157        // we compose the final post-save notification below.
158        mNotificationBuilder.setLargeIcon(croppedIcon);
159        // But we still don't set it for the expanded view, allowing the smallIcon to show here.
160        mNotificationStyle.bigLargeIcon(null);
161    }
162
163    @Override
164    protected SaveImageInBackgroundData doInBackground(SaveImageInBackgroundData... params) {
165        if (params.length != 1) return null;
166
167        // By default, AsyncTask sets the worker thread to have background thread priority, so bump
168        // it back up so that we save a little quicker.
169        Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
170
171        Context context = params[0].context;
172        Bitmap image = params[0].image;
173        Resources r = context.getResources();
174
175        try {
176            // Save the screenshot to the MediaStore
177            ContentValues values = new ContentValues();
178            ContentResolver resolver = context.getContentResolver();
179            values.put(MediaStore.Images.ImageColumns.DATA, mImageFilePath);
180            values.put(MediaStore.Images.ImageColumns.TITLE, mImageFileName);
181            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, mImageFileName);
182            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, mImageTime);
183            values.put(MediaStore.Images.ImageColumns.DATE_ADDED, mImageTime);
184            values.put(MediaStore.Images.ImageColumns.DATE_MODIFIED, mImageTime);
185            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/png");
186            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
187
188            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
189            sharingIntent.setType("image/png");
190            sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
191            sharingIntent.setFlags(Intent.FLAG_ACTIVITY_CLOSE_SYSTEM_DIALOGS);
192            mNotificationBuilder.addAction(R.drawable.ic_menu_share,
193                     r.getString(com.android.internal.R.string.share),
194                     PendingIntent.getActivity(context, 0, sharingIntent, 0));
195
196            OutputStream out = resolver.openOutputStream(uri);
197            image.compress(Bitmap.CompressFormat.PNG, 100, out);
198            out.flush();
199            out.close();
200
201            // update file size in the database
202            values.clear();
203            values.put(MediaStore.Images.ImageColumns.SIZE, new File(mImageFilePath).length());
204            resolver.update(uri, values, null, null);
205
206            params[0].imageUri = uri;
207            params[0].result = 0;
208        } catch (Exception e) {
209            // IOException/UnsupportedOperationException may be thrown if external storage is not
210            // mounted
211            params[0].result = 1;
212        }
213
214        return params[0];
215    }
216
217    @Override
218    protected void onPostExecute(SaveImageInBackgroundData params) {
219        if (params.result > 0) {
220            // Show a message that we've failed to save the image to disk
221            GlobalScreenshot.notifyScreenshotError(params.context, mNotificationManager);
222        } else {
223            // Show the final notification to indicate screenshot saved
224            Resources r = params.context.getResources();
225
226            // Create the intent to show the screenshot in gallery
227            Intent launchIntent = new Intent(Intent.ACTION_VIEW);
228            launchIntent.setDataAndType(params.imageUri, "image/png");
229            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
230
231            mNotificationBuilder
232                .setContentTitle(r.getString(R.string.screenshot_saved_title))
233                .setContentText(r.getString(R.string.screenshot_saved_text))
234                .setContentIntent(PendingIntent.getActivity(params.context, 0, launchIntent, 0))
235                .setWhen(System.currentTimeMillis())
236                .setAutoCancel(true);
237
238            Notification n = mNotificationBuilder.build();
239            n.flags &= ~Notification.FLAG_NO_CLEAR;
240            mNotificationManager.notify(mNotificationId, n);
241        }
242        params.finisher.run();
243    }
244}
245
246/**
247 * TODO:
248 *   - Performance when over gl surfaces? Ie. Gallery
249 *   - what do we say in the Toast? Which icon do we get if the user uses another
250 *     type of gallery?
251 */
252class GlobalScreenshot {
253    private static final int SCREENSHOT_NOTIFICATION_ID = 789;
254    private static final int SCREENSHOT_FLASH_TO_PEAK_DURATION = 130;
255    private static final int SCREENSHOT_DROP_IN_DURATION = 430;
256    private static final int SCREENSHOT_DROP_OUT_DELAY = 500;
257    private static final int SCREENSHOT_DROP_OUT_DURATION = 430;
258    private static final int SCREENSHOT_DROP_OUT_SCALE_DURATION = 370;
259    private static final int SCREENSHOT_FAST_DROP_OUT_DURATION = 320;
260    private static final float BACKGROUND_ALPHA = 0.5f;
261    private static final float SCREENSHOT_SCALE = 1f;
262    private static final float SCREENSHOT_DROP_IN_MIN_SCALE = SCREENSHOT_SCALE * 0.725f;
263    private static final float SCREENSHOT_DROP_OUT_MIN_SCALE = SCREENSHOT_SCALE * 0.45f;
264    private static final float SCREENSHOT_FAST_DROP_OUT_MIN_SCALE = SCREENSHOT_SCALE * 0.6f;
265    private static final float SCREENSHOT_DROP_OUT_MIN_SCALE_OFFSET = 0f;
266
267    private Context mContext;
268    private WindowManager mWindowManager;
269    private WindowManager.LayoutParams mWindowLayoutParams;
270    private NotificationManager mNotificationManager;
271    private Display mDisplay;
272    private DisplayMetrics mDisplayMetrics;
273    private Matrix mDisplayMatrix;
274
275    private Bitmap mScreenBitmap;
276    private View mScreenshotLayout;
277    private ImageView mBackgroundView;
278    private ImageView mScreenshotView;
279    private ImageView mScreenshotFlash;
280
281    private AnimatorSet mScreenshotAnimation;
282
283    private int mNotificationIconSize;
284    private float mBgPadding;
285    private float mBgPaddingScale;
286
287    private MediaActionSound mCameraSound;
288
289
290    /**
291     * @param context everything needs a context :(
292     */
293    public GlobalScreenshot(Context context) {
294        Resources r = context.getResources();
295        mContext = context;
296        LayoutInflater layoutInflater = (LayoutInflater)
297                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
298
299        // Inflate the screenshot layout
300        mDisplayMatrix = new Matrix();
301        mScreenshotLayout = layoutInflater.inflate(R.layout.global_screenshot, null);
302        mBackgroundView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot_background);
303        mScreenshotView = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot);
304        mScreenshotFlash = (ImageView) mScreenshotLayout.findViewById(R.id.global_screenshot_flash);
305        mScreenshotLayout.setFocusable(true);
306        mScreenshotLayout.setOnTouchListener(new View.OnTouchListener() {
307            @Override
308            public boolean onTouch(View v, MotionEvent event) {
309                // Intercept and ignore all touch events
310                return true;
311            }
312        });
313
314        // Setup the window that we are going to use
315        mWindowLayoutParams = new WindowManager.LayoutParams(
316                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
317                WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY,
318                WindowManager.LayoutParams.FLAG_FULLSCREEN
319                    | WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
320                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
321                    | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED,
322                PixelFormat.TRANSLUCENT);
323        mWindowLayoutParams.setTitle("ScreenshotAnimation");
324        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
325        mNotificationManager =
326            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
327        mDisplay = mWindowManager.getDefaultDisplay();
328        mDisplayMetrics = new DisplayMetrics();
329        mDisplay.getRealMetrics(mDisplayMetrics);
330
331        // Get the various target sizes
332        mNotificationIconSize =
333            r.getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
334
335        // Scale has to account for both sides of the bg
336        mBgPadding = (float) r.getDimensionPixelSize(R.dimen.global_screenshot_bg_padding);
337        mBgPaddingScale = mBgPadding /  mDisplayMetrics.widthPixels;
338
339        // Setup the Camera shutter sound
340        mCameraSound = new MediaActionSound();
341        mCameraSound.load(MediaActionSound.SHUTTER_CLICK);
342    }
343
344    /**
345     * Creates a new worker thread and saves the screenshot to the media store.
346     */
347    private void saveScreenshotInWorkerThread(Runnable finisher) {
348        SaveImageInBackgroundData data = new SaveImageInBackgroundData();
349        data.context = mContext;
350        data.image = mScreenBitmap;
351        data.iconSize = mNotificationIconSize;
352        data.finisher = finisher;
353        new SaveImageInBackgroundTask(mContext, data, mNotificationManager,
354                SCREENSHOT_NOTIFICATION_ID).execute(data);
355    }
356
357    /**
358     * @return the current display rotation in degrees
359     */
360    private float getDegreesForRotation(int value) {
361        switch (value) {
362        case Surface.ROTATION_90:
363            return 360f - 90f;
364        case Surface.ROTATION_180:
365            return 360f - 180f;
366        case Surface.ROTATION_270:
367            return 360f - 270f;
368        }
369        return 0f;
370    }
371
372    /**
373     * Takes a screenshot of the current display and shows an animation.
374     */
375    void takeScreenshot(Runnable finisher, boolean statusBarVisible, boolean navBarVisible) {
376        // We need to orient the screenshot correctly (and the Surface api seems to take screenshots
377        // only in the natural orientation of the device :!)
378        mDisplay.getRealMetrics(mDisplayMetrics);
379        float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels};
380        float degrees = getDegreesForRotation(mDisplay.getRotation());
381        boolean requiresRotation = (degrees > 0);
382        if (requiresRotation) {
383            // Get the dimensions of the device in its native orientation
384            mDisplayMatrix.reset();
385            mDisplayMatrix.preRotate(-degrees);
386            mDisplayMatrix.mapPoints(dims);
387            dims[0] = Math.abs(dims[0]);
388            dims[1] = Math.abs(dims[1]);
389        }
390
391        // Take the screenshot
392        mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]);
393        if (mScreenBitmap == null) {
394            notifyScreenshotError(mContext, mNotificationManager);
395            finisher.run();
396            return;
397        }
398
399        if (requiresRotation) {
400            // Rotate the screenshot to the current orientation
401            Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels,
402                    mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888);
403            Canvas c = new Canvas(ss);
404            c.translate(ss.getWidth() / 2, ss.getHeight() / 2);
405            c.rotate(degrees);
406            c.translate(-dims[0] / 2, -dims[1] / 2);
407            c.drawBitmap(mScreenBitmap, 0, 0, null);
408            c.setBitmap(null);
409            mScreenBitmap = ss;
410        }
411
412        // Optimizations
413        mScreenBitmap.setHasAlpha(false);
414        mScreenBitmap.prepareToDraw();
415
416        // Start the post-screenshot animation
417        startAnimation(finisher, mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels,
418                statusBarVisible, navBarVisible);
419    }
420
421
422    /**
423     * Starts the animation after taking the screenshot
424     */
425    private void startAnimation(final Runnable finisher, int w, int h, boolean statusBarVisible,
426            boolean navBarVisible) {
427        // Add the view for the animation
428        mScreenshotView.setImageBitmap(mScreenBitmap);
429        mScreenshotLayout.requestFocus();
430
431        // Setup the animation with the screenshot just taken
432        if (mScreenshotAnimation != null) {
433            mScreenshotAnimation.end();
434        }
435
436        mWindowManager.addView(mScreenshotLayout, mWindowLayoutParams);
437        ValueAnimator screenshotDropInAnim = createScreenshotDropInAnimation();
438        ValueAnimator screenshotFadeOutAnim = createScreenshotDropOutAnimation(w, h,
439                statusBarVisible, navBarVisible);
440        mScreenshotAnimation = new AnimatorSet();
441        mScreenshotAnimation.playSequentially(screenshotDropInAnim, screenshotFadeOutAnim);
442        mScreenshotAnimation.addListener(new AnimatorListenerAdapter() {
443            @Override
444            public void onAnimationEnd(Animator animation) {
445                // Save the screenshot once we have a bit of time now
446                saveScreenshotInWorkerThread(finisher);
447                mWindowManager.removeView(mScreenshotLayout);
448            }
449        });
450        mScreenshotLayout.post(new Runnable() {
451            @Override
452            public void run() {
453                // Play the shutter sound to notify that we've taken a screenshot
454                mCameraSound.play(MediaActionSound.SHUTTER_CLICK);
455
456                mScreenshotView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
457                mScreenshotView.buildLayer();
458                mScreenshotAnimation.start();
459            }
460        });
461    }
462    private ValueAnimator createScreenshotDropInAnimation() {
463        final float flashPeakDurationPct = ((float) (SCREENSHOT_FLASH_TO_PEAK_DURATION)
464                / SCREENSHOT_DROP_IN_DURATION);
465        final float flashDurationPct = 2f * flashPeakDurationPct;
466        final Interpolator flashAlphaInterpolator = new Interpolator() {
467            @Override
468            public float getInterpolation(float x) {
469                // Flash the flash view in and out quickly
470                if (x <= flashDurationPct) {
471                    return (float) Math.sin(Math.PI * (x / flashDurationPct));
472                }
473                return 0;
474            }
475        };
476        final Interpolator scaleInterpolator = new Interpolator() {
477            @Override
478            public float getInterpolation(float x) {
479                // We start scaling when the flash is at it's peak
480                if (x < flashPeakDurationPct) {
481                    return 0;
482                }
483                return (x - flashDurationPct) / (1f - flashDurationPct);
484            }
485        };
486        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
487        anim.setDuration(SCREENSHOT_DROP_IN_DURATION);
488        anim.addListener(new AnimatorListenerAdapter() {
489            @Override
490            public void onAnimationStart(Animator animation) {
491                mBackgroundView.setAlpha(0f);
492                mBackgroundView.setVisibility(View.VISIBLE);
493                mScreenshotView.setAlpha(0f);
494                mScreenshotView.setTranslationX(0f);
495                mScreenshotView.setTranslationY(0f);
496                mScreenshotView.setScaleX(SCREENSHOT_SCALE + mBgPaddingScale);
497                mScreenshotView.setScaleY(SCREENSHOT_SCALE + mBgPaddingScale);
498                mScreenshotView.setVisibility(View.VISIBLE);
499                mScreenshotFlash.setAlpha(0f);
500                mScreenshotFlash.setVisibility(View.VISIBLE);
501            }
502            @Override
503            public void onAnimationEnd(android.animation.Animator animation) {
504                mScreenshotFlash.setVisibility(View.GONE);
505            }
506        });
507        anim.addUpdateListener(new AnimatorUpdateListener() {
508            @Override
509            public void onAnimationUpdate(ValueAnimator animation) {
510                float t = (Float) animation.getAnimatedValue();
511                float scaleT = (SCREENSHOT_SCALE + mBgPaddingScale)
512                    - scaleInterpolator.getInterpolation(t)
513                        * (SCREENSHOT_SCALE - SCREENSHOT_DROP_IN_MIN_SCALE);
514                mBackgroundView.setAlpha(scaleInterpolator.getInterpolation(t) * BACKGROUND_ALPHA);
515                mScreenshotView.setAlpha(t);
516                mScreenshotView.setScaleX(scaleT);
517                mScreenshotView.setScaleY(scaleT);
518                mScreenshotFlash.setAlpha(flashAlphaInterpolator.getInterpolation(t));
519            }
520        });
521        return anim;
522    }
523    private ValueAnimator createScreenshotDropOutAnimation(int w, int h, boolean statusBarVisible,
524            boolean navBarVisible) {
525        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
526        anim.setStartDelay(SCREENSHOT_DROP_OUT_DELAY);
527        anim.addListener(new AnimatorListenerAdapter() {
528            @Override
529            public void onAnimationEnd(Animator animation) {
530                mBackgroundView.setVisibility(View.GONE);
531                mScreenshotView.setVisibility(View.GONE);
532                mScreenshotView.setLayerType(View.LAYER_TYPE_NONE, null);
533            }
534        });
535
536        if (!statusBarVisible || !navBarVisible) {
537            // There is no status bar/nav bar, so just fade the screenshot away in place
538            anim.setDuration(SCREENSHOT_FAST_DROP_OUT_DURATION);
539            anim.addUpdateListener(new AnimatorUpdateListener() {
540                @Override
541                public void onAnimationUpdate(ValueAnimator animation) {
542                    float t = (Float) animation.getAnimatedValue();
543                    float scaleT = (SCREENSHOT_DROP_IN_MIN_SCALE + mBgPaddingScale)
544                            - t * (SCREENSHOT_DROP_IN_MIN_SCALE - SCREENSHOT_FAST_DROP_OUT_MIN_SCALE);
545                    mBackgroundView.setAlpha((1f - t) * BACKGROUND_ALPHA);
546                    mScreenshotView.setAlpha(1f - t);
547                    mScreenshotView.setScaleX(scaleT);
548                    mScreenshotView.setScaleY(scaleT);
549                }
550            });
551        } else {
552            // In the case where there is a status bar, animate to the origin of the bar (top-left)
553            final float scaleDurationPct = (float) SCREENSHOT_DROP_OUT_SCALE_DURATION
554                    / SCREENSHOT_DROP_OUT_DURATION;
555            final Interpolator scaleInterpolator = new Interpolator() {
556                @Override
557                public float getInterpolation(float x) {
558                    if (x < scaleDurationPct) {
559                        // Decelerate, and scale the input accordingly
560                        return (float) (1f - Math.pow(1f - (x / scaleDurationPct), 2f));
561                    }
562                    return 1f;
563                }
564            };
565
566            // Determine the bounds of how to scale
567            float halfScreenWidth = (w - 2f * mBgPadding) / 2f;
568            float halfScreenHeight = (h - 2f * mBgPadding) / 2f;
569            final float offsetPct = SCREENSHOT_DROP_OUT_MIN_SCALE_OFFSET;
570            final PointF finalPos = new PointF(
571                -halfScreenWidth + (SCREENSHOT_DROP_OUT_MIN_SCALE + offsetPct) * halfScreenWidth,
572                -halfScreenHeight + (SCREENSHOT_DROP_OUT_MIN_SCALE + offsetPct) * halfScreenHeight);
573
574            // Animate the screenshot to the status bar
575            anim.setDuration(SCREENSHOT_DROP_OUT_DURATION);
576            anim.addUpdateListener(new AnimatorUpdateListener() {
577                @Override
578                public void onAnimationUpdate(ValueAnimator animation) {
579                    float t = (Float) animation.getAnimatedValue();
580                    float scaleT = (SCREENSHOT_DROP_IN_MIN_SCALE + mBgPaddingScale)
581                        - scaleInterpolator.getInterpolation(t)
582                            * (SCREENSHOT_DROP_IN_MIN_SCALE - SCREENSHOT_DROP_OUT_MIN_SCALE);
583                    mBackgroundView.setAlpha((1f - t) * BACKGROUND_ALPHA);
584                    mScreenshotView.setAlpha(1f - scaleInterpolator.getInterpolation(t));
585                    mScreenshotView.setScaleX(scaleT);
586                    mScreenshotView.setScaleY(scaleT);
587                    mScreenshotView.setTranslationX(t * finalPos.x);
588                    mScreenshotView.setTranslationY(t * finalPos.y);
589                }
590            });
591        }
592        return anim;
593    }
594
595    static void notifyScreenshotError(Context context, NotificationManager nManager) {
596        Resources r = context.getResources();
597
598        // Clear all existing notification, compose the new notification and show it
599        Notification n = new Notification.Builder(context)
600            .setTicker(r.getString(R.string.screenshot_failed_title))
601            .setContentTitle(r.getString(R.string.screenshot_failed_title))
602            .setContentText(r.getString(R.string.screenshot_failed_text))
603            .setSmallIcon(R.drawable.stat_notify_image_error)
604            .setWhen(System.currentTimeMillis())
605            .setAutoCancel(true)
606            .getNotification();
607        nManager.notify(SCREENSHOT_NOTIFICATION_ID, n);
608    }
609}
610