鎖屏上顯示Activity


在Android中,有些比較強的提醒,需要用戶緊急處理的內容。需要喚醒屏幕,甚至在鎖定屏幕的情況下,也要顯示出來。例如,來電界面和鬧鍾提醒界面。這是怎樣實現的呢?

其實,實現起來非常簡單。只要給Activity的Window添加如下屬性即可:

@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); ... } 

注意這里的FLAG_SHOW_WHEN_LOCKEDFLAG_TURN_SCREEN_ON,從名字上就能看出其作用。FLAG_TURN_SCREEN_ON使Activity啟動的時候能夠點亮屏幕。FLAG_SHOW_WHEN_LOCKED能夠在屏幕鎖定的時候,也能顯示。

關於FLAG_SHOW_WHEN_LOCKED這個flag,官方文檔說明如下:

Window flag: special flag to let windows be shown when the screen is locked. This will let application windows take precedence over key guard or any other lock screens. Can be used with FLAG_KEEP_SCREEN_ON to turn screen on and display windows directly before showing the key guard window. Can be used with FLAG_DISMISS_KEYGUARD to automatically fully dismisss non-secure keyguards. This flag only applies to the top-most full-screen window.

這段話的大概意思是,這個Flag能夠讓windown在鎖屏的時候,在鎖屏之上顯示。可以配合FLAG_KEEP_SCREEN_ON(保持屏幕常亮)和FLAG_DISMISS_KEYGUARD(解鎖屏幕)等Flag使用。需要特別注意的是最后一句話,意思就是這個flag只有是全屏幕的window才起作用。例如,對你的Activity使用了Dialog的Theme,如下:

<activity android:theme="@android:style/Theme.Dialog" /> 

這時,你的Activity將不能顯示在鎖屏之上。

另外,在鎖屏上顯示Activity,為了不讓界面顯得太突兀,你可能還想能夠使用系統的屏保作為你的Activity背景,系統鬧鍾就是這么做的。要實現這樣的功能也特別容易,只要把Activity的背景設為透明即可,例如你可以為你的Activity定義如下Theme:

<style name="FullScreenTheme" parent="@android:style/Theme.Light.NoTitle"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:colorBackgroundCacheHint">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsTranslucent">true</item> <item name="miui:windowTranslucentStatus">transparentDark</item> </style> <activity android:theme="@style/FullScreenTheme" /> 

題外話,我們可以通過如下方法判斷,系統是否處在鎖屏狀態:

KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); boolean showingLocked = km.inKeyguardRestrictedInputMode(); 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM