锁屏代码,有个问题,在锁屏后,屏幕还是会亮起,只不过是锁定状态而已,并不会关闭屏幕。
在需要锁屏地方使用以下代码:
DevicePolicyManager policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName componentName = new ComponentName(MainActivity.this,
LockReceiver.class);
if (policyManager.isAdminActive(componentName)) {// 判断是否有权限(激活了设备管理器)
policyManager.lockNow();// 直接锁屏
// android.os.Process.killProcess(android.os.Process.myPid());
} else {
activeManager(componentName);// 激活设备管理器获取权限
}
private void activeManager(ComponentName componentName) {
// 使用隐式意图调用系统方法来激活指定的设备管理器
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "锁屏");
startActivity(intent);
}
注册一个Receiver
<receiver
android:name="LockReceiver"
android:description="@string/app_name"
android:label="@string/app_name"
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>
配置权限文件lock_screen.xml,将文件放置在/res/xml/下
<?xml version="1.0" encoding="UTF-8"?>
<device-admin xmlns:android="http://schemas.android/apk/res/android" >
<uses-policies>
<!-- 强行锁定(这里只需要这个) -->
<force-lock />
<!-- 清除所有数据(恢复出厂设置) -->
<wipe-data />
<!-- 重置密码 -->
<reset-password />
<!-- 限制密码选择 -->
<limit-password />
<!-- 监控登录尝试 -->
<watch-login />
</uses-policies>
</device-admin>
实现Receiver
package com.huron.xx;
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
public class LockReceiver extends DeviceAdminReceiver {
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
System.out.println("onreceiver");
}
@Override
public void onEnabled(Context context, Intent intent) {
System.out.println("激活使用");
super.onEnabled(context, intent);
}
@Override
public void onDisabled(Context context, Intent intent) {
System.out.println("取消激活");
super.onDisabled(context, intent);
}
}