編輯:關於 Android 開發
想讓 App 知道使用者此刻是否正處於鎖屏畫面,最直接的途徑就是系統服務 KeyguardManager。它不只提供查詢鎖屏狀態的能力,也能用來控制鎖屏介面的顯示與隱藏,是許多需要「在背景執行前先確認螢幕狀態」的應用會用到的 API。
以下用一個最小範例說明:畫面上擺一顆按鈕,點下去就透過 Toast 告訴你現在是鎖屏還是解鎖。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- 定義獲得屏幕狀態的按鈕 --> <Button android:id="@+id/reenableKeyguard" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="屏幕的狀態" /> </RelativeLayout>
package com.example.yanlei.yl; import android.app.KeyguardManager; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends AppCompatActivity { // 定義鎖屏的按鈕 private Button btnKeyguard; //聲明KeyguardManager對象 private KeyguardManager keyguardManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 獲得KeyguardManager服務 keyguardManager=(KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); //得到布局中的所有對象 findView(); //設置對象的監聽器 setListener(); } private void findView() { // 得到布局中的所有對象 btnKeyguard = (Button) findViewById(R.id.reenableKeyguard); } private void setListener() { // 設置對象的監聽器 btnKeyguard.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub //判斷當前屏幕的狀態 if(keyguardManager.isKeyguardLocked()) { Toast.makeText(MainActivity.this, "鎖屏", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "沒有鎖屏", Toast.LENGTH_SHORT).show(); } } }); } }
整個實作可以拆成四個動作:
1. 透過 getSystemService(Context.KEYGUARD_SERVICE) 取得 KeyguardManager 物件。
2. 在 findView() 中把版面配置裡的按鈕抓出來。
3. 在 setListener() 註冊點擊事件。
4. 點擊時呼叫 isKeyguardLocked(),回傳 true 代表目前處於鎖屏,false 代表已解鎖。
值得注意的是,isKeyguardLocked() 判斷的是「裝置是否處於安全鎖定狀態」,若裝置本身未設定任何鎖屏密碼,結果可能與預期不同;若需要更精確地區分「有沒有設定鎖屏」與「目前是否鎖定」,可以搭配 isKeyguardSecure() 一起使用。
另外,若想主動解除鎖屏,需要 WAKE_LOCK 與 DISABLE_KEYGUARD 權限,並在較新的 Android 版本中改用 setShowWhenLocked()、setTurnScreenOn() 等 API,這是舊範例容易忽略的地方。
Android 讀取系統聯絡人:raw_contacts、data 與 mimetypes 三表解析
Android 讀取系統聯絡人:raw_contacts、data 與 mimetypes 三表解析 Android 的聯絡人資料庫(contacts2.db)結構以「表
Android Studio 快速上手:下載、安裝、建立專案與新增 module
Android Studio 是什麼 Google 在 I/O 大會上推出了 Android Studio,這是一款以 IntelliJ IDEA 為基礎的開發工具,並以
GitHub 好料分享:功能豐富的通知工具庫 NotifyUtil
GitHub 好料分享:功能豐富的通知工具庫 NotifyUtil 今天要介紹的是一個相當實用的通知工具庫 NotifyUtil。作者把常用的通知樣式都封裝得相當完整,使
PullToZoomScrollViewEx 實作下拉縮放:還原新浪微博登入頁動效(二)
PullToZoomScrollViewEx 實作下拉縮放:還原新浪微博登入頁動效(二) 上一篇我們談完了 ListView 版本的 PullToZoomListVie