《第一行代码》BroadcastBestPractice中出现的问题及解决方案(关于AlertDialog系统对话框的使用)...

该程序为《第一行代码》中的一个小demo,意在学习使用广播实现强制下线功能。

按《第一行代码》中的源码编写ForceOfflineReceiver类,用于接收广播并处理,代码如下:

public class ForceOfflineReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        dialogBuilder.setTitle("warning");
        dialogBuilder.setMessage("You are forced to be offline. Please try to login again.");
        dialogBuilder.setCancelable(false);
        dialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ActivityCollector.finishAll();
                Intent startLoginIntent = new Intent(context, LoginActivity.class);
                startLoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(startLoginIntent);
            }
        });

        AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT );
        alertDialog.show();

    }
}

由于在ForceOfflineReceiver中弹出了一个系统级别的对话框,所以必须在AndroidManifest中声明如下权限:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

但编写完成后运行程序点击发送广播后,在接收到广播并处理时,执行alertDialog.show()出错,无法弹出系统对话框且程序直接崩溃。

出错信息为:Unable to add window android.view.ViewRootImpl$W@f2a441d -- permission denied for this window type

解决办法如下:

  若API>=19,不要使用WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,可使用WindowManager.LayoutParams.TYPE_TOAST

  即修改倒数第二行代码为:

alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);

之后再运行程序即可正常弹出系统对话框

转载于:https://www.cnblogs.com/Johnny-ZhangRQ/p/5770719.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值