Android通过广播实现灭屏和亮屏

方法:

PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
/*        PARTIAL_WAKE_LOCK:保持CPU 运转,屏幕和键盘灯有可能是关闭的。
        SCREEN_DIM_WAKE_LOCK:保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯
        SCREEN_BRIGHT_WAKE_LOCK:保持CPU 运转,允许保持屏幕高亮显示,允许关闭键盘灯
        FULL_WAKE_LOCK:保持CPU 运转,保持屏幕高亮显示,键盘灯也保持亮度
        ACQUIRE_CAUSES_WAKEUP:强制使屏幕亮起,这种锁主要针对一些必须通知用户的操作.
                ON_AFTER_RELEASE:当锁被释放时,保持屏幕亮起一段时间*/
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK  | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE , "matrix");
wakeLock.acquire();
//wakeLock.acquire(10000);
wakeLock.release();

1、要实现灭屏和唤醒,需要在Manifest文件添加如下权限:

  
<uses-permission android:name="android.permission.WAKE_LOCK" />  
  
<user-permission android:name="android.permission.DEVICE_POWER" /> 

2、几个主要地方

import android.content.Context;  
import android.os.PowerManager;  
import android.os.SystemClock;

    PowerManager pm;  
    PowerManager.WakeLock wakeLock = null;

onCreate :

pm = (PowerManager) getApplication().getSystemService(Context.POWER_SERVICE);  
wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP  
                | PowerManager.SCREEN_DIM_WAKE_LOCK, "matrix"); 

灭屏和亮屏:

/** 
* 亮屏 
*/  
public void screenOn() {  
    wakeLock.acquire();  
    Log.w(TAG, "screenOn");  
}  

/** 
* 释放并直接灭屏 
*/  
public void screenOff() { 
    wakeLock.release();  
    pm.goToSleep(SystemClock.uptimeMillis());  
    Log.w(TAG, "screenOff");  
}  

3、接收广播,用于控制屏幕的唤醒和熄灭,这样其他APP中也可以通过广播来实现屏幕的控制。

private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {

    String SCREEN_MODE = "on";
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (action.equals("com.screen.ext.on")) {
            String screen_state = intent.getStringExtra("screen_state");

        Log.d(TAG, "com.screen.ext.on screen_state = "  + screen_state);
            if(SCREEN_MODE.equals(screen_state)){
                screenOn();
            }
            else {
                screenOff();
            }
        }
    }
}

4,发送广播控制

sendBroadcast(new Intent("com.screen.ext.on").putExtra("screen_state", "on"));

sendBroadcast(new Intent("com.screen.ext.on").putExtra("screen_state", "off"));

最后注意一点:
wakeLock.acquire() 和 wakeLock.release() 最好能成对出现,因为android系统检测到wakeLock acquire之后没有被release,系统就不会进入休眠状态。

你可能感兴趣的:(android)