安卓: 互联网连接改变监听器

我已经有这个代码,听连接变化-

public class NetworkStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Log.d("app","Network connectivity change");


if(intent.getExtras() != null)
{
NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED)
{
Log.i("app", "Network " + ni.getTypeName() + " connected");
}
}


if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE))
{
Log.d("app", "There's no network connectivity");
}
}
}

我检查互联网连接使用这个代码-网上查询

但问题是,如果网络突然失去互联网连接没有任何连接改变,这个代码是无用的。有没有办法为因特网连接更改创建 广播接收机监听器?我有一个网络应用程序和互联网连接突然变化可能会导致问题。

137025 次浏览

Try this

public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;


public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;


if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}


public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}

And for the BroadcastReceiver

public class NetworkChangeReceiver extends BroadcastReceiver {


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


int status = NetworkUtil.getConnectivityStatusString(context);
Log.e("Sulod sa network reciever", "Sulod sa network reciever");
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new ForceExitPause(context).execute();
} else {
new ResumeForceExitPause(context).execute();
}
}
}
}

Don't forget to put this into your AndroidManifest.xml

 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>

Hope this will help you Cheers!

Update:

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

You need to register the receiver via registerReceiver() method:

 IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mCtx.registerReceiver(new NetworkBroadcastReceiver(), intentFilter);

This should work:

public class ConnectivityChangeActivity extends Activity {


private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("app","Network connectivity change");
}
};


@Override
protected void onResume() {
super.onResume();


IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeReceiver, intentFilter);
}


@Override
protected void onPause() {
super.onPause();


unregisterReceiver(networkChangeReceiver);
}
}

ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback as long as you support api 24+.

In Kotlin:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
})
}
  1. first add dependency in your code as implementation 'com.treebo:internetavailabilitychecker:1.0.4'
  2. implements your class with InternetConnectivityListener.
public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


InternetAvailabilityChecker.init(this);
mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
mInternetAvailabilityChecker.addInternetConnectivityListener(this);
}


@Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" internet is connected or not");
alertDialog.setMessage("connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();


}
else {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet is connected or not");
alertDialog.setMessage("not connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();


}
}
}

Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):

ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
}


@Override
public void onLost(Network network) {
// network unavailable
}
};


ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}

implementation 'com.treebo:internetavailabilitychecker:1.0.1'

public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
InternetAvailabilityChecker.init(this);
}


@Override
public void onLowMemory() {
super.onLowMemory();
InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
}
}

I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.

You should have a Worker with network constraint AND it will fired only if network available, i.e:

val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()

And in worker you do whatever you want once connection back, you may fire the worker periodically .

i.e:

inside dowork() callback:

notifierLiveData.postValue(info)

I used this method as a connection listener. Working for Lolipop+, Android JAVA language.

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest networkRequest = new NetworkRequest.Builder().build();
connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
Log.i("Tag", "active connection");
}


@Override
public void onLost(Network network) {
super.onLost(network);
Log.i("Tag", "losing active connection");
isNetworkConnected();
}
});
}


private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())) {
//Do something
return false;
}
return true;
}

And also add this permission in your Android Manifest.xml

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

Hello from the year 2022.

In my custom view model I observe network status changes like this:

public class MyViewModel extends AndroidViewModel {
private final MutableLiveData<Boolean> mConnected = new MutableLiveData<>();


public MyViewModel(Application app) {
super(app);


ConnectivityManager manager = (ConnectivityManager)app.getSystemService(Context.CONNECTIVITY_SERVICE);


if (manager != null &&
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {


NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();


manager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
public void onAvailable(@NonNull Network network) {
mConnected.postValue(true);
}


public void onLost(@NonNull Network network) {
mConnected.postValue(false);
}


public void onUnavailable() {
mConnected.postValue(false);
}
});
} else {
mConnected.setValue(true);
}
}


@NonNull
public MutableLiveData<Boolean> getConnected() {
return mConnected;
}
}

And then in my Activity or Fragment I can change the UI by observing:

@Override
protected void onCreate(Bundle savedInstanceState) {
MyViewModel vm = new ViewModelProvider(this).get(MyViewModel.class);


vm.getConnected().observe(this, connected -> {
// TODO change GUI depending on the connected value
});
}

According to the official docs as on 12/07/22:

  1. Define network request
private val networkRequest = NetworkRequest.Builder().apply {
// To check wifi and cellular networks for internet availability
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Capabilities can be verified starting Android 6.0.
// For a network with NET_CAPABILITY_INTERNET,
// it means that Internet connectivity was successfully detected
addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Indicates that this network is available for use by apps,
// and not a network that is being kept up in the background
// to facilitate fast network switching.
addCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)
}
}.build()
  1. Configure a network callback
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
private val networks = mutableListOf<Network>()


override fun onAvailable(network: Network) {
super.onAvailable(network)


networks.add(network)
Log.d("Has network --->", networks.any().toString())
}


override fun onLost(network: Network) {
super.onLost(network)


networks.removeIf { it.toString() == network.toString() }
Log.d("Has network --->", networks.any().toString())
}
}
  1. Register for network updates
val connectivityService =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityService.registerNetworkCallback(networkRequest, networkCallback)

ref https://developer.android.com/training/monitoring-device-state/connectivity-status-type

To specify the transport type of the network, such as Wi-Fi or cellular connection, and the currently connected network's capabilities, such as internet connection, you must configure a network request.

Declare a NetworkRequest that describes your app’s network connection needs. The following code creates a request for a network that is connected to the internet and uses either a Wi-Fi or cellular connection for the transport type.

add this in onCreate

NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build();

Configure a network callback When you register the NetworkRequest with the ConnectivityManager, you must implement a NetworkCallback to receive notifications about changes in the connection status and network capabilities.

The most commonly implemented functions in the NetworkCallback include the following:

onAvailable() indicates that the device is connected to a new network that satisfies the capabilities and transport type requirements specified in the NetworkRequest. onLost() indicates that the device has lost connection to the network. onCapabilitiesChanged() indicates that the capabilities of the network have changed. The NetworkCapabilities object provides information about the current capabilities of the network.

add listener

private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
}


@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
}


@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
final boolean unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
}};

Register for network updates After you declare the NetworkRequest and NetworkCallback, use the requestNetwork() or registerNetworkCallback() functions to search for a network to connect from the device that satisfies the NetworkRequest. The status is then reported to the NetworkCallback.

Register in onCreate

ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(ConnectivityManager.class);
connectivityManager.requestNetwork(networkRequest, networkCallback);