2015-04-04 88 views
0

我在我的android應用程序中使用互聯網。我從服務器獲取數據,因此我必須檢查用於嘗試在服務器上請求的互聯網連接。我能爲此做些什麼?檢查互聯網連接是否可用?

回答

0

這是我用來檢查我的應用程序是否連接到互聯網的功能。

private void CheckEnabledInternet() { 
    boolean isConnected = false; 
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 
    NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo(); 
    for(NetworkInfo networkInfo : networkInfos) { 
     if(networkInfo.getState()== NetworkInfo.State.CONNECTED) { 
      isConnected = true; 
      break; 
     } 
    } 
    if(!isConnected) { 
     AlertDialog.Builder networkDialog = new AlertDialog.Builder(this); 
     networkDialog.setTitle("Not Connected"); 
     networkDialog.setMessage("Please connect to internet to proceed"); 
     networkDialog.setCancelable(false); 
     networkDialog.setPositiveButton("Okay!",new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       CheckEnabledInternet(); 
      } 
     }); 
     networkDialog.create().show(); 
    } 
}