我正在开发一个 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/