Android 锁屏功能
程序员文章站
2022-05-27 09:06:36
...
开发中遇到锁屏和唤醒屏幕的功能,顺便就想开发一个“一键锁屏”的app,然后就有了这篇文章。。。哈哈哈
首次打开必须用户手动授权锁屏功能;如下图:点击**
第一步、在AndroidManifest.xml中配置:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission android:name="android.permission.DEVICE_POWER" />
<receiver android:name=".screenlock.MyDeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/my_device_admin" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
第二步、配置中的my_device_admin代码 、MyDeviceAdminReceiver的代码
2.1、在res/xml中自定义my_device_admin.xml文件,我只配置了锁屏权限
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<!--
limit-password 设置密码的规则
watch-login 监控屏幕解锁尝试次数
reset-password 更改屏幕解锁密码
force-lock 设备自动锁屏
wipe-data 清除所有数据(恢复出厂设置)
-->
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
2.2、新建MyDeviceAdminReceiver类
//可以不实现任何方法,继承空类即可
public class MyDeviceAdminReceiver extends DeviceAdminReceiver {
// @Override
// public void onReceive(Context context, Intent intent) {
// super.onReceive(context, intent);
// Log.e("snoww", "onreceiver");
// }
//
// @Override
// public void onEnabled(Context context, Intent intent) {
// Log.e("snoww", "**使用");
// super.onEnabled(context, intent);
// }
//
// @Override
// public void onDisabled(Context context, Intent intent) {
// Log.e("snoww", "取消**");
// super.onDisabled(context, intent);
// }
}
第三步、 mainactivity的完整代码:
public class MainActivity extends AppCompatActivity {
DevicePolicyManager dpm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lock();
}
//锁屏
private void lock() {
dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
ComponentName componentName = new ComponentName(this, MyDeviceAdminReceiver.class);
// 判断该组件是否有系统管理员的权限
boolean isAdminActive = dpm.isAdminActive(componentName);
if (!isAdminActive) {//这一句一定要有...
Intent intent = new Intent();
intent.setAction(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
startActivityForResult(intent, 101);
}
//isAdminActive 为false,直接调用dpm.lockNow()会报java.lang.SecurityException: No active admin owned by uid 10510 for policy #3
if (isAdminActive) {
dpm.lockNow();
//杀掉进程
android.os.Process.killProcess(android.os.Process.myPid());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//这种方式可能会造成自动重启
// android.os.Process.killProcess(android.os.Process.myPid());
//授权技术关闭应用
finish();
}
}
最后将mainactivity的主题设置为透明,就可以了;