1/* 2 * Copyright (C) 2013 DroidDriver committers 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 io.appium.droiddriver.instrumentation; 18 19import android.graphics.Bitmap; 20import android.graphics.Bitmap.Config; 21import android.graphics.Canvas; 22import android.graphics.Rect; 23import android.graphics.RectF; 24import android.util.Log; 25import android.view.View; 26 27import java.util.concurrent.Callable; 28 29import io.appium.droiddriver.base.BaseUiDevice; 30import io.appium.droiddriver.base.DroidDriverContext; 31import io.appium.droiddriver.util.InstrumentationUtils; 32import io.appium.droiddriver.util.Logs; 33 34class InstrumentationUiDevice extends BaseUiDevice { 35 private final DroidDriverContext<View, ViewElement> context; 36 37 InstrumentationUiDevice(DroidDriverContext<View, ViewElement> context) { 38 this.context = context; 39 } 40 41 @Override 42 protected Bitmap takeScreenshot() { 43 try { 44 return InstrumentationUtils.runOnMainSyncWithTimeout(new GetScreenshot( 45 context.getDriver().getRootElement().getRawElement())); 46 } catch (Throwable e) { 47 Logs.log(Log.ERROR, e); 48 return null; 49 } 50 } 51 52 @Override 53 protected DroidDriverContext<View, ViewElement> getContext() { 54 return context; 55 } 56 57 private static class GetScreenshot implements Callable<Bitmap> { 58 private final View rootView; 59 60 private GetScreenshot(View rootView) { 61 this.rootView = rootView; 62 } 63 64 @Override 65 public Bitmap call() { 66 Bitmap screenshot; 67 rootView.destroyDrawingCache(); 68 rootView.buildDrawingCache(false); 69 Bitmap drawingCache = rootView.getDrawingCache(); 70 71 int[] xy = new int[2]; 72 rootView.getLocationOnScreen(xy); 73 if (xy[0] == 0 && xy[1] == 0) { 74 screenshot = Bitmap.createBitmap(drawingCache); 75 } else { 76 Canvas canvas = new Canvas(); 77 Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight()); 78 rect.offset(xy[0], xy[1]); 79 screenshot = 80 Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888); 81 canvas.setBitmap(screenshot); 82 canvas.drawBitmap(drawingCache, null, new RectF(rect), null); 83 canvas.setBitmap(null); 84 } 85 rootView.destroyDrawingCache(); 86 return screenshot; 87 } 88 } 89} 90