Prevent Screen Shot in All Activities
Source: https://www.geeksforgeeks.org/how-to-prevent-screenshot-or-screen-recorder-in-android/
Method 1
In the MainActivity.java file simply add the following code and it will prevent taking Screenshot in Android App.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
Below is the complete code for the MainActivity.java file.
import
androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.view.WindowManager;
public
class
MainActivity extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding this line will prevent taking screenshot in your app
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
}
}
Method 2
Method 1 is only appropriate for a single activity but what’s the solution for block screenshot for all the activities. We are going to discuss this in method 2. First of all, make a Custom Application class and add a registerActivityLifecycleCallbacks. Then register it in your manifest.
Step 1: Here write the given code in the MyApplicationContext.java file
import
android.app.Activity;
import
android.app.Application;
import
android.content.Context;
import
android.os.Bundle;
import
android.view.WindowManager;
public
class
MyApplicationContext extends
Application {
private
Context context;
public
void
onCreate() {
super.onCreate();
context = getApplicationContext();
setupActivityListener();
}
private
void
setupActivityListener() {
registerActivityLifecycleCallbacks(new
ActivityLifecycleCallbacks() {
@Override
public
void
onActivityCreated(Activity activity, Bundle savedInstanceState) {
activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); }
@Override
public
void
onActivityStarted(Activity activity) {
}
@Override
public
void
onActivityResumed(Activity activity) {
}
@Override
public
void
onActivityPaused(Activity activity) {
}
@Override
public
void
onActivityStopped(Activity activity) {
}
@Override
public
void
onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public
void
onActivityDestroyed(Activity activity) {
}
});
}
}
Step 2: Register it in the manifest file like the following
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:name=".MyApplicationContext" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>