如何以编程方式在 Android 上截取屏幕截图? [英] How to programmatically take a screenshot on Android?

查看:31
本文介绍了如何以编程方式在 Android 上截取屏幕截图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何不通过任何程序而是通过代码截取手机屏幕选定区域的屏幕截图?

How can I take a screenshot of a selected area of phone-screen not by any program but from code?

推荐答案

以下是允许我的屏幕截图存储在 SD 卡上并在以后用于任何您需要的代码:

Here is the code that allowed my screenshot to be stored on an SD card and used later for whatever your needs are:

首先,您需要添加适当的权限来保存文件:

First, you need to add a proper permission to save the file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

这是代码(在活动中运行):

And this is the code (running in an Activity):

private void takeScreenshot() {
    Date now = new Date();
    android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);

    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(mPath);

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or DOM
        e.printStackTrace();
    }
}

这是打开最近生成的图像的方法:

And this is how you can open the recently generated image:

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

如果您想在片段视图上使用它,请使用:

If you want to use this on fragment view then use:

View v1 = getActivity().getWindow().getDecorView().getRootView();

代替

View v1 = getWindow().getDecorView().getRootView();

关于takeScreenshot()函数

注意:

如果您的对话框包含表面视图,则此解决方案不起作用.详情请查看以下问题的答案:

This solution doesn't work if your dialog contains a surface view. For details please check the answer to the following question:

Android 截取 Surface View 的屏幕截图显示黑屏

这篇关于如何以编程方式在 Android 上截取屏幕截图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆