In Android, network conditions change from network to no network, from wifi to gprs, and from cmwap to cmnet!
If some functions of your program require network support, you may need to listen to network changes for corresponding processing.
For example, if a file is suddenly disconnected, how can this problem be solved? After the network recovers, how does one listen to and reconnect?
When the network changes, the system will issue a broadcasting broadcast. You only need to register a Broadcasting Receiver BroadcastReceiver in the program and add the corresponding filter to the IntentFilter. Once the network changes, the program will be able to listen
Public static final String CONNECTIVITY_CHANGE_ACTION = "android.net. conn. CONNECTIVITY_CHANGE ";
Private void registerDateTransReceiver (){
Log. I (TAG, "register receiver" + CONNECTIVITY_CHANGE_ACTION );
IntentFilter filter = new IntentFilter ();
Filter. addAction (CONNECTIVITY_CHANGE_ACTION );
Filter. setPriority (1000 );
RegisterReceiver (new MyReceiver (), filter );
}
In mycycler:
@ Override
Public void onReceive (Context context, Intent intent ){
String action = intent. getAction ();
Log. I (TAG, "PfDataTransReceiver receive action" + action );
If (TextUtils. equals (action, CONNECTIVITY_CHANGE_ACTION) {// a notification is sent when the network changes.
Log. I (TAG, "Network changed ");
Return;
}
}
When the network changes, broadcast will also be sent from the network to the network. For example, if the network is disconnected during download, when receiving a broadcast, you must determine whether the current network is available or unavailable. If yes, what operations are available and what operations are unavailable:
Public static NetworkInfo getActiveNetwork (Context context ){
If (context = null)
Return null;
ConnectivityManager mConnMgr = (ConnectivityManager) context
. GetSystemService (Context. CONNECTIVITY_SERVICE );
If (mConnMgr = null)
Return null;
NetworkInfo aActiveInfo = mConnMgr. getActiveNetworkInfo (); // gets the active network connection information
Return aActiveInfo;
}
The aActiveInfo returned by this method can determine whether the Network is available or not. If the returned value is null, the network is disconnected. If the returned object is not null, the network is connected. In the returned NetworkInfo object, you can obtain more information about the current network, such as wifi or cmwap.