问题
I use the following code to take screenshot on a rooted device:
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");
As i want to take screenshots frequently, I don't want to first save it to the file and then read the bytes. Is there a better way to get the screenshot bitmap directly? I just wan't to eliminate this unnecessary delay. Thanks a lot!
Update:
The screencap.cpp code can be viewed here.
Also, it mentions this:
"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"
Please help me out. Thanks!
回答1:
This will work unless you're on 8.1 Pixel2 XL, then you get a security exception.
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;
}
}
Place anywhere in your code to get bitmap
BitmapScreencap.Get.Screen();
来源:https://stackoverflow.com/questions/23313412/android-screencap-to-bytes-directly-skip-saving-to-file