1. 程式人生 > >android喚醒螢幕並解鎖

android喚醒螢幕並解鎖

在開發程式的時候,有時會有喚醒螢幕並解鎖螢幕的需求。

這個demo的作用是在進入主介面後30秒喚醒螢幕並解鎖,僅供演示喚醒螢幕功能。

首先加入以下兩個許可權:

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

然後是activity中的程式碼,喚醒並解鎖螢幕

/*
 * 程式碼喚醒螢幕demo
 * 程式執行後一段時間喚醒螢幕
 */

import
android.app.Activity; import android.app.KeyguardManager; import android.app.KeyguardManager.KeyguardLock; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { Context context = MainActivity.this
; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Thread wakeUpThread = new Thread(new WakeUpThread()); wakeUpThread.start(); } @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; } class WakeUpThread implements Runnable{ @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(30*1000);//休眠一分鐘 //獲取電源管理器物件 Log.e("zhiyinqing","該開啟螢幕了"); PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK,"bright"); wl.acquire(); //點亮螢幕 //wl.release();//釋放 //螢幕解鎖 KeyguardManager km= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); //得到鍵盤鎖管理器物件 KeyguardLock kl = km.newKeyguardLock("unLock"); //引數是LogCat裡用的Tag kl.disableKeyguard(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }