首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android BroadcastReceiver 強制下線彈窗崩潰:Manifest 註冊與 Context 使用雙重檢查

     編輯:程式設計綜合問答

崩潰典型場景

  • 在 onReceive() 中直接 new AlertDialog.Builder(context).show() 拋出 BadTokenException 或 WindowManager$BadTokenException。
  • 應用程式直接 Crash,Logcat 顯示 android.view.WindowManager$BadTokenException。

核心原因

  1. Context 不支援對話框:onReceive() 參數 context 為 ReceiverRestrictedContext,不能 用於啟動 Activity 或顯示對話框。
  2. Manifest 未註冊 Receiver:動態註冊 registerReceiver() 需在對應元件生命週期內,靜態註冊需在 <receiver> 標籤宣告並設定 android:exported。

正確實作模式

public class ForceOfflineReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 1. 必須用 Application Context 或啟動新 Task 的 Activity
        Intent dialogIntent = new Intent(context, ForceOfflineDialogActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 關鍵!
        context.startActivity(dialogIntent);
    }
}

ForceOfflineDialogActivity.java

public class ForceOfflineDialogActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 設定透明主題,僅顯示對話框
        setTheme(android.R.style.Theme_Translucent_NoTitleBar);
        
        new AlertDialog.Builder(this)
            .setTitle("強制下線")
            .setMessage("您的帳號在別處登入,請重新登入。")
            .setPositiveButton("確定", (d, w) -> {
                // 跳轉登入頁
                startActivity(new Intent(this, LoginActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
                finish();
            })
            .setCancelable(false)
            .show();
    }
}

Manifest 註冊範例

<receiver
    android:name=".ForceOfflineReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.example.FORCE_OFFLINE" />
    </intent-filter>
</receiver>

<activity
    android:name=".ForceOfflineDialogActivity"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:excludeFromRecents="true" />

除錯檢查清單

  1. adb logcat | grep -i forceoffline 確認廣播發送/接收。
  2. 檢查 AndroidManifest.xml 是否漏寫 <receiver> 或 <activity>。
  3. 確認 Intent.FLAG_ACTIVITY_NEW_TASK 已加在啟動 Activity 的 Intent 上。

遵循「BroadcastReceiver 僅負責轉發、Activity 負責 UI」原則,徹底避免 Context 權限不足導致的崩潰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved