/** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { try { //分辨率大小,后续可以通过代码来获取到当前的分辨率 int xResolution = 320; int yResolution = 480; //执行adb命令,把framebuffer中内容保存到fb1文件中 Runtime.getRuntime().exec("adb pull /dev/graphics/fb0 C:/fb1"); //等待几秒保证framebuffer中的数据都被保存下来,如果没有保存完成进行读取操作会有IO异常 Thread.sleep(15000); //读取文件中的数据 InputStream in = (InputStream)new FileInputStream("C:/fb1"); DataInput frameBuffer = new LittleEndianDataInputStream(in);
BufferedImage screenImage = new BufferedImage( xResolution, yResolution, BufferedImage.TYPE_INT_ARGB); int[] oneLine = new int[xResolution]; for (int y = 0; y < yResolution; y++) { //从frameBuffer中计算出rgb值 convertToRgba32(frameBuffer, oneLine); //把rgb值设置到image对象中 screenImage.setRGB(0, y, xResolution, 1, oneLine, 0, xResolution); } Closeables.closeQuietly(in);
ByteArrayOutputStream rawPngStream = new ByteArrayOutputStream(); try { if (!ImageIO.write(screenImage, "png", rawPngStream)) { throw new RuntimeException( "This Java environment does not support converting to PNG."); } } catch (IOException exception) { // This should never happen because rawPngStream is an in-memory stream. System.out.println("IOException=" + exception); } byte[] rawPngBytes = rawPngStream.toByteArray(); String base64Png = new Base64Encoder().encode(rawPngBytes);
int value = mDisplay.getRotation(); String hwRotation = SystemProperties.get("ro.sf.hwrotation", "0"); if (hwRotation.equals("270") || hwRotation.equals("90")) { value = (value + 3) % 4; } float degrees = getDegreesForRotation(value);
boolean requiresRotation = (degrees > 0); if (requiresRotation) { // Get the dimensions of the device in its native orientation mDisplayMatrix.reset(); mDisplayMatrix.preRotate(-degrees); mDisplayMatrix.mapPoints(dims);
int value = mDisplay.getRotation(); String hwRotation = SystemProperties.get("ro.sf.hwrotation", "0"); if (hwRotation.equals("270") || hwRotation.equals("90")) { value = (value + 3) % 4; } float degrees = getDegreesForRotation(value);
boolean requiresRotation = (degrees > 0); if (requiresRotation) { // Get the dimensions of the device in its native orientation mDisplayMatrix.reset(); mDisplayMatrix.preRotate(-degrees); mDisplayMatrix.mapPoints(dims);
Android源码中调用屏幕截图的接口。 捕获到组合键后,我们再看看android源码中是如何调用屏幕截图的函数接口。在上面的函数interceptScreenshotChord中我们看到用handler判断长按组合键500毫秒之后,会进入如下函数: private final Runnable mScreenshotChordLongPress = new Runnable() { public void run() { takeScreenshot(); } }; 在这里启动了一个线程来完成截屏的功能,接着看函数takeScreenshot(): private void takeScreenshot() { synchronized (mScreenshotLock) { if (mScreenshotConnection != null) { return; } ComponentName cn = new ComponentName("com.android.systemui", "com.android.systemui.screenshot.TakeScreenshotService"); Intent intent = new Intent(); intent.setComponent(cn); ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (mScreenshotLock) { if (mScreenshotConnection != this) { return; } Messenger messenger = new Messenger(service); Message msg = Message.obtain(null, 1); final ServiceConnection myConn = this; Handler h = new Handler(mHandler.getLooper()) { @Override public void handleMessage(Message msg) { synchronized (mScreenshotLock) { if (mScreenshotConnection == myConn) { mContext.unbindService(mScreenshotConnection); mScreenshotConnection = null; mHandler.removeCallbacks(mScreenshotTimeout); } } } }; msg.replyTo = new Messenger(h); msg.arg1 = msg.arg2 = 0; if (mStatusBar != null && mStatusBar.isVisibleLw()) msg.arg1 = 1; if (mNavigationBar != null && mNavigationBar.isVisibleLw()) msg.arg2 = 1; try { messenger.send(msg); } catch (RemoteException e) { } } } @Override public void onServiceDisconnected(ComponentName name) {} }; if (mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE)) { mScreenshotConnection = conn; mHandler.postDelayed(mScreenshotTimeout, 10000); } } } 可以看到这个函数使用AIDL绑定了service服务 到"com.android.systemui.screenshot.TakeScreenshotService",注意在service连接成功 时,对message的msg.arg1和msg.arg2两个参数的赋值。其中在mScreenshotTimeout中对服务service做了超时 处理。接着我们找到实现这个服务service的类TakeScreenshotService,看看其实现的流程: public class TakeScreenshotService extends Service { private static final String TAG = "TakeScreenshotService";
private static GlobalScreenshot mScreenshot;
private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: final Messenger callback = msg.replyTo; if (mScreenshot == null) { mScreenshot = new GlobalScreenshot(TakeScreenshotService.this); } mScreenshot.takeScreenshot(new Runnable() { @Override public void run() { Message reply = Message.obtain(null, 1); try { callback.send(reply); } catch (RemoteException e) { } } }, msg.arg1 > 0, msg.arg2 > 0); } } };
@Override public IBinder onBind(Intent intent) { return new Messenger(mHandler).getBinder(); } } 在这个类中,我们主要看调用接口,用到了mScreenshot.takeScreenshot()传递了三个参数,第一个是个runnable,第二和 第三个是之前message传递的两个参数msg.arg1和msg.arg2。最后我们看看这个函数takeScreenshot(),位于文件 GlobalScreenshot.java中(跟之前的函数重名但是文件路径不一样):
/** * Takes a screenshot of the current display and shows an animation. */ void takeScreenshot(Runnable finisher, boolean statusBarVisible, boolean navBarVisible) { // We need to orient the screenshot correctly (and the Surface api seems to take screenshots // only in the natural orientation of the device :!) mDisplay.getRealMetrics(mDisplayMetrics); float[] dims = {mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels}; float degrees = getDegreesForRotation(mDisplay.getRotation()); boolean requiresRotation = (degrees > 0); if (requiresRotation) { // Get the dimensions of the device in its native orientation mDisplayMatrix.reset(); mDisplayMatrix.preRotate(-degrees); mDisplayMatrix.mapPoints(dims); dims[0] = Math.abs(dims[0]); dims[1] = Math.abs(dims[1]); }
// Take the screenshot mScreenBitmap = Surface.screenshot((int) dims[0], (int) dims[1]); if (mScreenBitmap == null) { notifyScreenshotError(mContext, mNotificationManager); finisher.run(); return; }
if (requiresRotation) { // Rotate the screenshot to the current orientation Bitmap ss = Bitmap.createBitmap(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(ss); c.translate(ss.getWidth() / 2, ss.getHeight() / 2); c.rotate(degrees); c.translate(-dims[0] / 2, -dims[1] / 2); c.drawBitmap(mScreenBitmap, 0, 0, null); c.setBitmap(null); mScreenBitmap = ss; }
// Start the post-screenshot animation startAnimation(finisher, mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, statusBarVisible, navBarVisible); } 这段代码的注释比较详细,其实看到这里,我们算是真正看到截屏的操作了,具体的工作包括对屏幕大小、旋转角度的获取,然后调用Surface类的 screenshot方法截屏保存到bitmap中,之后把这部分位图填充到一个画布上,最后再启动一个延迟的拍照动画效果。如果再往下探究 screenshot方法,发现已经是一个native方法了: /** * Like {@link #screenshot(int, int, int, int)} but includes all * Surfaces in the screenshot. * * @hide */ public static native Bitmap screenshot(int width, int height); 使用JNI技术调用底层的代码,如果再往下走,会发现映射这这个jni函数在文件android_view_Surface.cpp中,这个真的已经是底层c++语言了,统一调用的底层函数是: static jobject doScreenshot(JNIEnv* env, jobject clazz, jint width, jint height, jint minLayer, jint maxLayer, bool allLayers) { ScreenshotPixelRef* pixels = new ScreenshotPixelRef(NULL); if (pixels->update(width, height, minLayer, maxLayer, allLayers) != NO_ERROR) { delete pixels; return 0; }
uint32_t w = pixels->getWidth(); uint32_t h = pixels->getHeight(); uint32_t s = pixels->getStride(); uint32_t f = pixels->getFormat(); ssize_t bpr = s * android::bytesPerPixel(f);
SkBitmap* bitmap = new SkBitmap(); bitmap->setConfig(convertPixelFormat(f), w, h, bpr); if (f == PIXEL_FORMAT_RGBX_8888) { bitmap->setIsOpaque(true); }
if (w > 0 && h > 0) { bitmap->setPixelRef(pixels)->unref(); bitmap->lockPixels(); } else { // be safe with an empty bitmap. delete pixels; bitmap->setPixels(NULL); }
return GraphicsJNI::createBitmap(env, bitmap, false, NULL); } 由于对C++不熟,我这里就不敢多言了。其实到这里,算是对手机android源码中通过组合键屏幕截图的整个流程有个大体了解了,一般我们在改动中熟悉按键的捕获原理,并且清楚调用的截屏函数接口即可,如果有兴趣的,可以继续探究更深的底层是如何实现的。
----------------------------------------------
(C)(P)Flying Wang