WindowManager$InvalidDisplayException - 指定的 window 类型 -1 无效

WindowManager$InvalidDisplayException - the specified window type -1 is not valid

我正在尝试从服务中膨胀 UI 元素。但是出现 WindowManager$InvalidDisplayException - the specified window type -1 is not valid 错误。 我的代码如下,

WindowManager windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.box, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
       WindowManager.LayoutParams.MATCH_PARENT,
       WindowManager.LayoutParams.MATCH_PARENT,
       PixelFormat.TRANSLUCENT));

windowManager.addView(layout, params);

我收到这个错误,

android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W@8b06417 -- the specified window type -1 is not valid
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:725)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
    at com.firebaseapp.privacy.MyIntentService.handleAction(MyIntentService.java:33)
    at com.firebaseapp.privacy.MyIntentService.onHandleIntent(MyIntentService.java:20)
    at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:68)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.os.HandlerThread.run(HandlerThread.java:61)

您需要在清单中添加权限

android.permission.SYSTEM_ALERT_WINDOW

也尝试添加参数类型

params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;

希望这能解决您的问题