在Android中,是否可以从服务中捕获屏幕截图 [英] In Android, is it possible to capture screenshots from service
问题描述
我正在开发一个 Android 应用程序来捕获屏幕截图.我想要做的是使用屏幕顶部的按钮创建一个服务,并通过点击它来截屏.
I'm developing an Android application to capture screenshots. What I'm trying to do is make a service with a button on the top of the screen and taking screenshot by tapping it.
我想知道它是否可行,就像我说的那样提供服务.我也希望从屏幕截图中排除该按钮.我能做到吗?
I wonder if it may work, with service as I said. Also I want the button excluded from the screenshot. Am I able to do this?
推荐答案
以下是允许我的屏幕截图存储在 sd 卡上并在以后用于任何您需要的代码:
Here is the code that allowed my screenshot to be stored on sd card and used later for whatever your needs are:
首先添加适当的权限保存文件:
First, add proper permission to save 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 OOM
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);
}
要排除按钮,您可以隐藏按钮,然后在一段时间后显示屏幕.
to exclude the button, you can make button hide and then take screen show after some time interval.
这篇关于在Android中,是否可以从服务中捕获屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!