1 /* 2 * Copyright (C) 2016 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 17 package com.android.shell; 18 19 import static android.view.Display.DEFAULT_DISPLAY; 20 21 import android.graphics.Bitmap; 22 import android.os.RemoteException; 23 import android.util.Log; 24 import android.view.WindowManagerGlobal; 25 import android.window.ScreenCapture; 26 import android.window.ScreenCapture.ScreenshotHardwareBuffer; 27 import android.window.ScreenCapture.SynchronousScreenCaptureListener; 28 29 /** 30 * Helper class used to take screenshots. 31 * 32 * TODO: logic below was copied and pasted from UiAutomation; it should be refactored into a common 33 * component that could be used by both (Shell and UiAutomation). 34 */ 35 final class Screenshooter { 36 37 private static final String TAG = "Screenshooter"; 38 39 /** 40 * Takes a screenshot. 41 * 42 * @return The screenshot bitmap on success, null otherwise. 43 */ takeScreenshot()44 static Bitmap takeScreenshot() { 45 Log.d(TAG, "Taking fullscreen screenshot"); 46 // Take the screenshot 47 final SynchronousScreenCaptureListener syncScreenCapture = 48 ScreenCapture.createSyncCaptureListener(); 49 try { 50 WindowManagerGlobal.getWindowManagerService().captureDisplay(DEFAULT_DISPLAY, null, 51 syncScreenCapture); 52 } catch (RemoteException e) { 53 e.rethrowAsRuntimeException(); 54 } 55 final ScreenshotHardwareBuffer screenshotBuffer = syncScreenCapture.getBuffer(); 56 final Bitmap screenShot = screenshotBuffer == null ? null : screenshotBuffer.asBitmap(); 57 if (screenShot == null) { 58 Log.e(TAG, "Failed to take fullscreen screenshot"); 59 return null; 60 } 61 62 // Optimization 63 screenShot.setHasAlpha(false); 64 65 return screenShot; 66 } 67 } 68