Android 用于启用移动连接的广播接收器不工作

Android 用于启用移动连接的广播接收器不工作,android,android-studio,broadcastreceiver,Android,Android Studio,Broadcastreceiver,我正在尝试编写一个广播接收器,用于检查Internet连接。但它不起作用。我的接受者是: public class MobileDataOnBroadcastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.d(MainActivity.TAG, "Broadcast received");

我正在尝试编写一个
广播接收器
,用于检查Internet连接。但它不起作用。我的接受者是:

public class MobileDataOnBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(MainActivity.TAG, "Broadcast received");
        Intent intent1 = new Intent(context, LoadPictureService.class);
        context.startService(intent1);
    }
}
当我尝试在
MainActivity
中动态注册它时,我得到“
无法解析符号conn
”:

当我试图在
清单
中注册它时,
广播接收器
根本就不会启动。我的
清单

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

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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=".MobileDataOnBroadcastReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>
    </application>
</manifest>


关于堆栈溢出这个话题有很多问题,但是没有人回答我的问题。为什么我不能动态注册
BroadcastReceiver
?为什么它在
清单
中不工作?我应该怎么做才能使它工作?

您需要使用API动态注册接收器,注意第二个参数是IntentFilter。 您可以尝试以下代码

IntentFilter filter = new IntentFilter();
filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);   
// this is the constant value android.net.conn.CONNECTIVITY_CHANGE
registerReceiver(receiver, filter);
还请注意,如果您的目标是API 24或更高版本,那么您将无法获得通过清单条目注册的此广播

参考

以Android 7.0为目标的应用程序不会收到连接性行动广播,即使它们有清单条目来请求通知这些事件。如果正在运行的应用程序请求使用BroadcastReceiver发出通知,它们仍然可以侦听其主线程上的连接更改


一般来说,动态注册接收机是这种广播的方式。只要记住,当组件生命周期状态更改或不再需要广播时,请适当地注销它们。

您需要使用API动态注册接收器,请注意第二个参数是IntentFilter。 您可以尝试以下代码

IntentFilter filter = new IntentFilter();
filter.addAction(android.net.ConnectivityManager.CONNECTIVITY_ACTION);   
// this is the constant value android.net.conn.CONNECTIVITY_CHANGE
registerReceiver(receiver, filter);
还请注意,如果您的目标是API 24或更高版本,那么您将无法获得通过清单条目注册的此广播

参考

以Android 7.0为目标的应用程序不会收到连接性行动广播,即使它们有清单条目来请求通知这些事件。如果正在运行的应用程序请求使用BroadcastReceiver发出通知,它们仍然可以侦听其主线程上的连接更改


一般来说,动态注册接收机是这种广播的方式。只要记住,当组件生命周期状态发生变化或不再需要广播时,请适当地注销它们。

有关更多信息,请查看此视频:有关更多信息,请查看此视频: