在BroadcastReceiver,当我们创建一个AlertDialog并show出来的时候,出现了下面的错误:
12-24 14:10:57.025: E/AndroidRuntime(17600): java.lang.RuntimeException: Unable to start receiver com.ustc.broadcastreceiver.ForceOfflineReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
下面的方法可以解决:
第一步:
在调用show方法之前,设置下面的属性:
dialog.getWindow() .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
再次运行,发现程序又挂了:
12-24 14:15:22.793: E/AndroidRuntime(17979): java.lang.RuntimeException: Unable to start receiver com.ustc.broadcastreceiver.ForceOfflineReceiver: android.view.WindowManager$BadTokenException: Unable to add window [email protected] --
permission denied for this window type
这个一看就知道了,权限拒绝,需要添加权限:
第二步:
在清单文件中添加权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
这样运行就OK了,我的代码如下:
package com.ustc.broadcastreceiver; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.view.WindowManager; public class ForceOfflineReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { AlertDialog.Builder builder = new Builder(context); builder.setTitle("提示"); builder.setMessage("强制下线"); builder.setCancelable(false); builder.setPositiveButton("ok", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCollector.finishAll(); Intent intent = new Intent(context, LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); AlertDialog dialog = builder.create(); dialog.getWindow() .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } }
时间: 2024-11-14 18:32:59