• Posted by:

    Asutosh Panda

    • December 20, 2016

    Implementing automatic screenshot functionality inside your android app

  • Blogs
  • Implementing automatic screenshot functionality inside your android app
  • Blogs
  • Implementing automatic screenshot f...

Sometimes we need to implement screenshot taking functionality in an Android app that captures the whole screen inside the app as an image automatically without the user doing anything.
This type of feature is useful in scenarios like auto saving a copy of a payment receipt as an image or when you are working in a drawing app and the app auto saves the drawing for printout when the drawing is over.  

1. Create a class called ViewToImage and paste this code - 
    public class ViewToImage {
        public ViewToImage(View view){
            Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),                      Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
            try {
                FileOutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/1.png");
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
                output.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2. Now simply make an object of this class to save the App screen as an image when you have to take an automatic screenshot in the app -
// top_level_layout is the topmost parent Layout/View in your Activity
// pass top_level_layout as a parameter and make an object of ViewToImage class
ViewToImage v = new ViewToImage(top_level_layout)

 

TOP