SoFunction
Updated on 2025-03-11

Android implements one-click screen lock function

Android implements one-click screen lock

Create AdminReceiver

import ;
public class AdminReceiver extends DeviceAdminReceiver {
}

Create device_admin.xml in xml

<?xml version="1.0" encoding="utf-8"?>
    <device-admin xmlns:andro >
        <uses-policies>
            <force-lock />
        </uses-policies>
    </device-admin>

Add to manifest

<receiver
            android:name=".AdminReceiver"
            android:permission=".BIND_DEVICE_ADMIN"
            android:exported="false">
            <meta-data
                android:name=".device_admin"
                android:resource="@xml/device_admin" />

            <intent-filter>
                <action android:name=".DEVICE_ADMIN_ENABLED" />
            </intent-filter>
        </receiver>

Finally MainActivity

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class MainActivity extends AppCompatActivity {
    private ComponentName componentName;

    private void activeManager() {
        //Use implicit intent to call the system method to activate the specified device manager        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        (DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
        (DevicePolicyManager.EXTRA_ADD_EXPLANATION, "One-click lock screen");
        startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        ();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DevicePolicyManager dpm = (DevicePolicyManager)
                        getSystemService(Context.DEVICE_POLICY_SERVICE);
                componentName = new ComponentName(getApplicationContext(),
                        );
                if ((componentName)) {//Determine whether you have permission (the device manager is activated)                    ();// Directly lock the screen                    //Kill the current application                    (());
                } else {
                    activeManager();//Activate the device manager to obtain permission                }
            }
        }).start();
    }
}

This is the end of this article about Android implementing one-click lock screen. For more related content on Android, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!