android service Dialog 彈出框

android service Dialog 彈出框

  相信你們第一次在Service中實現 AlertDialog 彈出框時,都會遇到應用閃退而後報出這個異常:android

Caused by: android.view.WindowManager$BadTokenException:ide

  下面說下爲何出現這個異常,緣由很簡單,是因爲 AlertDialog 的顯示是依賴於一個肯定的Activity,因此要想在 Service 中實現彈出來,須要作以下配置:ui

一、安裝常規寫好 AlertDialog 功能塊後,在alertObj .show()語句前加入:this

  alertObj.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
spa

  例如:code

  private void showHostOnlineAlert(){
        final AlertDialog dialog =new AlertDialog.Builder(BackgroudService.this).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//set background was transparent
 dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//須要添加的語句
        dialog.show();
    }

 

二、在AndroidManifest.xml中加入權限:
xml

 

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission>

 

總結:以上作法就是聲明咱們要彈出的這個提示框是一個系統的提示框,即全局性質的提示框,因此只要手機處於開機狀態,不管它如今處於何種界面之下,只要調用alterObj.show(),就會彈出提示框來。blog

相關文章
相關標籤/搜索