应用层唤醒/关闭屏幕

应用层唤醒屏幕及强制系统休眠

package com.example.hello;

import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.SystemClock; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.Menu;

public class MainActivity extends Activity {  protected static final String TAG = "MainActivity";  private Handler mHandler;  PowerManager pm;  WakeLock mWakeLock;  PowerManager.WakeLock wl;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         pm = (PowerManager)getSystemService(Context.POWER_SERVICE);         /*mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WhatEver");         Log.v(TAG, "PARTIAL_WAKE_LOCK");    mWakeLock.acquire();*/       //Forces the device to go to sleep.    pm.goToSleep(SystemClock.uptimeMillis());         mHandler = new Handler(){

   @Override    public void handleMessage(Message msg) {     Log.v(TAG, "handleMessage");     switch(msg.what){     case 1:      wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |   //这个参数是手机点亮的程度,(什么Cpu,屏幕亮度,键盘灯),可以理解为通过Android组件(Activity)去点亮了屏幕。                         PowerManager.ACQUIRE_CAUSES_WAKEUP |    //不依赖组件就可以点亮屏幕了,比如在通知里需要点亮屏幕,需要加入这个参数                         PowerManager.ON_AFTER_RELEASE, TAG);       wl.acquire( 5 * 1000);  //release after 5 seconds  

     break;     case 2:      break;      default:       Log.v(TAG, "can't process");     }         }                   };         mHandler.sendEmptyMessageDelayed(1, 5*1000);     }

    @Override     public boolean onCreateOptionsMenu(Menu menu) {         // Inflate the menu; this adds items to the action bar if it is present.         getMenuInflater().inflate(R.menu.main, menu);         return true;     }     }

唤醒屏幕是需要权限的,在AndroidManifest.xml请加入:

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


并且只有系统进程有加权限<uses-permission android:name="android.permission.DEVICE_POWER" />

android:sharedUserId="android.uid.system"


你可能感兴趣的:(应用层唤醒/关闭屏幕)