Prevent Users from Taking Screenshot in React Native

Android provides excellent functionality to block the users from taking a screenshot of the Application. Because to Protect the Content of App such as Bank Details or Important information.

This can be Implemented in React Native with a few lines of code.

Let’s get started.

Creating a React Native Project

Open the Terminal or CMD and run the below command.

react-native init ScreenshotProtectDemo

Then CD into the Directory

cd ScreenshotProtectDemo/android

Now Create a New file called local.properties and paste the below line.

  • For Linux:
sdk.dir = /home/USERNAME/Android/Sdk
  • For Windows:
sdk.dir=C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk

Replace the username with your actual username

Now Save the file and Come back to the Root Folder of your Project.

Which is ScreenshotProtectDemo in my case.

Now Open the Terminal and start the React Native Server with the following command.

npx react-native start

Now Open another terminal and run the command.

npx react-native run-android

Make sure you have connected the Device and USB debugging is enabled or Make sure your Android Emulator is running.

It’s time to edit the files.

Open the Project folder in Visual Studio Code.

Now Navigate to

/ScreenshotProtectDemo/android/app/src/main/java/com/screenshotprotectdemo/MainActivity.java

And add the below lines with + Symbol

package com.screenshotprotectdemo;
 
import com.facebook.react.ReactActivity;
+ import android.os.Bundle;
+ import android.view.WindowManager;
 
public class MainActivity extends ReactActivity {
 
  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "ScreenshotProtectDemo";
  }
 
 + @Override
 + protected void onCreate(Bundle savedInstanceState) {
 +   super.onCreate(savedInstanceState);
 +   getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, 
 +    WindowManager.LayoutParams.FLAG_SECURE);
 + }
}

Make sure to remove all the + symbols.

Now Save the File and Run the below command to build the app again.

npx react-native run-android

This time you can’t take screenshot of the app.

Here is the Source code for Preventing Users from Taking Screenshot in React Native.

Leave a Comment