I am using flutter and have disabled normal apps from recording the screen.
Here is the code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
The problem is there are some phones where screen recordings apps are pre-installed and above code can't stop them from recording the screen.
So is there any other way to stop these apps from recording the screen?
On other answers I saw that this was not possible but there are some apps on playstore which successfully achieve this. So there must be a way.
I was thinking, as screen recording apps are drawn over , they might be detected through a piece of code hence we can show a pop up while screen recording app is drawn over.
Is it possible ? If yes how can we detect if the app is drawn over our app.
Thanks.
As far as I'm aware, there is no official way to universally prevent screen grabs/recordings.
This is because FLAG_SECURE just prevents capturing on non-secure displays:
Window flag: treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
But apps that have elevated permissions can create a secure virtual display and use screen mirroring to record your screen, which does not respect the secure flag.
Read this article for more info:
That would mean that an Android device casting to a DRM-protected display like a TV would always display sensitive screens, since the concept of secure really means “copyrighted”. For apps, Google forestalled this issue by preventing apps not signed by the system key from creating virtual “secure” displays
Regarding how some apps still manage to do it, you could try these:
Check if there are any external/virtual displays connected, and hide/show your content based on that. see this
Don't show your content on rooted devices
Adding this code to my MainActivity.java solved the problem:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!this.setSecureSurfaceView()) {
Log.e("MainActivity", "Could not secure the MainActivity!");
}
}
private final boolean setSecureSurfaceView() {
ViewGroup content = (ViewGroup) this.findViewById(android.R.id.content);
//Intrinsics.checkExpressionValueIsNotNull(content, "content");
if (!this.isNonEmptyContainer((View) content)) {
return false;
} else {
View splashView = content.getChildAt(0);
//Intrinsics.checkExpressionValueIsNotNull(splashView, "splashView");
if (!this.isNonEmptyContainer(splashView)) {
return false;
} else {
View flutterView = ((ViewGroup) splashView).getChildAt(0);
//Intrinsics.checkExpressionValueIsNotNull(flutterView, "flutterView");
if (!this.isNonEmptyContainer(flutterView)) {
return false;
} else {
View surfaceView = ((ViewGroup) flutterView).getChildAt(0);
if (!(surfaceView instanceof SurfaceView)) {
return false;
} else {
((SurfaceView) surfaceView).setSecure(true);
this.getWindow().setFlags(8192, 8192);
return true;
}
}
}
}
}
private final boolean isNonEmptyContainer(View view) {
if (!(view instanceof ViewGroup)) {
return false;
} else {
return ((ViewGroup) view).getChildCount() >= 1;
}
}
Import the required things.
I'm developing an app with React Native for both iOS and Android, and I am trying to prevent device-specific scaling of the display in the app.
For text/font size scaling, putting the following code in the root-level App.js file solves the issue for both iOS and Android:
if (Text.defaultProps == null) {
Text.defaultProps = {};
}
Text.defaultProps.allowFontScaling = false;
However, Android devices have the following Display size setting that is still being applied:
I've tried (unsuccessfully) to piece together a variety of "solutions" to this issue that I've found in answers to the following questions:
Change the system display size programatically Android N
Disabling an app or activity zoom if Setting -> Display -> Display size changed to Large or small
how to prevent system font-size changing effects to android application?
I've often found references to a BaseActivity class that extends the Activity class. My understanding is that it is inside of that class where I would be writing a method (let's call it adjustDisplayScale) to make changes to the Configuration of the Context that I get from Resources, and that then I would be calling adjustDisplayScale within the onCreate() method after super.onCreate() in the MainApplication.java file.
As of now, in this directory I just have two files - MainApplication.java and MainActivity.java.
I've attempted creating a new Module and associated Package file to implement adjustDisplayScale following these instructions and it did not work:
https://facebook.github.io/react-native/docs/text.html
I've attempted placing implementing the functionality of adjustDisplayScale within the onCreate() like this and it did not work:
#Override
public void onCreate() {
super.onCreate();
Context context = getApplicationContext();
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
configuration.fontScale = 1f;
DisplayMetrics metrics = res.getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = 1f;
configuration.densityDpi = (int) res.getDisplayMetrics().xdpi;
context = context.createConfigurationContext(configuration);
SoLoader.init(this, /* native exopackage */ false);
}
A potentially promising answer included the following:
protected override void AttachBaseContext(Context #base) {
var configuration = new Configuration(#base.Resources.Configuration);
configuration.FontScale = 1f;
var config = Application.Context.CreateConfigurationContext(configuration);
base.AttachBaseContext(config);
}
But when I tried to utilize this, I got errors about not recognizing the symbol #base.
Some background... I've done 99% of my work on this project in JavaScript / React Native and I have almost no understanding about things like Resources, Context, Configuration, and DisplayMetrics associated with Android development AND the last time I wrote code in Java was 10 years ago. I've spent a number of agonizing hours trying to figure this out and any help would be greatly appreciated.
ps. I am well-aware that accessibility settings exist for a good reason so please spare me the diatribe I've seen in so many "answers" on why I need to fix my UI to work with accessibility settings rather than disable them.
NOTE
I strongly discourage applying such a solution. In a certain way, Screen Zoom just "emulates" different screen sizes and densities in the same device. So, if your app can't handle well a specific screen zoom level, it means that your app may not be displayed correctly on a real screen out there. If your app can't support screen changes, tell the user about it...
There are some docs about screen sizes in the Android Developer and that's how you should handle different screen sizes.
On Android 12, it seems this the context created via context.createConfigurationContext(configuration) is imuttable. So, you may have problems on Android 12 when rotating the device, for example. context.getResources().getxxxxx() may return portrait resources (because the context was created in portrait) instead of landscape resources (the new orientation)
Support Different Screen Sizes
supports-screens-element
The answer below is just a "hack" where I tried to circumvent the screen zoom feature. I don't use that on my apps and I strongly recommend dealing with the screen zoom in a more conventional way.
Answer
My first answer does not work if you change the screen resolution. On Samsung devices, you can change the screen zoom but you can also change the screen resolution on some models (Settings->Display->Screen Resolution-> HD, FHD, WQHD etc).
So, I came up with a different code which seems to work with that feature as well. Just, please, note I can't fully test this code since I don't have too many devices to test. On those devices I tested, it seems to work.
One additional note. Ideally, you don't need to use such kind of code to circumvent the screen zoom. In a certain way, the screen zoom is just "simulating" bigger or smaller screens. So, if your app properly supports different screen sizes, you don't need to completely "disable" the screen zoom.
public class BaseActivity extends AppCompatActivity {
#TargetApi(Build.VERSION_CODES.N)
private static final int[] ORDERED_DENSITY_DP_N = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#TargetApi(Build.VERSION_CODES.N_MR1)
private static final int[] ORDERED_DENSITY_DP_N_MR1 = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_260,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_340,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#TargetApi(Build.VERSION_CODES.P)
private static final int[] ORDERED_DENSITY_DP_P = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_260,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_340,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_440,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("TESTS", "Dimension: " + getResources().getDimension(R.dimen.test_dimension));
}
#Override
protected void attachBaseContext(final Context baseContext) {
Context newContext = baseContext;
// Screen zoom is supported from API 24+
if(Build.VERSION.SDK_INT >= VERSION_CODES.N) {
Resources resources = baseContext.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
Log.v("TESTS", "attachBaseContext: currentDensityDp: " + configuration.densityDpi
+ " widthPixels: " + displayMetrics.widthPixels + " deviceDefault: " + DisplayMetrics.DENSITY_DEVICE_STABLE);
if (displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
// display_size_forced exists for Samsung Devices that allow user to change screen resolution
// (screen resolution != screen zoom.. HD, FHD, WQDH etc)
// This check can be omitted.. It seems this code works even if the device supports screen zoom only
if(Settings.Global.getString(baseContext.getContentResolver(), "display_size_forced") != null) {
Log.v("TESTS", "attachBaseContext: This device supports screen resolution changes");
// density is densityDp / 160
float defaultDensity = (DisplayMetrics.DENSITY_DEVICE_STABLE / (float) DisplayMetrics.DENSITY_DEFAULT);
float defaultScreenWidthDp = displayMetrics.widthPixels / defaultDensity;
Log.v("TESTS", "attachBaseContext: defaultDensity: " + defaultDensity + " defaultScreenWidthDp: " + defaultScreenWidthDp);
configuration.densityDpi = findDensityDpCanFitScreen((int) defaultScreenWidthDp);
} else {
// If the device does not allow the user to change the screen resolution, we can
// just set the default density
configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
}
Log.v("TESTS", "attachBaseContext: result: " + configuration.densityDpi);
newContext = baseContext.createConfigurationContext(configuration);
}
}
super.attachBaseContext(newContext);
}
#TargetApi(Build.VERSION_CODES.N)
private static int findDensityDpCanFitScreen(final int densityDp) {
int[] orderedDensityDp;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
orderedDensityDp = ORDERED_DENSITY_DP_P;
} else if(Build.VERSION.SDK_INT >= VERSION_CODES.N_MR1) {
orderedDensityDp = ORDERED_DENSITY_DP_N_MR1;
} else {
orderedDensityDp = ORDERED_DENSITY_DP_N;
}
int index = 0;
while (densityDp >= orderedDensityDp[index]) {
index++;
}
return orderedDensityDp[index];
}
}
ORIGINAL ANSWER
You can try following code (overriding attachBaseContext). This will "disable" the screen zoom in on your app. This is the way to re-scale the whole screen at once.
#Override
protected void attachBaseContext(final Context baseContext) {
Context newContext;
if(Build.VERSION.SDK_INT >= VERSION_CODES.N) {
DisplayMetrics displayMetrics = baseContext.getResources().getDisplayMetrics();
Configuration configuration = baseContext.getResources().getConfiguration();
if (displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
// Current density is different from Default Density. Override it
configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
newContext = baseContext.createConfigurationContext(configuration);
} else {
// Same density. Just use same context
newContext = baseContext;
}
} else {
// Old API. Screen zoom not supported
newContext = baseContext;
}
super.attachBaseContext(newContext);
}
On that code, I check if the current density is different from the Device's default density. If they are different,
I create a new context using default density (and not the current one). Then, I attach this modified context.
You must do that on every Activity. So, you can create a BaseActivity and add that code there. Then, you just need to update your activities in order to extend BaseActivity
public class BaseActivity extends AppCompatActivity {
#Override
protected void attachBaseContext(final Context baseContext) {
....
}
}
Then, in your activities:
public class MainActivity extends BaseActivity {
// Since I'm extending BaseActivity, I don't need to add the code
// on attachBaseContext again
// If you don't want to create a base activity, you must copy/paste that
// attachBaseContext code into all activities
}
I tested this code with:
Log.v("Test", "Dimension: " + getResources().getDimension(R.dimen.test_dimension));
Different Screen Zoom (using that code):
2019-06-26 16:38:17.193 16312-16312/com.test.testapplication V/Test: Dimension: 105.0
2019-06-26 16:38:35.545 16312-16312/com.test.testapplication V/Test: Dimension: 105.0
2019-06-26 16:38:43.021 16579-16579/com.test.testapplication V/Test: Dimension: 105.0
Different Screen Zoom (without that code):
2019-06-26 16:42:53.807 17090-17090/com.test.testapplication V/Test: Dimension: 135.0
2019-06-26 16:43:19.381 17090-17090/com.test.testapplication V/Test: Dimension: 120.0
2019-06-26 16:44:00.125 17090-17090/com.test.testapplication V/Test: Dimension: 105.0
So, using that code, I can get the same dimension in pixels regardless of the zoom level.
Edit
What I Want:
Disable user to use split screen mode for any application in his phone.
What I've already done:
To disable split screen mode, I need to detect which method is called and in that method I can further add a functionality to draw a custom view over it or quickly pull down split screen window.
I'm looking into AccessibilityEvents as well, might be I need to parse and filter some keywords to get to split screen detection.
So what can be that method in which Android will tell that user has just started to use split screen mode. And how can I then quickly pull down split screen window?
You can detect when any application goes to split screen mode if you have asked AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED event when registering for accessibility service.
Possible way to detect Split screen mode:
In the onAccessibilityEvent(AccessibilityEvent event) function we need to write event.getSource().getContentDescription(); and search for "Split" or "Dismiss" or other keywords in the string, depends upon various custom roms. Whenever application comes in split screen mode, its content description is set as 'Split Whatsapp' etc. That's how we can detect when any particular application comes in split screen mode.
Possible way to block usage of split screen mode for any app:
After detecting you need to add this line in order to make it impossible for the user to utilize split screen mode. It will just dock the current application window.
performGlobalAction(AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
There are other global events as well to perform an action like:
GLOBAL_ACTION_BACK
GLOBAL_ACTION_HOME
GLOBAL_ACTION_LOCK_SCREEN
GLOBAL_ACTION_NOTIFICATIONS
GLOBAL_ACTION_POWER_DIALOG
GLOBAL_ACTION_QUICK_SETTINGS
GLOBAL_ACTION_RECENTS
GLOBAL_ACTION_TAKE_SCREENSHOT
GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN
But most suitable for this scenario is: GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN
public class AppAccessibility extends AccessibilityService {
#Override
protected void onServiceConnected() {
super.onServiceConnected();
AccessibilityServiceInfo config = new AccessibilityServiceInfo();
config.eventTypes = AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
if (Build.VERSION.SDK_INT >= 16) {
config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS;
}
setServiceInfo(config);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event != null && event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
if (event.getSource() != null && event.getSource().getContentDescription() != null) {
if (event.getSource().getContentDescription().toString().contains("Split")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
performGlobalAction(AccessibilityService.GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN));
}
}
}
}
}
How to check if any system dialog (like the one below or USSD) is displayed in Android ?
Programmatic way or cmd root way?
Any variants.
You can theoretically do this using the AccessibilityService, but it is rather complicated and may or may not work on different devices. Users will need to manually enable accessibility features for your application. You can get callbacks from Android whenever any window is opened and you can then interrogate the window to determine if it has specific text in it or belongs to a specific package, etc. This is a "brute force" approach, but it can be useful in some situations.
A system dialog is an activity. You can detect it by the top activity class name using ActivityManager.
final ActivityManager manager = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
In devices with API Level less than 23 (M):
final List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
final ComponentName componentName = runningTasks.get(0).topActivity;
final String className = componentName.getClassName();
if (className.equals("YOUR_EXPECTED_ACTIVITY_CLASS_NAME")) {
// do something
}
In newer devices:
final List<ActivityManager.AppTask> appTasks = manager.getAppTasks();
final ComponentName componentName = appTasks.get(0).getTaskInfo().topActivity;
final String className = componentName.getClassName();
if (className.equals("YOUR_EXPECTED_ACTIVITY_CLASS_NAME")) {
// do something
}
Or in this case, you can check if the device is in airplane mode before starting the activity:
private boolean isAirplaneModeOn(final Context context) {
final int airplaneMode = Settings.System.getInt(
context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON,
0
);
return airplaneMode != 0;
}
...
if (!isAirplaneModeOn(this)) {
// do something
}
Your question made me think of a solution in use by the permissions management in Android 6+. Have you ever seen the error message if a Toast or system alert dialog opens up when trying to set permissions?
Android "Screen Overlay Detected" message if user is trying to grant a permission when a notification is showing
The way they did it is by overriding the dispatchTouchEvent method in Activity. This can check if anything is 'in the way' intercepting touch events. You can use your special Activity as a base class for any Activity in your app that you wish to detect any overlays on it.
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
mObscured = (event.getFlags() & MotionEvent.FLAG_WINDOW_IS_OBSCURED) != 0;
return super.dispatchTouchEvent(event);
}
Add a public method to check at any given time if your activity is obscured
public boolean isObscured() {
return mObscured;
}
You should be careful - as it's not clear from the question - if a second Activity from a system or privileged app is at the front of the stack then your own activity will no longer be receiving touch events. This is to capture the fragments, toasts, floating widgets and other items that may share the view hierarchy.
I have created a class that inherits from Steema.TeeChart.TChart I am trying to disable panning and zooming, I have the below code but it still allows the user to pan and zoom on the device.
public class BaseChart : TChart
{
public BaseChart(Context context, string headerTitle)
: base(context)
{
_headerTitle = headerTitle;
SetDefaults();
}
private void SetDefaults()
{
Chart.Zoom.Allow = false;
Chart.Panning.Allow = ScrollModes.None;
Zoom.Allow = false;
Panning.Allow = ScrollModes.None;
}
}
TeeChart .NET standard zoom & scrolling is not working at the present moment in the Mono for Android version. We plan supporting it in future releases feature request being TM63016321 in our issue tracking system. Recently we implemented a new feature for MfA which disables both zooming and scrolling:
tChart1.Zoom.Style = Steema.TeeChart.ZoomStyles.None;
UPDATE: A new Zoom.Style option has been implemented: ZoomStyles.Classic. Now you can choose if you want to toggle zooming, panning and which directions are supported for both. A maintenance release has been published supporting that. The new version explains how to use ZoomStyles.Classic in the zooming/panning tutorial included, for example:
tChart1.Zoom.Allow = true;
tChart1.Zoom.Direction = Steema.TeeChart.ZoomDirections.Both;
tChart1.Panning.Allow = Steema.TeeChart.ScrollModes.Horizontal;