Judge the mobile phone network

Determine the phone has no network here to write a class has a network returns true, not a net return false:

 1 public static int getConnectedType(Context context){
 2         if(context != null){
 3             ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 4             NetworkInfo info = manager.getActiveNetworkInfo();
 5             if(info != null && info.isAvailable()){
 6                 return info.getType();
 7             }
 8         }
 9         return  -1;
10     }

Analyzing the phone through a data network or through WIFI network, the following classes will return three values ​​are (-1: no network 0: cellular data network. 1: WIFI network):

1 public static boolean isConnectInternet(Context context){
2         ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
3         NetworkInfo info = manager.getActiveNetworkInfo();
4         if(info != null){
5             return info.isAvailable();
6         }
7         return false;
8     }

Plus the following rights:

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

Here I wrote a class, easy call:

. 1  public  class the Connections {
 2  
. 3      / * 
. 4      * determines the network type
 5      * value. 1 - the WIFI
 . 6      * value of 0 - Mobile data network
 7      * -1 - Disconnect Network (both not included above)
 8      * / 
. 9      public  static  int getConnectedType (the context context) {
 10          IF (context =! null ) {
 . 11              ConnectivityManager Manager = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
 12 is              the NetworkInfo info = manager.getActiveNetworkInfo ();
 13 is              IF(info != null && info.isAvailable()){
14                 return info.getType();
15             }
16         }
17         return  -1;
18     }
19 
20     /*
21     * 判断网络状态
22     * 有网 - true
23     * 没网 - false
24     */
25     public static boolean isConnectInternet(Context context){
26         ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
27         NetworkInfo info = manager.getActiveNetworkInfo();
28         if(info != null){
29             return info.isAvailable();
30         }
31         return false;
32     }
33 
34 }

 

Guess you like

Origin www.cnblogs.com/Mr-Deng/p/11571371.html