我主要是运用在用户在锁屏状态下收到新的通知时,同时能够点亮屏幕。
一个工具类
package com.example.testone;
import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;
public class WakeAndLock {
Context context;
PowerManager pm;
PowerManager.WakeLock wakeLock;
public WakeAndLock() {
context = MyApplication.getInstance();
pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeAndLock");
}
/**
* 唤醒屏幕
*/
public void screenOn() {
wakeLock.acquire();
android.util.Log.i("cxq", "screenOn");
}
/**
* 熄灭屏幕
*/
public void screenOff() {
pm.goToSleep(SystemClock.uptimeMillis());
android.util.Log.i("cxq", "screenOff");
}
}
获取屏幕状态用这两句
// 获取屏幕状态;
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean screen = pm.isScreenOn();
别忘了添加权限
<!-- 屏幕唤醒 -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- 屏幕熄灭 -->
<user-permission android:name="android.permission.DEVICE_POWER" />
屏幕熄灭需要管理者权限,编译会报错,删除错误就能通过编译了,但是最好还是不要用,没有权限会崩掉。
原文地址:http://www.ithao123.cn/content-10529774.html