我使用以下代码在有根设备上截取屏幕截图:
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代码here。
另外,它提到了这个:
"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"
请帮帮我。谢谢!
答案 0 :(得分:0)
除非您使用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();