2017-08-26 98 views
0
public boolean isNetworkConnectionAvailable(){ 
     ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetwork = manager.getActiveNetworkInfo(); 
     boolean isConnected = activeNetwork != null && activeNetwork.isConnected(); 
     if(isConnected) { 

       Log.d("Network", "Connected"); 
       return true; 

     } 
     else{ 
      checkNetworkConnection(); 
      Log.d("Network","Not Connected"); 
      return false; 
     } 
    } 

這表明無法解決connectivitymanager和NETWORKINFO ....請幫助.. 在此先感謝檢查網絡連接在android中是否可用?

+0

嘗試清潔工程後的重建..嘗試添加此直接 進口android.net .ConnectivityManager; import android.net.NetworkInfo; –

+0

檢查您的清單是否具有適當的權限,您應該擁有「android.permission.ACCESS_NETWORK_STATE」權限。 – Dexter

回答

1

試試這個方法的util。我創建了一個實用程序類,並將此方法將其

public class Utils { 
     /** 
     * ****************************************** 
     * Method to check whether the Internet is Connected 
     * ****************************************** 
     */ 
     public static boolean IsNetworkConnected(Context context) { 
      if (context != null) { 
       ConnectivityManager connMgr = (ConnectivityManager) context 
         .getSystemService(Context.CONNECTIVITY_SERVICE); 
       NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
       return (networkInfo != null && networkInfo.isConnected()); 
      } else { 
       return false; 
      } 
     } 
} 

你可以試試這個方法

boolean isConnected = Utils.IsNetworkConnected(mContext); 

,並嘗試之前,添加這些permissionsto AndroidManifest.xml中

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

先閱讀問題!他不是要求網絡檢查方法,他與ConnectivityManager有問題! –

1

授予權限在AndroidManifest.xml中

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

使用般的魅力這種方法工作...

private boolean isNetworkAvailable() { 
ConnectivityManager connectivityManager 
     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 

}

您還需要:

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