我在我的类中实现了AlertDialog
,该类扩展了Application类,并且还在清单文件中添加了适当的权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
查看我的代码:
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();
}
调用方法:
showAlertDialog(getApplicationContext());
我尝试了这个答案,它昨天工作了,现在不工作:How to show Dialog Box from the class which extends Application in android?
顺便说一句,它昨天工作了,我不知道为什么今天不工作,我想念什么?
答案 0 :(得分:-1)
如果要签入棉花糖或API级别以上的设备,是否定义了运行时权限?
检查覆盖权限
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);
}}
在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...
}
}
}
最后----
检查设备是否具有API 23 +
如果使用23+ API,则检查用户是否具有权限
如果曾经获得许可,请勿将他驱逐到Settings.ACTION_MANAGE_OVERLAY_PERMISSION
,如果还没有许可,则要求进行运行时许可检查
将onCreate()
方法中的行置于下方。将此放在setContentView()
checkPermission();
现在将下面的代码放在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
}
}
}
现在终于有了checkPermission方法代码,
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);
}
}}
并声明一个全局变量
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
快乐编码:)