android DevicePolicyManager实现一键锁屏

时间:2021-08-03 18:35:06

本文章一部分资料来源于网上

1.实现一键锁屏关键是DevicePolicyManager这个类,然后使用lockNow();方法。

2.DevicePolicyManager类,可以让你的做软件获得系统级别的操作,例如锁屏,恢复出厂设置等。要使用这个类就要填加一个权限android:permission="android.permission.BIND_DEVICE_ADMIN"。

3.相关的代码

package com.example.mylock;

import android.os.Bundle;
import android.R.anim;
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.view.Menu; public class MainActivity extends Activity {
private DevicePolicyManager policyManager;
private ComponentName componentName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policyManager=(DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
componentName=new ComponentName(this, AdminReceiver.class);
mylock();
android.os.Process.killProcess(android.os.Process.myPid());
}
private void mylock(){
boolean active=policyManager.isAdminActive(componentName);
if(!active){
activeManage();
policyManager.lockNow();
}
if(active){
policyManager.lockNow();
}
}
private void activeManage(){
Intent intent=new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "--其他描述--");
startActivityForResult(intent, 0);
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} }

4.DevicePolicyManager的其他成员方法

1 lockNow() //锁屏
2 resetPassword(String password, int flags) //重置密码
3 setMaximumFailedPasswordsForWipe(ComponentName admin, int num) //设置密码输入失败的最大次数
4 setMaximumTimeToLock(ComponentName admin, long timeMs) //设置开始锁屏的最大时间(据我理解,用于某些应用哪怕不进行操作,也不希望锁屏的时候)
5 setPasswordMinimumLength(ComponentName admin, int length) //设置密码最短长度
6 setPasswordQuality(ComponentName admin, int quality) //设置密码质量?
7 wipeData(int flags) //擦出用户数据