摘要:Service 建立 Dialog對話框
一般在建立對話框時都會利用下面的方式建立:
public void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test!"));
builder.setIcon(R.drawable.icon);
builder.setMessage("Close!");
nid=notification_id;
builder.setPositiveButton("離開", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.setNegativeButton("關掉鈴聲", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuffdialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
不過這僅於在Activity裡面所建立,當您在使用Service如果要顯示對話框時
可能就會出現錯誤,那該如何做呢?
目前有2種方式:
1.建立一個新的Activity,並把Theme改成Theme.Dialog。
2.修改建立的Dialog屬性LayoutParams
不過第一種方式較麻煩,且還要重新做一個Layout,所以我們使用第二種來
操作增加方便性,其實加入下面的屬性設定就可以達成:
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
將Layout屬性參數改成系統的Alert視窗,所以修改上面的範例:
public void showDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test!"));
builder.setIcon(R.drawable.icon);
builder.setMessage("Close!");
nid=notification_id;
builder.setPositiveButton("離開", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
builder.setNegativeButton("關掉鈴聲", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// User clicked OK so do some stuff
clearNotification(nid);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//
alert.show();
}
並記得增加權限功能才會發揮:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />