-3

I knew this question has been asked but I couldn't solve it. I want to show simple AlertDialog on Android's Service. I can show it nicely on MainActivity but I had a problem on Service , Here is my code:

CustomMainActivity.java:

public void popupDialogMain()
{
    final Context context = getApplicationContext();
    Handler h1 = new Handler(context.getMainLooper());
    h1.post(new Runnable() {
        @Override
        public void run() {
            if (mBXmpp)
                mBXmppService.popupDialogMain2();
        }
    });
}

XmppService.java:

public static void popupDialogMain2()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(CustomMainActivity.this)
           .setMessage("Look at this dialog!")
           .setCancelable(true)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    //do things
               }
           });
     AlertDialog alert = builder.create();
     builder.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
     alert.show();
}

I get an error on this line: AlertDialog.Builder builder = new AlertDialog.Builder(CustomMainActivity.this)

Android Manifest: I added this permission:

android.permission.SYSTEM_ALERT_WINDOW

And I get this error: not an enclosing class: CustomMainActivity

Any suggestion to solve it?

Farzan Najipour
  • 2,442
  • 7
  • 42
  • 81
  • 1
    It's not a good practice to display the alert from a service.!! Try this [link](http://stackoverflow.com/a/19269931/4596556) – Madhukar Hebbar Dec 30 '15 at 10:05
  • 1
    *"I knew this question has been asked but I couldn't solve it."* Link to the previous questions/answers you read and couldn't apply to your code, and to the extent possible, say *why* you couldn't apply them. – T.J. Crowder Dec 30 '15 at 10:05
  • 2
    Possible duplicate of [Is not an enclosing class Java](http://stackoverflow.com/questions/20252727/is-not-an-enclosing-class-java) – malarres Dec 30 '15 at 10:06
  • Pass the data from service to activity thorough intent/local broadcast. In the receiving end alert the data!. – Madhukar Hebbar Dec 30 '15 at 10:35
  • @MadhukarHebbar I use a link that you sent but I get an error yet. – Farzan Najipour Dec 30 '15 at 12:54
  • @afn for alert dialog there should be an activity running. Without the activity you can't do anything. But you can start the activity looks like dialog [see this](http://stackoverflow.com/a/4135248/4596556) – Madhukar Hebbar Dec 30 '15 at 13:01

1 Answers1

2

You cannot access a this from a static method.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213