从清单注册时未调用 BroadcastReceiver

BroadcastReceiver not called when registering from manifest

这是我的清单的样子:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.lcukerd.earphonereminder">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <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/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name="ConnectivityActionReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGE" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

我的 Receiver 在从 activity 注册时工作正常,但我想从清单注册,这样即使应用程序关闭它也可以 运行。问题是什么?为什么它不起作用?

尝试使用 .ConnectivityActionReceiver 而不是 ConnectivityActionReceiver。当你调用 ConnectivityActionReceiver 时,Receiver 将不会被注册,因为没有找到 Class

    <receiver
        android:name=".ConnectivityActionReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter android:priority="100">
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGE" />
        </intent-filter>
    </receiver>

参考这个Question了解更多

自 Android Oreo 起,接收器必须在运行时使用

注册

context.registerReceiver(receiver, intentFilter);

接收隐式意图

您仍然可以接收显式意图和一些特殊的隐式操作,例如 boot_completed 或 locale_changed

更多信息请看下面link

https://developer.android.com/about/versions/oreo/background.html#broadcasts