本文介绍了如何以编程方式在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"/>

这是代码(在Activity中运行):

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上截屏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!