如何解决:java.lang.IllegalStateException:您需要将 Theme.AppCompat 主题(或后代)与此 activity 一起使用?

How to resolve: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity?

还有其他一些相同主题的文章,但我的情况不同。

我在 AlarmManager 应用程序中使用 BroadcastReciever。在警报触发时,我正在尝试显示具有自定义布局的 AlertDialog。当警报被触发时,我得到以下异常:

 java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

尽管我在整个应用程序中使用 Theme.AppCompat.Light.NoActionBar。 这是 Manifest:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"
    >

我也在对话框的布局文件中指定了这种样式:

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#10000000"
        android:orientation="vertical"
        style="@style/Theme.AppCompat.Light.NoActionBar"
        android:padding="10dip" >
<TextView/>...
<Button/>...
</LinearLayout>

此外我正在打开 dialog 形成我的 BroadcastReciver onRecive() 方法 class:

 @Override
    public void onReceive(Context context, Intent intent) {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View v = inflater.inflate(R.layout.fragment_alarm_running, null);
        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setView(v)
                .setCancelable(false)
                .create();

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(final DialogInterface dialog) {  ...   }
        });
        dialog.show();
} 

注意: onRecieve() 已成功调用,但问题在于显示 对话框 。之前我还尝试了一个单独的 activity 来显示对话框,但是当应用程序关闭时 activity 不会从后台启动。

我该如何解决这个问题?提前致谢!

广播接收器就像您的 Activity 一样是您应用程序的组件。 您正在尝试在需要 Theme.AppCompat 的接收器中显示警报对话框,但您的广播接收器没有该主题。 您需要做的是在接收广播时打开一个 activity 并在其中显示对话框,就像呼叫功能一样。或者使用通知管理器通过操作按钮显示通知。