Android WindowManager無法創(chuàng)建窗口可能有以下原因:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
對于Android 6.0(API級別23)及更高版本,您還需要在運行時請求此權(quán)限??梢允褂靡韵麓a片段:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(SYSTEM_ALERT_WINDOW) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{SYSTEM_ALERT_WINDOW}, PERMISSION_REQUEST_CODE);
}
}
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
或者
WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
layoutParams.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE; // 或者使用 TYPE_SYSTEM_ALERT, TYPE_SYSTEM_OVERLAY 等
onCreate()
方法中創(chuàng)建窗口。如果您仍然遇到問題,請檢查系統(tǒng)日志(Logcat),以獲取有關(guān)錯誤或異常的詳細信息。這將幫助您更好地診斷問題并找到解決方案。