Android實現一鍵鎖屏功能

android實現一鍵鎖屏

創建AdminReceiver

import android.app.admin.DeviceAdminReceiver;
public class AdminReceiver extends DeviceAdminReceiver {
}

在xml中創建device_admin.xml

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

在manifest中加入

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

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

最後MainActivity

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.os.SystemClock;

public class MainActivity extends AppCompatActivity {
    private ComponentName componentName;

    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, "一鍵鎖屏");
        startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DevicePolicyManager dpm = (DevicePolicyManager)
                        getSystemService(Context.DEVICE_POLICY_SERVICE);
                componentName = new ComponentName(getApplicationContext(),
                        AdminReceiver.class);
                if (dpm.isAdminActive(componentName)) {//判斷是否有權限(激活瞭設備管理器)
                    dpm.lockNow();// 直接鎖屏
                    //殺死當前應用
                    Process.killProcess(Process.myPid());
                } else {
                    activeManager();//激活設備管理器獲取權限
                }
            }
        }).start();
    }
}

到此這篇關於Android實現一鍵鎖屏的文章就介紹到這瞭,更多相關android一鍵鎖屏內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: