-2

I have a alertDialog prompt during onCreate of Application Class (i added <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />)

and I have set setCancelable to false and it did succeessfully prevent user from pressing back button.

This is what I have achieved so far and this is also what I want.

However, when I press home button, the app did "disappear" but somehow the dialog still showing on home screen, and this is what I DON'T WANT.

What I expecting is that the back button should do nothing(this is what I have achieved).

and when user click home button, the whole app Including the Dialog should disappear. But somehow when I click home button the Dialog still appearing on the home screen...

mark
  • 53
  • 7

3 Answers3

1

This is because when you are creating the AlertDialog, you probably pass an ApplicationContext instead of just Context.

By following the android framework guideline, you should not make any UI changes in your Application class. Do it in your Activity of Fragment.

So do this in your Activity class:

new AlertDialog.Builder(this)

or this in your Fragment:

new AlertDialog.Builder(getContext)

Then it will disappear if your application goes into the background state.

szholdiyarov
  • 385
  • 2
  • 12
0

Try this,

        myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog1, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });
Komal12
  • 3,340
  • 4
  • 16
  • 25
  • thanks. It did disable back button but when I click home button the dialog somehow still there on home screen. – mark Mar 10 '17 at 10:18
  • You wan't to dismiss dialog on home button click? – Komal12 Mar 10 '17 at 10:21
  • I want to make dialog "Disappear" on home screen when i click home button. but when I return back to the app I want to dialog prompt again... just like the rest of the activities. – mark Mar 10 '17 at 10:34
0

This will do the trick:-

dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialogs, int keyCode,
                             KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK) {
                 return true;
            }
            if (keyCode == KeyEvent.KEYCODE_HOME) {
                 // Do your stuff here...
                 return true;
            }
            return false;
        }
    });
Paresh P.
  • 6,677
  • 1
  • 14
  • 26