Android判斷網路連線相關方法

2021-06-19 07:39:10 字數 2289 閱讀 6726

獲取網路資訊需要在androidmanifest.xml檔案中加入相應的許可權。

1.判斷是否有網路連線

public boolean isnetworkconnected(context context)   

} return false;

}

2.判斷wifi網路是否可用

public boolean iswificonnected(context context)   

} return false;

}

3.判斷mobile網路是否可用

public boolean ismobileconnected(context context)   

} return false;

}

4.獲取當前網路連線的型別資訊

public static int getconnectedtype(context context)   

} return -1;

}

在開發android應用時,涉及到要進行網路訪問,時常需要進行網路狀態的檢查,以提供給使用者必要的提醒。一般可以通過connectivitymanager來完成該工作。

connectivitymanager有四個主要任務:

1、監聽手機網路狀態(包括gprs,wifi, umts等)

2、手機狀態發生改變時,傳送廣播

3、當乙個網路連線失敗時進行故障切換

4、為應用程式提供可以獲取可用網路的高精度和粗糙的狀態

當我們要在程式中監聽網路狀態時,只要一下幾個步驟即可:

1、定義乙個receiver過載其中的onreceive函式,在其中完成所需要的功能,如根據wifi和gprs是否斷開來改變空間的外觀

connectionreceiver = new broadcastreceiver()  else if (wifistate != null && mobilestate != null  

&& state.connected != wifistate  

&& state.connected != mobilestate) else if (wifistate != null && state.connected == wifistate)  

}}};

2、在適當的地方註冊receiver,可以在程式中註冊,在oncreate中呼叫如下函式即可:

intentfilter intentfilter = new intentfilter();

intentfilter.addaction(connectivitymanager.connectivity_action);

registerreceiver(connectionreceiver, intentfilter);

3、在適當時取消註冊receiver,可以在程式中取消,在ondestroye中呼叫如下函式即可:

if (connectionreceiver != null)

下面是網路判斷的方法:

1.無網路(這種狀態可能是因為手機停機,網路沒有開啟,訊號不好等原因)

2.使用wifi上網

3.cmwap(中國移動**)

4.cmnet上網

這四種狀態,如果沒有網路,肯定是無法請求internet了,如果是wap就需要為手機新增中國移動**,關於為手機新增中國移動的**,請到 這裡寫有關於新增中國移動**的例子!

/**

* @author sky

* email [email protected]

* 獲取當前的網路狀態 -1:沒有網路 1:wifi網路2:wap網路3:net網路

* @param context

* @return

*/ public static int getapntype(context context)

int ntype = networkinfo.gettype();

if(ntype==connectivitymanager.type_mobile)

else

} else if(ntype==connectivitymanager.type_wifi)

return nettype;

}

Android網路連線判斷

獲取網路資訊需要在androidmanifest.xml檔案中加入相應的許可權。工具類 定義乙個類 netstateutil1 判斷是否有網路連線 1 public boolean isnetworkconnected context context 9 10return false 11 2 判斷...

android 網路連線判斷

android 網路判斷類,用來判斷網路狀態 使用方法 1 先初始化 初始化網路狀態檢測類 networkstatemanager.instance init this 2 判斷是否聯網 networkstatemanager.instance isnetworkconnected import a...

Android之網路連線判斷

android進行網路聯網的一些操作時,經常會對網路是否已經連線成功進行判斷。我們通常會對wifi和流動網路進行判斷,我們需要判斷網路裝置是否開啟,是否連線成功,這裡做個筆記哈。package com.example.util import android.content.context impor...