android面试题-Service中弹出Dialog

时间:2022-11-01 15:32:48
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("有新消息,是否查看?");
alertDialog.setPositiveButton("否",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});

alertDialog.setNegativeButton("是",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});

ad = alertDialog.create();

ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
ad.setCanceledOnTouchOutside(false);//点击外面区域不会让dialog消失
ad.show();

添加权限

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
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, 1);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
// SYSTEM_ALERT_WINDOW permission not granted...
}
}
}
}