Android click the button to turn off the screen

Keywords: Android xml encoding

Sometimes we see some pad of control equipment in some hotels. When we click the close button, we will turn off the device and turn off the pad screen. Today, we will try to realize the function of clicking the button to turn off the screen.

1. Create an XML folder under res and a resource file of lock_screen.xml. The source code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-policies>
        <!--Lock screen-->
        <force-lock />
    </uses-policies>
</device-admin>

2. Create a broadcast receiver and inherit DeviceAdminReceiver

public class LockReceiver extends DeviceAdminReceiver {
    @Override
    public void onEnabled(Context context, Intent intent) {
        super.onEnabled(context, intent);
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        super.onDisabled(context, intent);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
    }
}

Register this radio receiver in Android manifest

<!--Extinguishing screen-->
<receiver android:name=".utils.LockReceiver"
            android:permission="android.permission.BIND_DEVICE_ADMIN">
    <meta-data android:name="android.app.device_admin"
                android:resource="@xml/lock_screen" />
    <intent-filter>
        <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
    </intent-filter>
</receiver>

3. Authorization management authority
In the source code, we need to authorize the management authority manually. When the application is installed for the first time, an authorization pop-up box will pop up and select "allow"

//Screen need
private DevicePolicyManager policyManager;
private ComponentName componentName;

//==============Screen out================
private void lockScreen() {
        if (policyManager.isAdminActive(componentName)) {
            policyManager.lockNow();
        }
    }

private void activeManager() {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "screenLock");
        startActivity(intent);
    }

//==============Screen out================

The management authority has been authorized when judging in the method of declaration cycle

if (!policyManager.isAdminActive(componentName)) {
            activeManager();
        }

Finally, calling the lockScreen() method in the click event of the button can achieve the function of the screen.
Note: when we uninstall this app, we need to cancel the previously authorized management permission, otherwise we will be prompted that we cannot uninstall it

Posted by bonekrusher on Thu, 02 Apr 2020 07:55:25 -0700