Disable screenshot function in a certain page

DannyPhamDannyPham USMember ✭✭✭

Hello, I know that we are able to disable the screenshot function for the whole Android app by doing this: this.Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);

Now I want to go further by doing that in a certain page, rather than the whole app. Is it possible to do that? Thanks in advance.

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai
    this.Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
    

    This will only affect the current activity. If you move to another activity you can take screenshots there.
    I tested it on my real physical phone and place it in the OnCreate like:

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    
        Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
    
        // Create your application here
        SetContentView(Resource.Layout.activity_main);
    
        // ...
    }
    
  • DannyPhamDannyPham USMember ✭✭✭

    @LandLu thanks for your answer. However, I'm using Xamarin Forms, and can't specify which activity that needs to be modified. If I put that code into MainActivity.cs, then the whole app will be affected.

  • LandLuLandLu Member, Xamarin Team Xamurai

    Forms only has one activity so if you do this configuration in the MainActivity all the pages can't be captured.
    You can subscribe a MessagingCenter in the OnCreate event of the main activity. When the page displays send a signal to notify the activity to disable the screenshot capturing. And enable it when it disappears.
    Here is the code:

    // Subscribe in the activity
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
    
        base.OnCreate(savedInstanceState);
    
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    
        MessagingCenter.Subscribe<object, bool>(this, "LockScreenshot", (sender, shouldLock) =>
        {
            if (shouldLock)
            {
                Window.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
            }
            else
            {
                Window.ClearFlags(WindowManagerFlags.Secure);
            }
        });
    }
    
    // Send messages on a particular page
    protected override void OnAppearing()
    {
        base.OnAppearing();
    
        MessagingCenter.Send<object, bool>(this, "LockScreenshot", true);
    }
    
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
    
        MessagingCenter.Send<object, bool>(this, "LockScreenshot", false);
    }
    
Sign In or Register to comment.