我已经在Asynctask的onProgressUpdate方法中创建了警告对话框,我已将权限放入清单:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
当app显示警告对话框时,我收到此异常:
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@e9ea0e -- permission denied for this window type
代码是:
@Override
protected void onProgressUpdate(Object[] values) {
this.holder.itemView.setBackgroundColor(Color.WHITE);
if(messaggio){
// Toast.makeText(context, testoMessaggio, Toast.LENGTH_SHORT).show();
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(nameFile);
alertDialog.setMessage(testoMessaggio);
alertDialog.setCancelable(true);
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//alertDialog.cancel();
}
});
alertDialog.show();
}
super.onProgressUpdate(values);
}
为什么我有这个例外?
如果我删除它:
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//alertDialog.cancel();
}
});
它起作用的原因是什么?
onProgressUpdate我已尝试创建通知,但它不起作用:
@Override
protected void onProgressUpdate(Object[] values) {
this.holder.itemView.setBackgroundColor(Color.WHITE);
if(messaggio){
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, EUDroid_Main_Activity.class), 0);
Notification notification = new NotificationCompat.Builder(context)
.setTicker("Ticker")
.setContentTitle("Title")
.setContentText("Hello")
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
super.onProgressUpdate(values);
}
为什么?
答案 0 :(得分:0)
试试这个,这可能对你有所帮助。我不知道它有多可靠但我的应用程序现在没有崩溃。
windowManager = (WindowManager)getSystemService(WINDOW_SERVICE);
//here is all the science of params
final LayoutParams myParams = new LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
PixelFormat.TRANSLUCENT
);
在您的清单文件中,只需提供权限
即可 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
除此之外,您还可以检查API级别,如果它的&gt; = 23然后
if(Build.VERSION.SDK_INT >= 23) {
if (!Settings.canDrawOverlays(Activity.this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1234);
}
}
else
{
Intent intent = new Intent(Activity.this, Service.class);
startService(intent);
}
我希望它可以帮助某个人。