Android startService 启动自动解锁点亮屏幕

做提醒功能的一个服务,自动解锁+亮屏。

写一个Activity启动该服务即可,用一个线程开启服务,要是黑屏的状态下启动才有效果。

import Android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

public class ScreenService extends Service {

//声明键盘管理器
KeyguardManager mKeyguardManager = null;  
//声明键盘锁
private KeyguardLock mKeyguardLock = null;  
//声明电源管理器
private PowerManager pm;
private PowerManager.WakeLock wakeLock;

@Override  
public IBinder onBind(Intent arg0) {  
return null;  
}  
@Override  
public void onCreate() {  
//获取电源的服务
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//获取系统服务
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
super.onCreate();  
}  
@Override  
public void onStart(Intent intent, int startId){ 
//点亮亮屏
wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wakeLock.acquire();
Log.i("Log : ", "------>mKeyguardLock");
//初始化键盘锁,可以锁定或解开键盘锁
mKeyguardLock = mKeyguardManager.newKeyguardLock("");  
//禁用显示键盘锁定
mKeyguardLock.disableKeyguard();  
}
@Override
public void onDestroy() {
wakeLock.release();
super.onDestroy();
}  
}

记得需要在AndroidManifest文件中加入
<!-- 解锁的权限 -->
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>
<!-- 亮屏的权限 -->
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>

用startService 启动的,屏幕一直不会彻底变黑,在Activity的stop方法中stopService,
然后再Service的destory方法中将亮屏的给释放 mWakelock.release();
这样就不会一直亮着了。


屏幕虽然亮了,可是并没有像正常操作那样的彻底变亮啊,这种让屏幕变亮只是亮一点,还是很暗。


public void acquire () //该方法只是确保屏幕会被唤醒
Makes sure the device is on at the level you asked when you created the wake lock.

public void acquire (long timeout) //参数表示唤醒的时间,时间过后,会自动释放该锁
Makes sure the device is on at the level you asked when you created the wake lock. The lock will be released after the given timeout.

API有个参数可以点亮

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwfyjw.html