首頁 > 軟體

Android實現一鍵鎖屏功能

2022-10-23 18:00:03

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一鍵鎖屏內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com