1. 程式人生 > 其它 >android開發BadTokenException: Unable to add window -- token null is not valid; is your activity running?比較好的解決方法

android開發BadTokenException: Unable to add window -- token null is not valid; is your activity running?比較好的解決方法

BadTokenException: Unable to add window -- token null is not valid; is your activity running?比較好的解決方法

  1. 具體崩潰資訊:

    android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running? at android.view.ViewRootImpl.setView(ViewRootImpl.java:1165)

  2. 崩潰原因是:

    呼叫了popupWindow.showAtLocation,比如popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0),

    而如果這個anchorView還沒有新增到Activity,或者Activity剛好關閉了,比如剛好手機來電話了等等都會偶爾受影響,

    此時呼叫popupWindow.showAtLocation方法就會出現BadTokenException異常,因為anchorView的windowToken為空。

    說白了崩潰原因就是因為anchorView的windowToken為空。

    復現案例:在Activity的onCreate方法裡呼叫popupWindow.showAtLocation就會出現。。。

  3. 比較好的解決方法

    private fun showPopWindow(anchorView: View) {
            val popupWindow = PopupWindow(this)
            popupWindow.contentView =...
            if (anchorView.windowToken != null){//判斷一下如果windowToken不為空才顯示,不然延遲200ms再試試
                popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0)
            }else{
                Handler(Looper.getMainLooper()).postDelayed({
                    if (anchorView.windowToken != null){//延遲200ms後再判斷保證windowToken不為空才顯示
                        popupWindow.showAtLocation(anchorView,Gravity.TOP,0,0)
                    }
                },200)
            }
        }