2013-12-16 65 views
-1

在我的應用程序中,我希望能夠檢查互聯網連接是否可用。如何處理如果互聯網連接在android中不可用?

正是我想要的:

假設連接不可用,應用程序應該重定向到一個設置頁面設​​置「啓用連接」。

這裏是我的代碼,找出連接可用性...

public Map<String, String> getConnectionDetails(Context context) { 
    Map<String, String> networkDetails = new HashMap<String, String>(); 
    try { 
     ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo wifiNetwork = connectivityManager 
       .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     if (wifiNetwork != null && wifiNetwork.isConnected()) { 

      networkDetails.put("Type", wifiNetwork.getTypeName()); 
      networkDetails.put("Sub type", wifiNetwork.getSubtypeName()); 
      networkDetails.put("State", wifiNetwork.getState().name()); 
     } 

     NetworkInfo mobileNetwork = connectivityManager 
       .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
     if (mobileNetwork != null && mobileNetwork.isConnected()) { 
      networkDetails.put("Type", mobileNetwork.getTypeName()); 
      networkDetails.put("Sub type", mobileNetwork.getSubtypeName()); 
      networkDetails.put("State", mobileNetwork.getState().name()); 
      if (mobileNetwork.isRoaming()) { 
       networkDetails.put("Roming", "YES"); 
      } else { 
       networkDetails.put("Roming", "NO"); 
      } 
     } 
    } catch (Exception e) { 
     networkDetails.put("Status", e.getMessage()); 
    } 
    return networkDetails; 
} 

而且我一卷像烤麪包味精遵循

Map<String, String> networkDetails = networkstate.getConnectionDetails(getApplicationContext()); 
    if (networkDetails.isEmpty()) { 
     Toast.makeText(getApplicationContext(), "Internet Connection unavailable", Toast.LENGTH_SHORT).show(); 
    } else { 
     Toast.makeText(getApplicationContext(), "Internet Connection available", Toast.LENGTH_SHORT).show(); 
    } 

請給建議...

回答

1

你可以試試像

if (networkDetails.isEmpty()) { 
     Intent myIntent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); 
     startActivity(myIntent); 
    } 

這將顯示設置以允許配置無線控制,如Wi-Fi,藍牙和移動網絡。

+0

什麼我要導入無線設置有很多進口建議 –

+0

@AristoMichael導入android.provider.Settings; –

相關問題