檢查網路是否連線

2 篇文章 / 0 new
最新文章
author
檢查網路是否連線
在Android 中是否已連網可以通過 ConnectivityManager.getActiveNetworkInfo().isAvailable() 來判斷,如果為True則表示當前Android手機已經連網,可能是WiFi或GPRS、HSDPA等等.
public String internetState()
{
    String state = "Net:";
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info=connManager.getActiveNetworkInfo();//wifi
    if (info == null)
        state = state + " No WiFi";
    if (info.isConnected())
    {
        state = state + " WiFi Online";
        if (info.isAvailable())
        {
            state = state + " Available";
        }
    } else
        state = state + " WiFi Offline";
 
    NetworkInfo mobNetInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );//3G
    if (info == null)
        state = state + " No 3G";
    if (info.isConnected())
    {
        state = state + " 3G Online";
        if (info.isAvailable())
        {
            state = state + " Available";
        }
    } else
        state = state + " 3G Offline";
    //
    return state;
}
需具有權限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
author
檢查所有連線裝置
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = connManager.getAllNetworkInfo();
if ( (networkInfo != null) && (networkInfo.length > 0) ) {
    for (int i = 0; i < networkInfo.length; i++) {
        Log.d("Net","裝置 == "+ networkInfo[i].getTypeName());
        if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
            Log.d("Net","connect");
        }
    }
}
發表回應前,請先登入
Free Web Hosting