2016-09-13 82 views

回答

0

使用過濾器來檢查網絡狀態(WIFI /手機(2G,3G & 4G))

代碼.........

if(Contant_status.equalsIgnoreCase("WIFI")){ 
       Log.v("haveNetworkConnection","WIFI"); 
      }else if(Contant_status.equalsIgnoreCase("MOBILE")){ 
       if(getNetworkClass(MainActivity.this).equalsIgnoreCase("2G")){ 
        Log.v("haveNetworkConnection","2G"); 
       }else if(getNetworkClass(MainActivity.this).equalsIgnoreCase("3G")){ 
        Log.v("haveNetworkConnection","3G"); 
       }else if(getNetworkClass(MainActivity.this).equalsIgnoreCase("4G")){ 
        Log.v("haveNetworkConnection","4G"); 
       }else if(getNetworkClass(MainActivity.this).equalsIgnoreCase("Unknown")){ 
        Log.v("haveNetworkConnection","Unknown"); 
       } 
      } 

    private void haveNetworkConnection() { 
    String haveConnectedWifi = ""; 
    String haveConnectedMobile = ""; 

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo[] netInfo = cm.getAllNetworkInfo(); 
    for (NetworkInfo ni : netInfo) { 
     if (ni.getTypeName().equalsIgnoreCase("WIFI")) 
      if (ni.isConnected()) 
       haveConnectedWifi = "WIFI"; 
     if (ni.getTypeName().equalsIgnoreCase("MOBILE")) 
      if (ni.isConnected()) 
       haveConnectedMobile = "MOBILE"; 
    } 
    if(haveConnectedWifi.equalsIgnoreCase("WIFI")){ 
     Contant_status = "WIFI"; 
    }else if(haveConnectedMobile.equalsIgnoreCase("MOBILE")){ 
     Contant_status = "MOBILE"; 
    } 
} 

public String getNetworkClass(Context context) { 
    TelephonyManager mTelephonyManager = (TelephonyManager) 
      context.getSystemService(Context.TELEPHONY_SERVICE); 
    int networkType = mTelephonyManager.getNetworkType(); 
    switch (networkType) { 
     case TelephonyManager.NETWORK_TYPE_GPRS: 
     case TelephonyManager.NETWORK_TYPE_EDGE: 
     case TelephonyManager.NETWORK_TYPE_CDMA: 
     case TelephonyManager.NETWORK_TYPE_1xRTT: 
     case TelephonyManager.NETWORK_TYPE_IDEN: 
      return "2G"; 
     case TelephonyManager.NETWORK_TYPE_UMTS: 
     case TelephonyManager.NETWORK_TYPE_EVDO_0: 
     case TelephonyManager.NETWORK_TYPE_EVDO_A: 
     case TelephonyManager.NETWORK_TYPE_HSDPA: 
     case TelephonyManager.NETWORK_TYPE_HSUPA: 
     case TelephonyManager.NETWORK_TYPE_HSPA: 
     case TelephonyManager.NETWORK_TYPE_EVDO_B: 
     case TelephonyManager.NETWORK_TYPE_EHRPD: 
     case TelephonyManager.NETWORK_TYPE_HSPAP: 
      return "3G"; 
     case TelephonyManager.NETWORK_TYPE_LTE: 
      return "4G"; 
     default: 
      return "Unknown"; 
    } 
} 
相關問題