Android 在服務Service中建立Dialog對話方塊
一般我們都是在Activity中建立dialog的,無論是系統的AlertDialog還是我們自定義的Dialog。
我們只需設定title,message等資訊,然後show出來即可。
可是在服務中呢,沒有activity,dialog沒有了依賴,那麼怎麼辦呢? 這時,dialog就要以系統對話方塊的形式彈出了。在我們取得Dialog物件後,需給它設定型別,即:
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
1
看看這個TYPE的解釋
/**
* Window type: system window, such as low power alert. These windows
* are always on top of application windows.
* In multiuser systems shows only on the owning user's window.
*/
public static final int TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3;
在這裡別忘了在Manifest中加上許可權
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
1
最後來段示例程式碼
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage("Hello,My name is Message.");
builder.setNegativeButton("CANCEL", null);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 具體操作
}
});
final Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dial