标签:
Android手机一般不用时,都会通过电源键来锁定屏幕同时关闭屏幕灯。
其实从API Level 8 (也就是Android 2.2) 开始, Android提供了DevicePolicyManager类, 可以让你的应用程序也能执行屏幕锁定等操作。
锁定效果:
要让自己的应用实现该屏幕锁定,主要需要用到以下几个类:DevicePolicyManager
这是设备管理的主类。通过它可以实现屏幕锁定、屏幕亮度调节、出厂设置等功能。
DeviceAdminReceiver
该类继承自 BroadcastReceiver 。 从源码可以看到,其实就是实现了一个OnReceive方法,该方法中根据不同的Action,执行相应的操作。 比如,如果激活成功,那么Action就是ACTION_DEVICE_ADMIN_ENABLED, 据此调用 onEnabled 方法。
系统源码:
/** * Intercept standard device administrator broadcasts. Implementations * should not override this method; it is better to implement the * convenience callbacks for each action. */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_PASSWORD_CHANGED.equals(action)) { onPasswordChanged(context, intent); } else if (ACTION_PASSWORD_FAILED.equals(action)) { onPasswordFailed(context, intent); } else if (ACTION_PASSWORD_SUCCEEDED.equals(action)) { onPasswordSucceeded(context, intent); } else if (ACTION_DEVICE_ADMIN_ENABLED.equals(action)) { onEnabled(context, intent); } else if (ACTION_DEVICE_ADMIN_DISABLE_REQUESTED.equals(action)) { CharSequence res = onDisableRequested(context, intent); if (res != null) { Bundle extras = getResultExtras(true); extras.putCharSequence(EXTRA_DISABLE_WARNING, res); } } else if (ACTION_DEVICE_ADMIN_DISABLED.equals(action)) { onDisabled(context, intent); } }
具体中的简单引用:
屏幕锁定和恢复出厂设置
1.创建 MyAdmin 的广播接受者 继承 DeviceAdminReceiver
<receiver android:name=".MyAdmin"> <meta-data android:name="android.app.device_admin" android:resource="@xml/my_admin" /> <intent-filter> <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver>
my_admin.xml
<?xml version="1.0" encoding="utf-8"?> <device-admin xmlns:android="http://schemas.android.com/apk/res/android"> <uses-policies> <limit-password /> <watch-login /> <reset-password /> <force-lock /> <wipe-data /> </uses-policies> </device-admin>
2.注册广播接受者为admin设备
ComponentName mAdminName = new ComponentName(this, MyAdmin.class); if (mService != null) { if (!mService.isAdminActive(mAdminName)) { Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra (DevicePolicyManager.EXTRA_DEVICE_ADMIN,mAdminName); startActivity(intent); } }
3.获取IDevicePolicyManager
DevicePolicyManager dm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE); public void lock(View view){ dm.resetPassword("123", 0); //滑动解锁屏幕条后需要输入密码(方法中新设置的密码)才能真正解锁 dm.lockNow(); //恢复出厂设置. //dm.wipeData(0);
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/
Android IDevicePolicyManager实现手动锁屏
标签:
原文地址:http://my.oschina.net/ososchina/blog/493058