How To Build A Screenshot Android App - Hive Programmers

in StemSocial11 months ago

Greetings to my favorite Science community online, StemSocial.

I'm excited to be back to continue my Android App Development series after having a restful weekend.

In today's simple yet very useful episode, we're going to learn how to build a screenshot Android App which would be capable of taking shots of the Android device screen when a button is clicked within the App.

Polish_20240122_135104684.pngOriginal Image Source by janjf93 from Pixabay

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Being able to take screenshots on an Android device is becoming as useful and as helpful as a selfie or camera because people use screenshots a lot these days.

Maybe you're flipping through images or an article or even a simple meme and don't have an option to save or download it, you could easily use a screenshot app to take the shorts.

It's true that phones do come with screenshots capabilities by default but I onced used a device for so long it had an issue with the power and volume button so I couldn't take a screenshot and the phone didn't come with a screenshot button in notification bar area.

  • I had to go download screenshot triggering apps which came in handy at that time.

In today's episode, we'll be building such an App and it would be a way to introduce my readers to new Android Studio APIs and classes like Bitmap and Permission requests.

I hope you're ready for this one guys. Let's get started with today's work.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Prerequisites

For the benefit of newcomers to Android App development or my series, I'll share with you the required softwares you need to be able to go through with this tutorial.

  • Android Studio IDE - the platform on which we'll develop this and all other Android Apps.

  • Java Development Kit, JDK - You need to install JDK correctly on your PC for your PC to be able to execute Java commands or codes.

  • Physical Android Device or Emulator - After building the App, we'll need to test it either on an emulator or a physical Android device.

If you have all these checked out, you're absolutely ready to go through with this tutorial

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Creating A New Project

Alright guys so we'll start out our work by opening Android Studio IDE and clicking on "Create A New Project"

Continue by selecting your preferred Project template but as always I'll recommend choosing "Empty Activity" to make things easier for beginners. Click the "Next" button when you're through.

Set both the package name and App name of your App project and also set the programming language of your project as Java and not Kotlin.

When you're through with the Project configuration, click on the "Finish" button and Android Studio will load your new project Space for you.

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Designing Our Simple User Interface

Alright guys it's time to work on the frontend part of our App.

This is a beginner's tutorial showing how to develop the screenshot App feature so all we would really need is a single button that would trigger the screenshot activity when the user presses it.

  • So we would have to add a Button element in our layout activity.

The user interface or frontend layout code will be written inside our activity_main.xml file.

Here's how the code should look like

(html comment removed:  activity_main.xml )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCapture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Capture Screenshot"
        android:layout_centerInParent="true"/>
</RelativeLayout>

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Logic Code - Handling Button Click

It's time for a marathon code guys. We're going to be writing the logic code which would trigger the screenshot action when we click the "Capture Screenshot" button we created in our user interface design.

The entire logic code will be written inside our MainActivity.java file.

  • We have two tasks in our hands though.

The first is to implement setOnClickListener method which triggers the action and the second thing to do is to request the WRITE_EXTERNAL_STORAGE permission so that we can save each screenshot we make.

When it comes to the permission request, we'll do it in two different files.

The first request which will allow the App to access the storage of the Android device to save the screenshot images would be done inside our MainActivity.java file and the second request will be implemented inside the AndroidManifest.xml

Several image handling APIs like Bitmap will be used in our logic code.

I really hope you're ready for this marathon code

Here's how the logic code of our screenshot App should look like

// MainActivity.java
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnCapture = findViewById(R.id.btnCapture);
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermissionAndCaptureScreenshot();
            }
        });
    }

    private void requestPermissionAndCaptureScreenshot() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
        } else {
            captureScreenshot();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                captureScreenshot();
            } else {
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void captureScreenshot() {
        View rootView = getWindow().getDecorView().getRootView();
        rootView.setDrawingCacheEnabled(true);

        Bitmap bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
        rootView.setDrawingCacheEnabled(false);

        saveScreenshot(bitmap);
    }

    private void saveScreenshot(Bitmap bitmap) {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String fileName = "Screenshot_" + timeStamp + ".png";

        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(storageDir, fileName);

        try {
            FileOutputStream fos = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            Toast.makeText(this, "Screenshot saved: " + imageFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Failed to save screenshot", Toast.LENGTH_SHORT).show();
        }
    }
}

As you can see from the above code, I also added a code to handle errors.

We essentially used the toast message to show a "Failed to save screenshot" message if the screenshot couldn't save due to perhaps the memory of device being full.

YpihifdXP4WNbGMdjw7e3DuhJWBvCw4SfuLZsrnJYHEpsqZFkiGGNCQTayu6EytKdg7zA3LL2PbZxrJGpWk6ZoZvBcJrADNFmaFEHagho8WsASbAA8jrpnELSvRtvjVuMiU1C5ADFX1vJgcpDvNtue9Pq83tjBKX62dqT5UoxtDk.png

Request Permissions

As I mentioned earlier on, since our Screenshot App would require access to the storage of the Android Device, we need to request access permission inside our AndroidManifest.xml file.

Here's how the permission request code should look like guys

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2dk2RRM2dZ8gKjXsrozapsD83FxL3Xbyyi5LFttAhrXxr16mCe4arfLHNDdHCBmaJroMz2VbLrf6Rxy9uPQm7Ts7EnXL4nPiXSE5vJWSfR53VcqDUrQD87CZSpt2RKZcmrYrze8KanjkfyS8XmMCcz4p33NZmfHE4S9oRo3wU2.png

Run Your App

Congratulations guys, you have completed your first ever very simple and basic screenshot App.

It's now time to run it. Click on the run button in your Android Studio IDE Menu screen and run the App either on an emulator or a physical Android device.

When the App finally launches, press the "Capture Screenshot" button to capture and save the screenshot automatically.

However guys, you need to ensure your device or emulator has external storage available otherwise the Failed error toast message would appear in the App.

That's all for this tutorial guys. I hope you enjoyed the episode.

As always if you're having troubles writing the code, installing the required softwares or running thr finished App, please let me know in the comments.

Thank you all for the support. To my friends @stickupcurator or @stickupboys and everyone else.

Have A Great Day And Catch You Next Time On StemSocial. Goodbye 👨‍💻


You Can Follow Me @skyehi For More Like This And Others

Sort:  

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

Thanks for including @stemsocial as a beneficiary, which gives you stronger support.