且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android:直接截屏到字节 - 跳过保存到文件

更新时间:2023-12-02 20:16:28

除非您使用的是 8.1 Pixel2 XL,否则这将有效,然后您会收到安全异常.

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();