For example, they turned on the Internet, displayed a corresponding message, then disconnected it and again received a corresponding message.
Those monitor the status of the Internet at any time, and not a one-time
For example, they turned on the Internet, displayed a corresponding message, then disconnected it and again received a corresponding message.
Those monitor the status of the Internet at any time, and not a one-time
You do not need to monitor the state of the Internet , but receive notifications about its change
Determining the connection status at time:
boolean checkInternet(Context context) { ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork.isConnectedOrConnecting(); } BroadcastReceiver on network status change:
public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { if(checkInternet(context)){ Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); } } And in the manifest to determine the receiver itself:
<receiver android:name="<ваш.пакет.сюда>.NetworkChangeReceiver "> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> And be sure to get the status of the network:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Get the ConnectivityManager and select which broadcasts we’ll listen to:
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); BroadcastReceiver connectivityStatusReceiver = new NetworkConnectionStatusReceiver(); When you need to start monitoring the state of the Internet, we launch a wiretap of the corresponding intents:
context.registerReceiver(connectivityStatusReceiver, NETWORK_INTENT_FILTER)) Well sobsno check the availability of the Internet:
protected boolean hasConnection() { NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { switch (netInfo.getType()) { case ConnectivityManager.TYPE_MOBILE: case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: return true; default: return false; } } return false; } private class NetworkConnectionStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (hasConnection()) { // network available } else { // no network }; } } Source: https://ru.stackoverflow.com/questions/523668/
All Articles