在 android Studio 项目的清单文件中声明接收器

Declaring a receiver in the manifest file of an android Studio project

在我的清单文件中,我为我的 Activity 声明了两个 BroadcastReceiver。到目前为止,当我在调试模式下工作时,接收器是在 activity 块中声明的,一切都很好。由于我的项目接近尾声,我决定构建一个签名的 APK。我面临的问题是 android studio returns 我出现以下错误:

Error:(20) Error: The <receiver> element must be a direct child of the <application> element [WrongManifestParent]

如果我将接收方块移出 activity 块,则会生成签名的 APK。结果是在调用接收器时出现 运行 时间错误(java.lang.RuntimeException:无法实例化接收器...)。

我怎样才能让我的应用 运行 在调试和发布模式下都正确?

您的清单文件的结构应该类似于下面的代码。您不应在其他任何地方声明 receivers

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- -- First Activity -- -->

    <activity
        ...
        ... >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- -- Second Activity -- -->

    <activity
        ...
        ... >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="..." />
    </activity>

    <!-- -- First Receiver -- -->

    <receiver android:name="..."/>

    <!-- -- Second Receiver -- -->

    <receiver android:name="..." android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

</application>

好吧,因为我的接收器 class 是一个内部 class,显然没有必要在清单文件中声明它(因为它是一个内部 -class ,当我在 activity 块之外声明它时会产生错误)。现在我已经删除了它的声明,签名的 APK 已正确生成,我不再收到运行时错误。