2013-07-15

Popup a AlertDialog in Android Service

If you want to popup a dialog in Android Service, you have two ways:
1. Use an Activity as Dialog
a. Create an Activity
b. Config theme as Theme.Dialog in manifest
c. Define your layout in res
2. Use AlertDialog.Builder, but you'll need to config dialog as System Alert
Here is the sample code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test dialog"));
builder.setIcon(R.drawable.icon);
builder.setMessage("Content");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //Do something
        dialog.dismiss();
});
builder.setNegativeButton("Close", 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();
Also, remember to add permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

No comments: