Good day. It is necessary to activate the message when the Internet is disconnected. Trying to understand this topic, I am even more confused. As I understand it, you need to create a receiver of broadcast messages (create a class that inherits BroadcastReceiver ), then in activit register this receiver of broadcast messages. But then there are two questions:

  1. Suppose a message is sent that the Internet is gone, respectively, the onReceive method onReceive , but doesn’t the activation know something about it? How to transfer this information accordingly?
  2. How to implement the sending of messages for the receiver about changing the status of the Internet (found on the Internet that you need to use the ConnectivityManager )?
  • On 1 point itself understood, there is a second point. - Nikita

1 answer 1

In your case, it will be easiest to register the BroadcastReceiver in the Activity code. And to detect changes in the connection status, you need to catch the action "android.net.conn.CONNECTIVITY_CHANGE" .

In MainActivity.java

 private BroadcastReceiver mReceiver; @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); IntentFilter intentFilter = new IntentFilter( "android.net.conn.CONNECTIVITY_CHANGE"); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (!isNetworkAvailable()) Toast.makeText(context, "Соединение с Интернет было потеряно", Toast.LENGTH_SHORT).show(); } }; this.registerReceiver(mReceiver, intentFilter); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); this.unregisterReceiver(this.mReceiver); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } 

In AndroidManifest.xml

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