若我們使用在Activity建立對話框的方式套用在Service裡,則會產生錯誤。
會產生錯誤的原因是,在Android系統規定,正在運作的Activity UI只能被該Activity的主thread做更改。
當Service企圖更改正在執行的Activity的UI,則會導致錯誤產生。
上網搜尋找到的解決方法:將Service所顯示的對話框設定為系統的提示框。
首先必須在Manifest增加權限
程式碼如下:
public void showDialog(int title,String message){
    Log.i("service","show dialog function");
    TextView errmsg = (TextView) layout.findViewById(R.id.errmsg);
    Log.i("service", "dialog error msg:"+message);  
    errmsg.setText(Html.fromHtml(message));
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title);
    builder.setMessage(message); 
    builder.setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//設定提示框為系統提示框
    alert.show();
}
參考網址
感謝你的分享,讓我獲益良多
回覆刪除感謝!!!
回覆刪除原來Dialog和WindowManager還可以做出這樣的搭配
有用的資料,感謝~
回覆刪除