Taking a screenshot programmatically in Android Apps

Taking a screenshot programmatically in an Android Application can be very interesting to let your users to send you a visual representation of the application state when a bug occurs. Furthermore, it can be also useful to let users to share their current screen in a game with friends. It can help you to create a viral effect on social networks for example.

Image for post
Image for post

So, in that tutorial, you are going to learn how to take a screenshot programmatically in an Android Application. Note that you can also watch this tutorial in video on YouTube :

Creating a Screenshot object

Android SDK offers in standard the possibility to get a Bitmap representation of a specific View. So, to take a screenshot of the content displayed to the user on the screen, the main idea is to get the root view of the current activity and then creating the corresponding Bitmap.

For that, we create a dedicated Screenshot object. We will have two methods :

  • A takeScreenshot method taking in parameter a View and returning the Bitmap associated.
  • A takescreenshotOfRootView method taking in parameter a View and returning the Bitmap associated to the root view of that View.

It gives us the following code for the Screenshot class :

Taking a Screenshot

Now, it’s time to use our Screenshot object in an Activity. We create a simple activity with just a Button and an ImageView taking the whole part of the screen. When the user will click on it, we will call the takescreenshotOfRootView method to get the Bitmap associated to the screen.

To visualize our screenshot, we set this Bitmap on the ImageView by calling its setImageBitmap method. It gives us the following code for our MainActivity :

Our Screenshot App in Action

To test our Screenshot Android Application, we have just to launch the application and click on the Button. You should have the following result :

Image for post
Image for post

Storing the Screenshot

To share the screenshot taken, you will need to store it. So, how can we achieve that ? We are going to use the compress method of the Bitmap class. This method lets us to write a Bitmap in a File represented by a FileOutputStream instance.

It gives us the following code for our storeScreenshot method taking in parameter the Bitmap representing our Screenshot taken previously :

That’s all for that tutorial !

To discover more tutorials on Android development, you can subscribe to the SSaurel’s Channel :

Written by

Entrepreneur / Developer / Blogger / Author. In Bitcoin We Trust: https://www.inbitcoinwetrust.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store