Search code examples
javaandroidandroid-bitmap

How can I save a screenshots programmatically with out over writing the previously taken screenshot?


I'm working on an android application and I want to save a screenshot of the application. I can save a single screenshot but it keeps over writing the previous screenshot. I followed a tutorial and modified it but it does not take more than a single screenshot

Attached here is the code in the button action

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

and the screenshot storing function

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

Solution

  • You are declaring i variable inside the button save so you will always start with 0 when button is clicked. To use the way you are trying you should declare that variable outside that scope, but it will restart when you kill and reopen the app.

    You can use Shared Preferences to save the following number to use (or the last you used) if you want to use that approach. If not you can use simply

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

    You will also have the time when the screenshot was taken (although in millis). If you want you can format it to be like "user readable" 20191110 for example