I implemented AlertDialog
in my class which extend Application class, also added proper permission in manifest file:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
See my code:
private void showAlertDialog(Context context) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do some stuff eg: context.onCreate(super)
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCancelable(false)
.setMessage("Messag...")
.setTitle("Title")
.setPositiveButton("OK", listener);
Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
Call Method:
showAlertDialog(getApplicationContext());
I tried this answer, it was working yesterday, now is not working: How to show Dialog Box from the class which extends Application in android?
BTW, it was working yesterday, I don't know why it is not working today, what am I missing?
Did you define runtime permissions if you are checking in marshmallow or above API level devices?
Check the overlay permission
public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
public void someMethod() {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
}}
In onActivityResult,
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
if (!Settings.canDrawOverlays(this)) {
// SYSTEM_ALERT_WINDOW permission not granted...
}
}
}
Finally----
Check if the device has API 23+
if 23+ API then check if the user has permission or not
if had permit once don't drive him to Settings.ACTION_MANAGE_OVERLAY_PERMISSION
and if has not to permit yet then ask for runtime permission check
Put below the line in your onCreate()
method. Put this after setContentView()
checkPermission();
Now put below code in onActivityResult,
@TargetApi(Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
if (!Settings.canDrawOverlays(this)) {
// You don't have permission
checkPermission();
} else {
// Do as per your logic
}
}
}
Now finally the checkPermission method code,
public void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}}
And declare a variable as global
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
Happy Coding :)