You need to have ACTION_MANAGE_OVERLAY_PERMISSION permission to open/display Alert onkey event in input method.
Before you set your custom Keyboard Check for Overlay Permission.
final boolean overlayEnabled = Settings.canDrawOverlays(MainActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !overlayEnabled) {
openOverlaySettings();
}
@TargetApi(Build.VERSION_CODES.M)
private void openOverlaySettings() {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
try {
startActivityForResult(intent, RC_OVERLAY);
} catch (ActivityNotFoundException e) {
Log.e("MainActivity", e.getMessage());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RC_OVERLAY:
final boolean overlayEnabled = Settings.canDrawOverlays(this);
if (overlayEnabled) {
preferenceManager.setBooleanPref(IS_CYBER_BULLING_ON, true);
Intent intent = new Intent(MainActivity.this, ImePreferences.class);
startActivity(intent);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
} else {
// switchCyberBulling.setChecked(false);
}
// Do something...
break;
}
}
Then inside your SoftKeyboard.java class, put code for alert dialog & set alert type of "TYPE_APPLICATION_OVERLAY".
AlertDialog.Builder builder = new AlertDialog.Builder(this)
//set icon
.setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Warning!")
//set message
.setMessage("This is alert dialog!")
//set positive button
.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what would happen when positive button is clicked
dialogInterface.dismiss();
}
})
//set negative button
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
}else{
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
}
alertDialog.show();
Do not forget for Draw Overlay Permission. Hope this helps you. :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…