I need to prompt a alertDialog in a background service, but it crashed by the bad context, how can I handle it, where I can get the right Context?
How to use alertDialog in background service
4.7k views Asked by Leon Leung At
3
There are 3 answers
0
On
The accepted answer would not work in Oreo+ Please use the flag TYPE_APPLICATION_OVERLAY instead of TYPE_PHONE or SYSTEM_ALERT in WindowManager.LayoutParams: use
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
instead
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
still the overlay dont show? then check if your app has the permission
Settings.canDrawOverlays() if this is false then.
User should have this permission too! This was introduced in Marshmallow
// Check if Android M or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Show alert dialog to the user saying a separate permission is
needed
// Launch the settings activity if the user prefers
Intent myIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(myIntent);
}
Code inside Service class to open AlertDialog
You have to add permissions in Manifest file
You can do customize on alert dialog as your requirements.
Done