Android uses BroadcastReceiver to listen for changes in network connection status

  • 2021-09-11 21:28:25
  • OfStack

Only need to achieve the following two pieces of code to achieve the status of network connection monitoring, don't forget to add network access rights in Manifest. xml.

1. Define a broadcast receiver

NetState.java


package huaxa.it.map.net;

import huaxa.it.map.demo.MapDemo;

import com.baidu.mapapi.map.MapView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiInfo;
import android.util.Log;
import android.widget.Toast;

/**
 * @ Project name:  ZhiHUIGuangDong
 * @ Package name:  huaxa.it.zhihuiguangdong
 * @ Class name:  NetState
 * @ Creator:   Yellow summer lotus 
 * @ Creation time:  2016 Year 10 Month 22 Day  , Morning 1:10:16
 * 
 * @ Description:  TODO
 */
public class NetState extends BroadcastReceiver
{

 public int flag = 0;
 private int flag1=0;

 @Override
 public void onReceive(Context context, Intent arg1)
 {
  ConnectivityManager manager = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
  if (activeNetworkInfo == null)
  {
   Toast.makeText(context, " There is currently no network. Please check the network connection of your mobile device ", Toast.LENGTH_SHORT)
     .show();
   flag = 1;
   flag1 = 1;
   Log.i("TAG"," The network is not connected +flag+"+flag);
  }
  // activeNetworkInfo.getTypeName();  How to connect 
  // :cmwap/cmnet/wifi/uniwap/uninet
  // activeNetworkInfo.isAvailable();  Is the current network available (true)
  // activeNetworkInfo.isFailover(); There is something wrong with the network 
  else
  {
   if (!activeNetworkInfo.isAvailable()
     || activeNetworkInfo.isFailover())
   {
    Toast.makeText(context, " The current network is unavailable ", Toast.LENGTH_SHORT).show();
    flag = 1;
    flag1=2;
    Log.i("TAG"," The current network is unavailable flag+"+flag);
   }

   if (flag == 1)
   {
    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
    {
     Toast.makeText(context, " Move Data on Connection ", Toast.LENGTH_SHORT)
       .show();
    } else
    {
     Toast.makeText(context, " Connected WIFI Data ", Toast.LENGTH_SHORT)
       .show();
    }
    Log.i("TAG"," Network ok,flag+"+flag+"....."+flag1);
   }

  }
 }
}

2. Register Broadcast Receiver

Add in Activity:


NetState receiver = new NetState();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
this.registerReceiver(receiver, filter);// Registration 
receiver.onReceive(this, null);// Receive 

Broadcast Receiver Knowledge Points

Every time a message is received, onReceive (Context context, Intent intent) is called to process it.

Intent can pass data to realize custom broadcast events, and then send them through sendBroadcast (intent). The received data is processed through the onReceive () method.


String Action = "xxxxxx";//xxxxxx Refers to custom Broadcast Adj. action Attributes, such as com.annyAndroid.broadcastdemo.action.USER_BROADCAST , defined casually, but in the broadcast receiver's intentfilter In action Property must be associated with this 1 To 
Intent intent = new Intent();
intent.putExtra("user","huaxa");//key-Value
sendBroadcast(intent);

Note: If the code execution time in the onReceive () method exceeds 5s, Android will be ANR.

1. Use a broadcast receiver


public class AAAAA extends Broadcast Receiver{
 @Override
 onReceive(Context context,Intent intent){
 // Handling broadcast events 
 ......
 }
}

2. Register Broadcast Receiver (2 methods)

1) In Manifest. xml:


<receiver android:name=".MyReceiver"> 
   <intent-filter> 
    <action android:name="xxxxxxxx"/>
    <!--xxxxx Of the broadcast event Action Attribute  -->
   </intent-filter> 
</receiver> 

2. In Activity, onCreate () is implemented by Java code


IntentFilter filter = new IntentFilter(xxxx);// Object for adding an event ACTION Such as battery power, network connection changes, incoming calls, short messages, etc. 
AAAAA aAAAA = new AAAAA();
registerReceiver(aAAAA,filter);// Registration 

3) When appropriate, cancel the registration of Receiver, which can be cancelled in the program, and call the following function in onDestroy ():


if (connectionReceiver != null) {
 unregisterReceiver(connectionReceiver);
 }

Related articles: