视图已添加到窗口管理器

时间:2019-02-06 14:32:27

标签: android android-view android-windowmanager

我在服务中有2个视图,我想根据某些情况进行切换。我正在做的切换,删除第一个视图,然后添加第二个视图。这是我的代码:

public void switchView(boolean toCallView) {
        if (toCallView) {
            if (lockScreenLayout != null && lockScreenLayout.getParent() != null && lockScreenLayout.getWindowToken() != null)
                windowManager.removeView(lockScreenLayout);
            if (callScreenLayout != null && callScreenLayout.getWindowToken() == null)
                windowManager.addView(callScreenLayout, layoutParams);
        } else {
            if (callScreenLayout != null && callScreenLayout.getParent() != null && callScreenLayout.getWindowToken() != null)
                windowManager.removeViewImmediate(callScreenLayout);
            if (lockScreenLayout != null && lockScreenLayout.getParent() != null && lockScreenLayout.getWindowToken() == null)
                windowManager.addView(lockScreenLayout, layoutParams); // exception raise here
        }
    }

但是在某些情况下,我仍然会因以下异常而导致应用程序崩溃:

ACRA caught a RuntimeException for com.myapp
java.lang.RuntimeException: Error receiving broadcast Intent { act=intent.activate.incoming.call.screen flg=0x10 (has extras) } in com.myapp.activity.LockScreenService$9@e94ff0a
    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:895)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:234)
    at android.app.ActivityThread.main(ActivityThread.java:5524)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: View android.widget.RelativeLayout{d4d82ee V.E...... ......ID 0,0-720,1184} has already been added to the window manager.
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:281)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:86)
    at com.myapp.util.IncomingCallHandler.switchView(IncomingCallHandler.java:73)
    at com.myapp.activity.LockScreenService$9.onReceive(LockScreenService.java:270)
    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:885)
    ... 7 more

有人可以给我提示如何避免这种情况。

1 个答案:

答案 0 :(得分:0)

作为例外状态,lockScreenLayout已被添加到WindowManager中,并且无法再次添加。因此,您有两种选择可以防止这种情况发生:

第一

编辑您的逻辑。您的某些情况达到两次的情况应该不会发生

第二

检查视图是否已添加。像这样:

if (!lockScreenLayout.isShown()) 
{
    // Add child to window
}