我如何在不重写之前拍摄的屏幕截图的情况下以编程方式保存屏幕截图



我正在开发一个android应用程序,我想保存该应用程序的屏幕截图。我可以保存一张屏幕截图,但它会重写以前的屏幕截图。我遵循了一个教程并对其进行了修改,但它只需要一张屏幕截图

此处附上按钮动作中的代码

case R.id.btn_save:
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
int i = 0;
File file = new File("ScreenShot"+ i +".PNG");
if(!file.exists()){
store(bitmap, "ScreenShot"+ i +".PNG");
}
else {
store(bitmap, "ScreenShot"+ i++ +".PNG");
}

以及屏幕截图存储功能

public void store(Bitmap bm, String fileName){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
File dir = new File(dirPath);
if (!dir.exists()){
dir.mkdirs();
}
File file = new File(dirPath,fileName);
try{
FileOutputStream fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100,fos);
fos.flush();
fos.close();
}catch (Exception e){
e.printStackTrace();
Toast.makeText(this, "Error saving File", Toast.LENGTH_SHORT).show();
}
}

您在按钮save中声明了i变量,因此单击按钮时始终以0开头。要使用您尝试的方式,您应该在该范围之外声明该变量,但当您终止并重新打开应用程序时,它会重新启动。

如果要使用该方法,可以使用"共享首选项"保存以下数字(或上次使用的数字(。如果没有,你可以简单地使用

"Screenshot" + System.currentTimeInMillis().toString(). 

您还将有截图拍摄的时间(尽管以毫秒为单位(。如果你想,你可以将其格式化为"用户可读"20191110,例如

因为在该代码中,文件名总是相同的-i总是0。为了让它在应用程序的一次使用中发挥作用,我应该是一个成员变量,并在每个屏幕截图中递增。为了使其更通用,您应该使用File.createTempFile((生成一个随机名称

case R.id.btn_save:
View rootView getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File dir = new File(Environment.getExternalStorageDirectory(), "Screenshots");
if (!dir.exists())
if ( !dir.mkdirs())
{
Toast ( could not create dir...);
return;
}
int i = 0;
while (++i > 0 )
{
String fileName = "ScreenShot"+ i +".png";
File file = new File(dir, fileName);
if(!file.exists())
{
store(bitmap, file);
break;
}
}
break;     

store(Bitmap bm, String fileName)的参数更改为store(Bitmap bm, File file)

在那里,您可以在try块之前删除所有代码。

相关内容

最新更新