In Android, many people use the following methods to determine whether the current network is available:
/**
* Get current network state (whether available)/public
static Boolean isnetworkavailable () {
Boolean isaalable = false;
Connectivitymanager Connmanager = (Connectivitymanager) baseapplication.getapplication (). GetSystemService ( Context.connectivity_service);
if (Connmanager!= null && connmanager.getactivenetworkinfo ()!= null) {
isaalable = Connmanager.getactivenetworkinfo (). isavailable ();
}
return isaalable;
}
However, if you have an exception record, you may see the following exception information:
Many people do not understand, clearly have been judged whether it is empty, why still appear null pointer anomaly? This kind of anomaly often appears in the network state extremely unstable time, the following first read the correct wording:
/**
* Get current network status (available) */public
static Boolean isnetworkavailable () {
Connectivitymanager Connmanager = (Connectivitymanager) baseapplication.getapplication (). Getsystemservice (Context.connectivity_service);
if (Connmanager!= null) {
/**
* Get Network Information entity
* Since the data obtained from the system service belongs to interprocess communication, data outside the base type must implement the Parcelable interface,
* Networkinfo implements the Parcelable and obtains a activenetinfo equivalent to a copy (copy) of the Network information entity object in the service,
* So, regardless of whether the entity object in the System Network service is set to NULL, The Activenetinfo obtained here will not change
* *
networkinfo activenetinfo = Connmanager.getactivenetworkinfo ();
if (activenetinfo!= null) {return
activenetinfo.isavailable ();
}
}
return false;
}
As for why it can be changed to write on it, the code comments have been said to be very clear, it is not quite understood to look at interprocess communication (IPC) and pacelable knowledge.
The above is a small set to introduce the android in the use of Networkinfo to determine the status of the network when the null pointer (nullpointerexception) problem solution, I hope to help you, if you have any questions please leave me a message, Small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!