Alert Dialog from Android Service

Alert Dialog from Android Service

How do I display dialog from a service?

1

7 Answers

Another way without using an activity:

AlertDialog alertDialog = new AlertDialog.Builder(this)
                    .setTitle("Title")
                    .setMessage("Are you sure?")
                    .create();

alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();

Please note that you have to use this permission:

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

android-smspopup does exactly that.

A service receives a sms and it starts an Activity with:

android:theme="@android:style/Theme.Dialog"

EDIT: The dialog activity is started here with this code

private void notifyMessageReceived(SmsMmsMessage message) {
    (...)
    context.startActivity(message.getPopupIntent());
    (...)
}

With getPopupIntent() declared as followed (code here):

public Intent getPopupIntent() {
    Intent popup = new Intent(context, SmsPopupActivity.class);
    popup.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    popup.putExtras(toBundle());
    return popup;
    }

SmsPopupActivity class obviously defines the dialog activity. Its declared as followed in AndroidManifest.xml:

    <activity
        android:name=".ui.SmsPopupActivity"
        android:configChanges="keyboardHidden|orientation|screenSize"
        android:launchMode="singleTask"
        android:screenOrientation="user"
        android:taskAffinity="net.everythingandroid.smspopup.popup"
        android:theme="@style/DialogTheme" >
    </activity>
1

Material styled Dialog from a Service

From a Service, you can easily show a Material Design styled Dialog manipulating its Window type, attributes and LayoutParams.

Before we begin: AppCompat Library

This guide presumes you are using Android AppCompat libray.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.