解決在BroadcastReceiver(廣播接受者)中不能添加AlertDialog(對話方塊)的問題(android.view.WindowManager$BadTokenException)

來源:互聯網
上載者:User

標籤:廣播接收者裡面添加對話方塊   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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.