2010-05-07 164 views

回答

53

首先,你需要許可才能知道設備是否連接到網絡或沒有。這需要在您的清單,在<manifest>元素:

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

接下來,你需要去的ConnectivityManager參考:

ConnectivityManager cm = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE); 

從那裏,你需要獲得一個NetworkInfo對象。對於大多數人來說,這將意味着使用ConnectivityManager. getActiveNetworkInfo()

NetworkInfo ni = cm.getActiveNetworkInfo(); 
if (ni == null) { 
    // There are no active networks. 
    return false; 
} 

從那裏,你只需要使用的NetworkInfo的方法之一,以確定該設備連接到互聯網:

boolean isConnected = ni.isConnected(); 
+3

我得到這個說法一個空指針異常的可能重複:布爾isConnected = ni.isConnected(); 爲什麼? – 2010-05-18 10:08:02

+0

是的,我也是! – xpepermint 2011-07-02 22:05:49

+3

@Maxood,這意味着沒有活動的網絡。換句話說,該設備沒有連接到網絡。我會改變代碼。 – 2011-10-21 03:01:55

6

首先,你需要有權知道設備是否連接到網絡。這需要在你的清單中的元素:

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

然後

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 

if (connec != null && (
    (connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) || 
    (connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED))) { 

     //You are connected, do something online. 

} else if (connec != null && (
    (connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) || 
    (connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED))) {    

     //Not connected.  
     Toast.makeText(getApplicationContext(), "You must be connected to the internet", Toast.LENGTH_LONG).show(); 

} 
4

在AppManifest.xml文件中添加此權限:

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

的方法檢查如果網絡可用或不可用:

boolean isNetworkAvailable() { 
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 
    return isConnected; 
} 

Source

相關問題