Android:Screencap直接到字节 – 跳过保存到文件

我使用以下代码在root设备上截取屏幕截图:

sh = Runtime.getRuntime().exec("su", null,null); os = sh.getOutputStream(); os.write(("/system/bin/screencap -p " + "/sdcard/img.jpg" + "\n").getBytes("ASCII")); os.flush(); os.close(); sh.waitFor(); myBitmap = BitmapFactory.decodeFile("/sdcard/img.jpg"); 

由于我想经常截取屏幕截图,我不想先将其保存到文件然后读取字节。 是否有更好的方法直接获取屏幕截图位图? 我只是想消除这种不必要的延迟。 非常感谢!

更新:

可以在此处查看screencap.cpp代码。

另外,它提到了这个:

  "usage: %s [-hp] [-d display-id] [FILENAME]\n" " -h: this message\n" " -p: save the file as a png.\n" " -d: specify the display id to capture, default %d.\n" "If FILENAME ends with .png it will be saved as a png.\n" "If FILENAME is not given, the results will be printed to stdout.\n" 

请帮帮我。 谢谢!

除非您使用的是8.1 Pixel2 XL,否则会出现安全例外情况。

 import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.IOException; import java.io.OutputStreamWriter; public class BitmapScreencap { public final static BitmapScreencap Get = new BitmapScreencap(); private BitmapScreencap() { } public Bitmap Screen() { try { Process process = Runtime.getRuntime().exec("su"); OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream()); outputStream.write("/system/bin/screencap -p\n"); outputStream.flush(); Bitmap screen = BitmapFactory.decodeStream(process.getInputStream()); outputStream.write("exit\n"); outputStream.flush(); outputStream.close(); return screen; } catch (IOException e) { e.printStackTrace(); } return null; } } 

放置在代码中的任何位置以获取位图

 BitmapScreencap.Get.Screen();