判斷 android 是否成功聯網

android 中查看當前是否聯網
方法如下:
ConnectivityManager cManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cwjManager.getActiveNetworkInfo();
  if (info != null && info.isAvailable()){
       //do something
       //能聯網
        return true;
  }else{
       //do something
       //不能聯網
        return false;
  }
如果爲True則表示當前Android手機已經聯網,可能是WiFi或GPRS、HSDPA等等,具體的可以通過 ConnectivityManager 類的getActiveNetworkInfo() 方法判斷詳細的接入方式。

同時要在manifest裏面加個權限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

文檔如下:
boolean android.net.NetworkInfo.isAvailable()

public boolean isAvailable ()
Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include

The device is out of the coverage area for any network of this type.
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.
The device's radio is turned off, e.g., because airplane mode is enabled.

Returns
true if the network is available, false otherwise
發佈了15 篇原創文章 · 獲贊 8 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章