需求

android 需要监听网线插拔广播

解决

NetworkStateBroadcastReceiver.java

package com.tianze.platform.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.tianze.coagulationanalyzer.MainActivity;
import com.tianze.platform.log.DLog;

public class NetworkStateBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "NetworkStateBroadcastReceiver";

    public static final String ACTION_NETWORK_PLUG_STATE = "com.android.example.NETWORK_PLUG_STATE";
    private boolean plugIn = false;
    private NetworkHelper helper;
    private boolean exceptionUnplugged = false;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onReceive(Context context, Intent intent) {
      String action =intent.getAction();
      switch (action) {
	  //接受到自定义广播
	  case "android.net.conn.CONNECTIVITY_CHANGE":
	      if (helper.getLocalIpAddress().equals("0.0.0.0")) {
		  if (plugIn) {
		      exceptionUnplugged = true;
		  }
		  plugIn = false;
		  DLog.d(TAG, "ACTION_NETWORK_PLUG_STATE: plug off");
		  Toast.makeText(context, "network plug off", Toast.LENGTH_SHORT).show();
	      } else {
		  plugIn = true;
		  DLog.d(TAG, "ACTION_NETWORK_PLUG_STATE: plug in");
		  Toast.makeText(context, "network plug in", Toast.LENGTH_SHORT).show();
	      }
	      ((MainActivity)context).NewNetworkLocalAddress(helper.getLocalIpAddress());
	      break;

	  default:
	      break;
      }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void NetworkInit(Context context) {
      helper = new NetworkHelper(context);
      if (helper.getLocalIpAddress().equals("0.0.0.0")) {
	  if (plugIn) {
	      exceptionUnplugged = true;
	  }
	  plugIn = false;
	  DLog.d(TAG, "ACTION_NETWORK_PLUG_STATE: plug off");
	  Toast.makeText(context, "network plug off", Toast.LENGTH_SHORT).show();
      } else {
	  plugIn = true;
	  DLog.d(TAG, "ACTION_NETWORK_PLUG_STATE: plug in");
	  Toast.makeText(context, "network plug in", Toast.LENGTH_SHORT).show();
      }
      ((MainActivity)context).NewNetworkLocalAddress(helper.getLocalIpAddress());
    }

    public boolean isPlugIn() {
      return plugIn;
    }

    public boolean isExceptionUnplugged() {
      return exceptionUnplugged;
    }

    public void clearExceptionUnplugged() {
      exceptionUnplugged = false;
    }
}
private NetworkStateBroadcastReceiver networkStateBroadcastReceiver = new NetworkStateBroadcastReceiver();

    IntentFilter networkFilter = new IntentFilter();
    networkFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(networkStateBroadcastReceiver, networkFilter);

参考