2013-04-30 108 views
3

我必須開發一個android應用程序。檢查網絡可在android

在這裏我必須開發一個twitter集成android應用程序。

我一直在使用下面的代碼:

public void onClickTwitt() { 
    if (isNetworkAvailable()) { 
     Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key); 
     twitt.shareToTwitter(_Title); 
    } else { 
     showToast("No Network Connection Available !!!"); 
    } 
} 
public boolean isNetworkAvailable() { 
    ConnectivityManager connectivity =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

    if (connectivity == null) { 
     return false; 
    } else { 
     NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
     if (info != null) { 
      for (int i = 0; i < info.length; i++) { 
       if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
        return true; 
       } 
      } 
     } 
    } 
    return false; 
} 

這裏我得到以下錯誤:

The method getSystemService(String) is undefined for the type 
SubCate 

請幫我...我怎樣才能解決這些錯誤????

+0

isNetworkAvailable()是一個活動的內部所限定的方法? – Blackbelt 2013-04-30 07:37:19

+0

傳遞上下文,如context.getSystemService – 2013-04-30 07:42:16

+0

getSystemService來自Context類。 – njzk2 2013-04-30 07:44:00

回答

4
public void onClickTwitt() { 
    if (isNetworkAvailable(this)) { 
     Twitt twitt = new Twitt(getActivity(), consumer_key, secret_key); 
     twitt.shareToTwitter(_Title); 
    } else { 
     showToast("No Network Connection Available !!!"); 
    } 
} 
public boolean isNetworkAvailable(Context context) { 
    ConnectivityManager connectivity =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    if (connectivity == null) { 
     return false; 
    } else { 
     NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
     if (info != null) { 
      for (int i = 0; i < info.length; i++) { 
       if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
        return true; 
       } 
      } 
     } 
    } 
    return false; 
} 
7
public static boolean isNetworkAvailable(Context context) { 
    if(context == null) { return false; } 
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    // if no network is available networkInfo will be null, otherwise check if we are connected 
    try { 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
     if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) { 
      return true; 
     } 
    } catch (Exception e) { 
     AppLog.e(TAG, "isNetworkAvailable()" , e.getMessage()); 
    } 
    return false; 
} 

,然後執行這個

if(isNetworkAvailable(TempOrderActivity.this)) { 
       //do something 

      } else { 
       //do something 
      }