想在系統(tǒng)鎖屏界面彈出Toast給用戶提示砸捏,結(jié)果死活彈不出來(lái),后來(lái)發(fā)現(xiàn)Toast其實(shí)已經(jīng)彈出來(lái)了,只是被鎖屏給擋住了拭卿。
原因:
Android的窗口的分層管理,即我們看到的屏幕顯示只是z軸(z-ordered)最外面的贱纠,后面的其實(shí)是被擋住了(雖然看不見但它依然存在)峻厚,故要想讓Toast顯示出來(lái),其層級(jí)一定要在鎖屏之上才行谆焊。
應(yīng)用Window層級(jí)范圍[1-99], 子Window的層級(jí)范圍[1000-1999], 系統(tǒng)Window的層級(jí)范圍[2000-2999]
實(shí)現(xiàn)代碼:
Toast mToast = Toast.makeText(mContext, mContext.getString(com.android.internal.R.string.keyguardon_not_switch), Toast.LENGTH_SHORT);
mToast.getWindowParams().type = WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL;
mToast.getWindowParams().privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
mToast.getWindowParams().flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
mToast.show();
主要參數(shù):
/frameworks/base/core/java/android/view/WindowManager.java
/** 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
* {@link #FLAG_KEEP_SCREEN_ON} to turn screen on and display windows
* directly before showing the key guard window. Can be used with
* {@link #FLAG_DISMISS_KEYGUARD} to automatically fully dismisss
* non-secure keyguards. This flag only applies to the top-most
* full-screen window.
*/
public static final int FLAG_SHOW_WHEN_LOCKED = 0x00080000;
/** In a multiuser system if this flag is set and the owner is a system process then this
* window will appear on all user screens. This overrides the default behavior of window
* types that normally only appear on the owning user's screen. Refer to each window type
* to determine its default behavior.
* * {@hide} */
public static final int PRIVATE_FLAG_SHOW_FOR_ALL_USERS = 0x00000010;
參考資料
1.鎖屏界面無(wú)法無(wú)法顯示Toast(介紹了非系統(tǒng)應(yīng)用的實(shí)現(xiàn))
https://blog.csdn.net/u013398960/article/details/73194812
2.延伸閱讀
2.1 Android窗口管理分析(3):窗口分組及Z-order的確定
https://blog.csdn.net/happylishang/article/details/77893723
2.2 源碼
frameworks/base/core/java/android/view/WindowManager.java
3.疑問
3.1 https://github.com/weidongshan/APP_0010_SurfaceTest/blob/master/SurfaceTest.cpp#L46
window的z-ordered顯然要和surface的layer對(duì)應(yīng)惠桃,這中間怎么處理的?
surfaceControl->setLayer(100000);