Sayed Jalil Hassan
Sayed Jalil Hassan

Reputation: 2595

Android Alert dialog from inside an intent service

I want to display an alert dialog from inside an intent service.

   AlertDialog alertDialog = new AlertDialog.Builder(this).create();

This throws the following exception

   Unable to add window — token null is not for an application

I have tried IntentService.this and getApplicationContext() as well. Between i dont want to do it using an activity. I just want to show a simple alert dialog with a little text.

Upvotes: 12

Views: 26817

Answers (4)

Niranj Patel
Niranj Patel

Reputation: 33238

Need Activity for display AlertDialog, because we can't display Dialog from any Service

Solution.

Create Activity as Dialog Theme and start that Activity from Service.

Just need to register you Activity in menifest.xml like as below

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

or

android:theme="@android:style/Theme.Translucent.NoTitleBar"

MyDialog.java

public class MyDialog extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("your title");
        alertDialog.setMessage("your message");
        alertDialog.setIcon(R.drawable.icon);

        alertDialog.show();
    }
}

Upvotes: 24

Eliran Kuta
Eliran Kuta

Reputation: 4348

Only if you set your alertDialog type to TYPE_SYSTEM_ALERT it will be displayed from an intent service.

 AlertDialog alertDialog = new AlertDialog.Builder(this).create();

add these after your code:

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

But, it have a cost:

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

Upvotes: 11

Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

Please visit

https://github.com/selmantayyar/Custom-SMS-Popup

it will surly help you!!

or what you can do is register anActivity in menifest.xml as follows

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

or

android:theme="@android:style/Theme.Translucent.NoTitleBar"

and work around it

Upvotes: 1

user3458500
user3458500

Reputation:

The problem is because of Context. You can't use this as Context in Intent Service. So need to pass a Context variable of your Intent Service to your Alert Dialog. Like,

AlertDialog alertDialog = new AlertDialog.Builder(context).create();

Upvotes: -2

Related Questions