To develop a network-based application on the Android platform, you must determine the current network connection status. The following code, as an example, describes in detail how to judge the current network situation.
First, let's look at a self-defined application class.
View plaincopy to clipboardprint?
Public class NetworkDetector {
Public static boolean detect (Activity act ){
ConnectivityManager = (ConnectivityManager) act
. GetApplicationContext (). getSystemService (
Context. CONNECTIVITY_SERVICE );
If (manager = null ){
Return false;
}
NetworkInfo networkinfo = manager. getActiveNetworkInfo ();
If (networkinfo = null |! Networkinfo. isAvailable ()){
Return false;
}
Return true;
}
}
Public class NetworkDetector {
Public static boolean detect (Activity act ){
ConnectivityManager = (ConnectivityManager) act
. GetApplicationContext (). getSystemService (
Context. CONNECTIVITY_SERVICE );
If (manager = null ){
Return false;
}
NetworkInfo networkinfo = manager. getActiveNetworkInfo ();
If (networkinfo = null |! Networkinfo. isAvailable ()){
Return false;
}
Return true;
}
}
This class has only one static method to check whether the network of the current system is available. If available, return true.
It should be further noted that the NetworkInfo class has a method getType (), which can be used to determine whether the current available network is wifi or mobile.
Let's take a look at the example.
View plaincopy to clipboardprint?
Boolean networkState = NetworkDetector. detect (XXXActivity. this );
If (! NetworkState ){
DialogUtil. openMsgDialog (XXXActivity. this,
Android. R. drawable. ic_dialog_info,
"The network is unavailable. Do you want to set up the network now ?", Android. R. string. OK,
Android. R. string. cancel,
New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
StartActivityForResult (new Intent (
ACTION_WIRELESS_SETTINGS), 0 );
}
}, New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. cancel ();
}
}). Show ();
}
Boolean networkState = NetworkDetector. detect (XXXActivity. this );
If (! NetworkState ){
DialogUtil. openMsgDialog (XXXActivity. this,
Android. R. drawable. ic_dialog_info,
"The network is unavailable. Do you want to set up the network now ?", Android. R. string. OK,
Android. R. string. cancel,
New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
StartActivityForResult (new Intent (
ACTION_WIRELESS_SETTINGS), 0 );
}
}, New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface dialog, int which ){
Dialog. cancel ();
}
}). Show ();
}
XXXActivity is my own