java - 在Android中,是否可以从服务中捕获屏幕截图

标签 java android screenshot

我正在开发一个 Android 应用程序来捕获屏幕截图。我想做的是在屏幕顶部创建一个带有按钮的服务,并通过点击它来截取屏幕截图。

我想知道它是否可以工作,如我所说的服务。我还希望该按钮从屏幕截图中排除。我能做到吗?

最佳答案

以下代码允许将我的屏幕截图存储在 SD 卡上,并在以后满足您的任何需求:

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

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

这是代码(在 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 OOM
        e.printStackTrace();
    }
}

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

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

要排除该按钮,您可以使按钮隐藏,然后在一段时间间隔后屏幕显示。

关于java - 在Android中,是否可以从服务中捕获屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149983/

相关文章:

android - 如何在 Libgdx 中处理 Sprite ?

Android:如何在应用程序 list 中引用可绘制库

c - 仅使用 X11 lib 在 C 中截取窗口的屏幕截图

java - 如何开始 : testing Java Swing GUI with AssertJ Swing

android - 通过 PreferenceScreen 中的 Intent 共享链接

java - Android URI 类 - 它的用途是什么?

android - 是否可以在不显示 View 的情况下拍摄 View 的屏幕截图?

android - 阻止 Android 中特定 Activity 的屏幕截图

java - 在 Android 应用程序中设置单个静态 applicationContext 有哪些缺点?

java - 检查两个字符串是否是字谜的运行时间应该是多少