Question:
For example, they turned on the Internet, a corresponding message was displayed, then they turned it off and again received the corresponding message.
Those monitor the state of the Internet at any time, and not one-time
Answer:
You do not need to monitor the state of the Internet , but receive notifications about its change
Determining the connection state at a point in time:
boolean checkInternet(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork.isConnectedOrConnecting();
}
BroadcastReceiver on network state 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, define 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 have permission to get the state of the network:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />