源码片段
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
, LockReceiver.
class
);
if
(policyManager.isAdminActive(componentName)) {
//判断是否有权限(激活了设备管理器)
policyManager.lockNow();
// 直接锁屏
finish();
}
else
{
activeManager();
//激活设备管理器获取权限
finish();
}
}
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);
}
}