Skip to content

Commit

Permalink
Android screen security implementation forced to run on the main thre…
Browse files Browse the repository at this point in the history
…ad to fix bug "Exception: Only the original thread that created a view hierarchy can touch its views".
  • Loading branch information
FabriBertani committed Jul 3, 2023
1 parent 34a3e8a commit 2a4d572
Showing 1 changed file with 20 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using Android.Views;
using Android.OS;
using Android.Views;

namespace Plugin.Maui.ScreenSecurity;

partial class ScreenSecurityImplementation : IScreenSecurity
{
private static volatile Handler? handler;

/// <summary>
/// Prevent screen content from being exposed when the app
/// is sent to <b>Background</b> or the <b>Recents screen</b>.
Expand All @@ -13,9 +16,15 @@ public void EnableScreenSecurityProtection()
{
try
{
var activity = Platform.CurrentActivity;
if (handler?.Looper != Looper.MainLooper)
handler = new Handler(Looper.MainLooper!);

handler?.Post(() =>
{
var activity = Platform.CurrentActivity;

activity?.Window?.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
activity?.Window?.SetFlags(WindowManagerFlags.Secure, WindowManagerFlags.Secure);
});
}
catch (Exception ex)
{
Expand All @@ -33,9 +42,15 @@ public void DisableScreenSecurityProtection()
{
try
{
var activity = Platform.CurrentActivity;
if (handler?.Looper != Looper.MainLooper)
handler = new Handler(Looper.MainLooper!);

handler?.Post(() =>
{
var activity = Platform.CurrentActivity;

activity?.Window?.ClearFlags(WindowManagerFlags.Secure);
activity?.Window?.ClearFlags(WindowManagerFlags.Secure);
});
}
catch (Exception ex)
{
Expand Down

0 comments on commit 2a4d572

Please sign in to comment.