项目中遇到了需要设备息屏和唤醒屏幕的需求,查了很多资料,有说广播锁屏和唤醒的,试了下:结果是无效的,这在Android4之前还可以试试。
直接上代码:
AndroidManifest.xml添加
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<receiver android:name=".DeviceReceiver" android:exported="false" android:permission="android.permission.BIND_DEVICE_ADMIN"> <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin" /> <intent-filter> <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver>
device_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>
MainActivity.java中实现:
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mAdmin;
mDevicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
mAdmin = new ComponentName(this, DeviceReceiver.class);
if(mDevicePolicyManager.isAdminActive(mAdmin)){
//已获取到权限
wakeDevice();
}else{
ActiveMNG();
}
/**
*获取设备权限
*/
private void ActiveMNG(){
Intent intent = new Intent (DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"--其他描述--");
startActivityForResult(intent , 0 );
}
/**
* 锁屏后唤醒屏幕
*/
public void wakeDevice(){
try{
mDevicePolicyManager.lockNow();
Thread.sleep(500);
}catch (Exception exception){
}finally {
KeyguardManager km= (KeyguardManager) this.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl =km.newKeyguardLock("unLock");
kl.disableKeyguard();
PowerManager mgr = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = mgr.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright");
wl.acquire();
wl.release();
}
}
DeviceReceiver.class
import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class DeviceReceiver extends DeviceAdminReceiver{
@Override
public void onEnabled(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("TAG000","------onEnabled-------");
super.onEnabled(context, intent);
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("TAG000","--------onReceive-----");
super.onReceive(context, intent);
}
}