0

I am trying to show an alert. Whose type is set to toast in the below manner

alert.getWindow().setType(Windows agar.LayoutParams.TYPE_TOAST)

But this is crashing on higher version devices

Chetan Joshi
  • 5,279
  • 4
  • 24
  • 33

2 Answers2

0

This requires the SYSTEM_ALERT_WINDOW permission:

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

As the docs say:

Very few applications should use this permission; these windows are intended for system-level interaction with the user.

Another solution is to set the window type to a system dialog:

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

Try to set dialog by passing ActivityName.this instead of getApplicationContext()

If you are using below to set dialog then try as i explained

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

try to use

AlertDialog alertDialog = new AlertDialog.Builder(FirstActivity.getInstance()).create()

For more detail Check this

Update :

Check app info in setting that SYSTEM_ALERT_WINDOW is granted or not, if not then try to get that permission at run time. For that check below question's answer.

How to get SYSTEM_ALERT_WINDOW permission at run time ?

Ninja
  • 580
  • 8
  • 23
Shailesh
  • 3,443
  • 3
  • 19
  • 42
0

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog. If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason:

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.

Update :

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

Amardeep
  • 1,246
  • 8
  • 17