標籤:廣播接收者裡面添加對話方塊 android.view.windowm
在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了,My Code如下:
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 {@Overridepublic 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() {@Overridepublic 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();}}
解決在BroadcastReceiver(廣播接受者)中不能添加AlertDialog(對話方塊)的問題(android.view.WindowManager$BadTokenException)