Is it possible to lock tablet screen after 15 minutes using a service and a broadcast receiver ?

Hi,

I'm trying to lock the screen of my tablet after being unplugged for 15 minutes using a broadcast receiver that detects if the tablet is plugged to an alimentation or not.

This broadcast receiver is placed into a service.

If the power is plugged, a Toast will display "Power Connected" , if unplugged, a Toast will display "Power Disconnected". And it works from any activity of my application. (That part is running well)

I'm blocking on "how to lock/turn off screen the tablet when it happens".

I'd also need to unlock that tablet when the power is plugged. I removed all lockscreens from the settings, there's no issue with slide to unlock or enter the pin or pattern.

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    To lock the screen, try the following code

    public class MainActivity : AppCompatActivity
    {
        DevicePolicyManager policyManager;
        ComponentName componentName;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            policyManager = (DevicePolicyManager)ApplicationContext.GetSystemService(Context.DevicePolicyService);
            componentName = new ComponentName(this, typeof(Receive));
    
            if (policyManager.IsAdminActive(componentName))
            {
                policyManager.LockNow();
            }
            else
            {
                activieManage();
            }
        }
    
        private void activieManage()
        {
            Intent intent = new Intent(DevicePolicyManager.ActionAddDeviceAdmin);
    
            //permission
            intent.PutExtra(DevicePolicyManager.ExtraDeviceAdmin, componentName);
    
            //description
            intent.PutExtra(DevicePolicyManager.ExtraAddExplanation, "descrpiton");
    
            StartActivityForResult(intent, 101);
        }
    
        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            if (requestCode == 101 && resultCode == Result.Ok)
            {
                policyManager.LockNow();
            }
            else
            {
                //activieManage();
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }
    }
    

    Refer to: https://blog.csdn.net/luoposhusheng/article/details/52557519

  • MohanasundharamMohanasundharam Member ✭✭✭
    edited June 13

    Is it Applicable for Mobile?

Sign In or Register to comment.