解决在BroadcastReceiver(广播接受者)中不能添加AlertDialog(对话框)的问题(android.view.WindowManager$BadTokenException)

在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 android.view.ViewRootImpl$W@535ab190 -- 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();
	}

}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。