Android 互联网连接的 BroadcastReceiver 调用了两次

Android BroadcastReceiver for internet connection called twice

我遇到这个问题有一段时间了,注意到其他一些人也遇到了这个问题,但我无法解决它。

问题

我有一个 BroadcastReceiver,它一直在监听互联网变化。因此,每当互联网连接或断开连接时,我都会在接收器的 onReceive 中获得状态。

问题是它总是被调用两次。当我连接调试器并在代码中设置断点时,我可以看到它被调用了两次,但我的状态更改代码会执行。当调试器未连接时,在这种情况下,我的状态更改代码根本不会执行。

我的代码

BroadcastReceiver 文件

public class ConnectivityReceiver
    extends BroadcastReceiver {

public static ConnectivityReceiverListener connectivityReceiverListener;

public ConnectivityReceiver() {
    super();
}

@Override
public void onReceive(Context context, Intent arg1) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }
}

public static boolean isConnected() {
    ConnectivityManager
            cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null
            && activeNetwork.isConnectedOrConnecting();
}


public interface ConnectivityReceiverListener {
    void onNetworkConnectionChanged(boolean isConnected);
}

}

明确意图行动

<receiver
        android:name=".utils.ConnectivityReceiver"
        android:enabled="true">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
        </intent-filter>
    </receiver>

这里当我尝试在过滤器中只使用 <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> 时,它也出现了两次 onRecieve。当我尝试使用 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 时,我根本没有达到 onReceive

BaseActivity

 @Override
public void onNetworkConnectionChanged(boolean isConnected) {
    setNetworkIndicator(isConnected); //THE CODE TO EXECUTE ON STATUS CHANGE
}

我尝试了现有的答案,但它对我不起作用。

通常,当 on Receive 被调用两次时,广播接收器被调用 twice.So 请检查您是否在 2 个位置注册了广播?如果是,那么请 仅在简历或创建中注册您的广播,并在 activity.[=12 的 onPause() 方法中注销它=]

例如注册广播接收器,

LocalBroadcastManager.getInstance(this).registerReceiver(myLocalBroadcastManager, new IntentFilter(Constant.CONNECTIVITY_CHANGE));

未注册的广播接收器如:-

LocalBroadcastManager.getInstance(this).unregisterReceiver(myLocalBroadcastManager);

希望对你有所帮助

我的猜测是 wifi 接收器被调用了两次,因为它被调用一次用于 enabling 状态,一次用于后续 enabled状态。

Documentation中指出:

Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown. One extra provides this state as an int. Another extra provides the previous state, if available.

您可以检查 EXTRA_WIFI_STATE and EXTRA_PREVIOUS_WIFI_STATE 的值以验证是否属于这种情况。

因此,为了忽略不需要的 connecting/disconnecting 状态,您可以将 onReceive() 更新为以下内容:

@Override
public void onReceive(Context context, Intent arg1) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

    boolean isConnected = false;
    if (activeNetwork != null){

        if (activeNetwork.getState() == NetworkInfo.State.CONNECTING || activeNetwork.getState() == NetworkInfo.State.DISCONNECTING){
            return;
        }
        isConnected = activeNetwork.isConnected();
    }

    if (connectivityReceiverListener != null) {
        connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
    }

}

您应该检查 onReceive 回调中的意图操作:

String action = arg1.getAction();
if (action != null && action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
    // do your task here.
}

Check this link

对于 Android 7 及更高版本,您需要在 activity 文件而不是清单文件中注册接收器。

因此在您的 activity 的 onCreate() 中添加以下行:

    myConnectivityReceiver = new ConnectivityReceiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(getResources().getString(R.string.action_connectivity_change));
    registerReceiver(myConnectivityReceiver,filter);

并在 onDestroy()

  @Override
  protected void onDestroy() {
      unregisterReceiver(myConnectivityReceiver);
      super.onDestroy();
  }

在 strings.xml

中定义意图操作
<string name="action_connectivity_change">android.net.conn.CONNECTIVITY_CHANGE</string>