當前位置:首頁 » 安卓系統 » android網路狀態檢測

android網路狀態檢測

發布時間: 2022-05-14 11:01:19

Ⅰ android 怎麼監控網路狀態可以訪問互聯網而不是連接狀態

在開發android應用時,涉及到要進行網路訪問,時常需要進行網路狀態的檢查,以提供給用戶必要的提醒。一般可以通過ConnectivityManager來完成該工作。
ConnectivityManager有四個主要任務:
1、監聽手機網路狀態(包括GPRS,WIFI, UMTS等)
2、手機狀態發生改變時,發送廣播
3、當一個網路連接失敗時進行故障切換
4、為應用程序提供可以獲取可用網路的高精度和粗糙的狀態
當我們要在程序中監聽網路狀態時,只要一下幾個步驟即可:
1、定義一個Receiver重載其中的onReceive函數,在其中完成所需要的功能,如根據WIFI和GPRS是否斷開來改變空間的外觀
復制代碼 代碼如下:

connectionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
Log.i(TAG, "unconnect");
// unconnect network
}else {
// connect network
}
}
};

2、在適當的地方注冊Receiver,可以在程序中注冊,在onCreate中調用如下函數即可:
復制代碼 代碼如下:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionReceiver, intentFilter);

3、在適當時取消注冊Receiver,可以在程序中取消,在onDestroye中調用如下函數即可:
復制代碼 代碼如下:

if (connectionReceiver != null) {
unregisterReceiver(connectionReceiver);
}

Ⅱ android 判斷是否有網路

用戶手機當前網路可用:WIFI、2G/3G網路,用戶打開與不打開網路,和是否可以用是兩碼事。可以使用指的是:用戶打開網路了並且可以連上互聯網進行上網。
檢測當前網路是否可用,代碼如下:
/**
* 檢測當的網路(WLAN、3G/2G)狀態
* @param context Context
* @return true 表示網路可用
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 當前網路是連接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 當前所連接的網路可用
return true;
}
}
}
return false;
}
/**
* 檢測當的網路(WLAN、3G/2G)狀態
* @param context Context
* @return true 表示網路可用
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 當前網路是連接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 當前所連接的網路可用
return true;
}
}
}
return false;
}

在AndroidManifest.xml文件添加的許可權:

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

Ⅲ Android檢測是否有網路的代碼

public class CheckNetwork {
private NetworkStateReceiver netStateReceiver;
private Context mContext;
private long servicetimes = 0;
private Utility myUtility = null;
private int runInternerTime = 0;
private HandlerNetwork mHandlerNetwork = new HandlerNetwork();
private static CheckNetwork mNetworkState = null;
private Map<String, Handler> mHandlerOuterMap = new HashMap<String, Handler>();

public static CheckNetwork getNetworkState(Context context) {
if (mNetworkState == null) {
mNetworkState = new CheckNetwork(context);
}
return mNetworkState;
}

private CheckNetwork(Context context) {
mContext = context;
myUtility = new Utility(mContext);

registNetworkStatusReceiver();

}

public void registNetworkStatusReceiver() {
netStateReceiver = new NetworkStateReceiver(mHandlerNetwork);
IntentFilter filter = new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE");
filter.addAction("android.intent.action.MY_NET_BOOTCHECK");
mContext.registerReceiver(netStateReceiver, filter);

Intent intent = new Intent("android.intent.action.MY_NET_BOOTCHECK");
mContext.sendBroadcast(intent);
}

/**
* 增加一個網路狀態消息接受者
*
* @param key
* @param handler
*/
public void addHandler(String key, Handler handler) {

mHandlerOuterMap.put(key, handler);
if (!key.equals("IntegrateActHandlerKey")) {
// 當整合頁添加handle時,網路狀態還沒准備好,所以不通過handle對外發通知
sendNetworkMessage(mHandlerOuterMap);
}
}

/**
* 向接受者集合中的接受者發送網路狀態的消息
*
* @param map
*/
public static void sendNetworkMessage(Map<String, Handler> map) {

Set<String> key = map.keySet();
for (Object element : key) {
String s = (String) element;
Message msg = Message.obtain();
msg.what = GlobalParams.Handle_Msg.NetWorkStatus.ordinal();
map.get(s).sendMessage(msg);
}
}

private class HandlerNetwork extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg.what == GlobalParams.Handle_Msg.ConnectSuccess.ordinal()) {
if (System.currentTimeMillis() - servicetimes > 3000) {// 防止短時間內接收多個廣播,執行多次
runInternerTime = 0;
servicetimes = System.currentTimeMillis();
new CheckServerThread().start();
}
} else if (msg.what == GlobalParams.Handle_Msg.ConnectFail
.ordinal()) {
if (System.currentTimeMillis() - servicetimes > 2000) {// 防止短時間內接收多個廣播,執行多次
servicetimes = System.currentTimeMillis();
runInternerTime++;
if (runInternerTime > 3) {
// Intent intent = new Intent(context,
// IntegrateActivity.class);
// context.startActivity(intent);

GlobalParams.NetworkStatus = 0;
sendNetworkMessage(mHandlerOuterMap);
} else {
Log.e("RUN", "本地連接不上嘗試第" + runInternerTime + "次");
Message msgrun = Message.obtain();
msgrun.what = GlobalParams.Handle_Msg.InternerFail
.ordinal();
mHandlerNetwork.sendMessageDelayed(msgrun, 3000);
}

}
} else if (msg.what == GlobalParams.Handle_Msg.InternerFail
.ordinal()) {
//檢測棒子與路由器間的連接不足3次時,繼續檢測
Intent intent = new Intent(
"android.intent.action.MY_NET_BOOTCHECK");
mContext.sendBroadcast(intent);
}else if(msg.what==GlobalParams.Handle_Msg.NetWorkStatusIn.ordinal()){
if(msg.arg1==0){
GlobalParams.NetworkStatus = 2;
sendNetworkMessage(mHandlerOuterMap);
}else{
GlobalParams.NetworkStatus = 1;
sendNetworkMessage(mHandlerOuterMap);
}
}
}
}

private class CheckServerThread extends Thread{
@Override
public void run() {
File f = new File(Environment.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher/Images");
if (!f.exists())
f.mkdirs();
File ftemp = new File(Environment.getExternalStorageDirectory()
.getPath() + "/CudgelLauncher/Temp");
if (!ftemp.exists())
ftemp.mkdirs();

// 等待SD卡准備完成
while (true) {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 因為舊的配置文件都不適合用於新版,所以要把舊的都清除再重新載入
myUtility.delete(new File("/data/data/"
+ GlobalParams.PROCESSPACKNAME
+ "/databases/cudgellauncher"));
myUtility.delete(new File("/system/media/cudgel"));
myUtility.delete(new File("/mnt/sdcard/CudgelLauncher"));
break;
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

XmlParser parser = new XmlParser();
File fileConfig = new File("/mnt/sdcard/CudgelLauncher/config.xml");
File file = new File("/mnt/sdcard/CudgelLauncher/ConfigInterface.xml");
while (true) {
try {
Map<String, String> mapConfig = parser
.getServiceAsmx(fileConfig);
Map<String, String> mapInterface = parser.getServiceAsmx(file);
if (!fileConfig.exists() || mapConfig == null
|| !mapConfig.containsKey("area") || !file.exists()
|| mapInterface == null
|| !mapInterface.containsKey("servicenamespace")) {
// 第一次運運沒配置文件時或防止配置文件被損壞,重新復制
myUtility.saveConfigFile(Environment
.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher", "Config.xml", R.raw.config,
mContext);
myUtility.saveConfigFile(Environment
.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher", "ConfigInterface.xml",
R.raw.configinterface, mContext);
} else {
GlobalParams.AreaID = mapConfig.get("area");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//開始檢測通不通公網
PingAddrUtils pingAddrUtils=new PingAddrUtils(mHandlerNetwork,GlobalParams.Handle_Msg.NetWorkStatusIn.ordinal());
pingAddrUtils.startPingAddr();
super.run();
}
}
}

ublic class PingAddrUtils {
private final static byte[] writeLock = new byte[0];
private String[] urls = new String[] { "tiipot.chinadhia.com",
"www.youku.com", "v.qq.com", "www.letv.com", "www..com",
"www.pptv.com", "tv.sohu.com" };
private String[] names = new String[] { "雲聯", "優酷", "騰訊", "樂視", "網路",
"pptv", "搜狐" };
private boolean[] isConected = { false, false, false, false, false, false,
false };
private Handler mHandler;
private int msgWhat;
private Timer timer;

/**
* mHandler用於接收返回成功連接或失敗的消息
*
* @param mHandler
* @param mContext
*/
public PingAddrUtils(Handler mHandler, int msgWhat) {
this.mHandler = mHandler;
this.msgWhat = msgWhat;
}

/**
* 開始ping地址,返回值通過消息形式發送到構造方法傳入的Handler,msg.What也是用構造方法傳入的msgWhat
* 參數說明arg1:0失敗;1通了;obj:用於生成二維碼的字元串(String)
*
* @param msgWhat
*/
public void startPingAddr() {
// 開始檢測時把狀態都置為false以防重復檢測時出現錯誤結果
for (int i = 0; i < isConected.length; i++) {
isConected[i] = false;
}
for (int i = 0; i < urls.length; i++) {
new IpAddrThread(i).start();
}
timer = new Timer();
timer.schele(new TimerTask() {
@Override
public void run() {
if (!isAllConected()) {// 全通線程中已處理了,所以這里只考慮沒有全通的情況
boolean isAnyOneConected = false;
for (int i = 0; i < isConected.length; i++) {
isAnyOneConected = isAnyOneConected || isConected[i];
}
if (isAnyOneConected) {
sendMessage(1);// 有某個地址連接成功了。
} else {
sendMessage(0);// 全部地址連接失敗。
}
}
}
}, 9000);// 9秒後
}

/***
* 判斷是否所有地址都一ping通
*
* @return
*/
private boolean isAllConected() {
boolean isAllConected = true;
for (int j = 0; j < isConected.length; j++) {
// 所有都為TRUE isAllConected才為TRUE
isAllConected = isAllConected && isConected[j];
}
return isAllConected;
}

class IpAddrThread extends Thread {
int IpNum;

public IpAddrThread(int IpNum) {
this.IpNum = IpNum;
}

@Override
public void run() {
try {
Process p = Runtime.getRuntime().exec(
"ping -c 3 -w 5 " + urls[IpNum]);
int status = p.waitFor();

if (status == 0) {
// pass
// mPingIpAddrResult = "連接正常";
setThisIpTrue(IpNum);
} else {
// Fail:Host unreachable
// mPingIpAddrResult = "連接不可達到";
}
} catch (UnknownHostException e) {
// Fail: Unknown Host
// mPingIpAddrResult = "出現未知連接";
} catch (IOException e) {
// Fail: IOException
// mPingIpAddrResult = "連接出現IO異常";
} catch (InterruptedException e) {
// Fail: InterruptedException
// mPingIpAddrResult = "連接出現中斷異常";
}
}
}

/**
* 生成用於產生二維碼的字元串。01~10~21~31~41~50~61,有7組結果,用符號~分隔,每組結果都有兩位數字,第一位數字代表是哪個伺服器(
* 0是XX,1是優酷,2是 騰訊, 3是樂視, 4是網路,5是pptv,6是搜狐),第二位數字代碼ping的結果(0表示不通,1表示已通)
*
* @return
*/
private String getQRCodeString() {
String oRCodeString = "";
for (int i = 0; i < isConected.length; i++) {
int state = 0;
if (isConected[i]) {
state = 1;
}
oRCodeString = oRCodeString + i + state;
if (i < isConected.length - 1) {
oRCodeString = oRCodeString + "~";
}
}
writeFileSdcard(oRCodeString);
return oRCodeString;
}

/**
* 寫入SD卡
*
* @param filePath
* @param message
*/
private void writeFileSdcard(String message) {

try {
File file = new File("/mnt/sdcard/netstatus.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);

FileOutputStream fout = new FileOutputStream(file);

byte[] bytes = message.getBytes();

fout.write(bytes);

fout.close();

}

catch (Exception e) {

e.printStackTrace();

}

}

/**
* 定義消息並發送
*
* @param state
*/
private void sendMessage(int state) {
Message msg = Message.obtain();
msg.what = msgWhat;
msg.arg1 = state;// 全通
msg.obj = getQRCodeString();
mHandler.sendMessage(msg);
}

/**
* 把該ipNum代表的地址的通達狀況置為True並判斷是否所有都已聯通,如果都已連通則發送成功連接的消息
*
* @param IpNum
*/
private void setThisIpTrue(int IpNum) {
synchronized (writeLock) {
isConected[IpNum] = true;// 把本地址的標記置為true;
if (isAllConected()) {
sendMessage(1);
timer.cancel();
timer = null;

}

}
}
}

Ⅳ android 怎麼判斷網路狀態

獲取android系統的連接服務可判斷網路連接狀態,代碼如下
public class NetUtils{
public static boolean isNetworkConnected(Context context){
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] infos = cm.getAllNetworkInfo();
for(NetworkInfo info:infos){
if(info.isAvailable()&&info.isConnected()){
return true;
}
}
return false;
}
}

NetworkInfo的isAvailable()和isConnected()有以下5種狀態:
在WLAN設置界面
1,顯示連接已保存,但標題欄沒有,即沒有實質連接上:isConnected()==false,isAvailable()=true
2,顯示連接已保存,標題欄也有已連接上的圖標:isConnected()==true,isAvailable()=true
3,選擇不保存後:isConnected()==false,isAvailable()=true
4,選擇連接,在正在獲取IP地址時:isConnected()==false,isAvailable()=false
5,連接上後:isConnected()==true,isAvailable()=true

Ⅳ Android系列之如何判斷網路鏈接狀態

獲取android系統的連接服務可判斷網路連接狀態,代碼如下

java">publicclassNetUtils{
(Contextcontext){
=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[]infos=cm.getAllNetworkInfo();
for(NetworkInfoinfo:infos){
if(info.isAvailable()&&info.isConnected()){
returntrue;
}
}
returnfalse;
}
}

NetworkInfo的isAvailable()和isConnected()有以下5種狀態:

在WLAN設置界面

1,顯示連接已保存,但標題欄沒有,即沒有實質連接上:isConnected()==false,isAvailable()=true


2,顯示連接已保存,標題欄也有已連接上的圖標:isConnected()==true,isAvailable()=true


3,選擇不保存後:isConnected()==false,isAvailable()=true


4,選擇連接,在正在獲取IP地址時:isConnected()==false,isAvailable()=false


5,連接上後:isConnected()==true,isAvailable()=true

Ⅵ 如何判斷 android 網路狀態

在屏幕的上方有沒有E\G\H\3G的圖標,圖標下方是打對勾的還是上下箭頭?如果有就代表你的網路是開啟的

Ⅶ android 怎麼判斷當前網路連接是否可以連接到外網

Android里判斷是否可以上網,常用的是如下方法:

/**
* 檢測網路是否連接
*
* @return
*/
private boolean isNetworkAvailable() {
// 得到網路連接信息
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// 去進行判斷網路是否連接
if (manager.getActiveNetworkInfo() != null) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false;
}

有時候我們連接上一個沒有外網連接的WiFi或者有線就會出現這種極端的情況,目前Android SDK還不能識別這種情況,一般的解決辦法就是ping一個外網。

/* @author suncat
* @category 判斷是否有外網連接(普通方法不能判斷外網的網路是否連接,比如連接上區域網)
* @return
*/
public static final boolean ping() {

String result = null;
try {
String ip = "www..com";// ping 的地址,可以換成任何一種可靠的外網
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping網址3次
// 讀取ping的內容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的狀態
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}

Ⅷ android判斷移動網路是否打開

Android 判斷網路狀態這一應用技巧在實際應中是比較重要的。那麼,在Android操作系統中,如何能夠正確的判斷我們所連接的網路是否斷開:
public class ConnectionChangeReceiver extends
BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService
( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.
getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo
( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " +
activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " +
mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
< !-- Needed to check when the network connection changes -->
< uses-permission android:name="android.permission.
ACCESS_NETWORK_STATE"/>
< receiver android:name="com.blackboard.androidtest.
receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
< intent-filter>
< action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
< /intent-filter>
< /receiver>

Ⅸ androidstudio中實現顯示手機當前網路狀態


1、首先先用usb線連接android手機,然後輸入指令:adbtcpip,埠號默認為5555。
2、設置埠號後,然後查看設置中手機的ip地址。
3、通過adb連接ip地址adbconnectip地址。
4、打開androidstudio,可以看到手機已經連接上了。

Ⅹ android 如何判斷網路是否能夠上網

實現步驟:
下面解決辦法來自於android學習手冊,android學習手冊包含9個章節,108個例子,源碼文檔隨便看,例子都是可交互,可運行,源碼採用android studio目錄結構,高亮顯示代碼,文檔都採用文檔結構圖顯示,可以快速定位。360手機助手中下載。排到第三個。
1、獲取ConnectivityManager對象
Context context = activity.getApplicationContext();
// 獲取手機所有連接管理對象(包括對wi-fi,net等連接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

2、獲取NetworkInfo對象
// 獲取NetworkInfo對象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

3、判斷當前網路狀態是否為連接狀態
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}

4、在AndroidManifest.xml中添加訪問當前網路狀態許可權
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

代碼如下:

public class ClassTestDemoActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isNetworkAvailable(ClassTestDemoActivity.this))
{
Toast.makeText(getApplicationContext(), "當前有可用網路!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "當前沒有可用網路!", Toast.LENGTH_LONG).show();
}
}

/**
* 檢查當前網路是否可用
*
* @param context
* @return
*/

public boolean isNetworkAvailable(Activity activity)
{
Context context = activity.getApplicationContext();
// 獲取手機所有連接管理對象(包括對wi-fi,net等連接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivityManager == null)
{
return false;
}
else
{
// 獲取NetworkInfo對象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

if (networkInfo != null && networkInfo.length > 0)
{
for (int i = 0; i < networkInfo.length; i++)
{
System.out.println(i + "===狀態===" + networkInfo[i].getState());
System.out.println(i + "===類型===" + networkInfo[i].getTypeName());
// 判斷當前網路狀態是否為連接狀態
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}

熱點內容
linux查看arp 發布:2025-08-13 07:53:30 瀏覽:474
為什麼刷機還要弄以前的解鎖密碼 發布:2025-08-13 07:47:14 瀏覽:273
acfun如何上傳 發布:2025-08-13 07:35:10 瀏覽:270
ftp共享伺服器需要什麼配置 發布:2025-08-13 07:33:00 瀏覽:543
主要資料庫 發布:2025-08-13 07:15:27 瀏覽:178
壓縮包漫畫 發布:2025-08-13 07:15:25 瀏覽:131
伺服器空島原版如何獲得礦物 發布:2025-08-13 07:08:22 瀏覽:437
購車時哪些是必備的配置 發布:2025-08-13 06:42:33 瀏覽:693
寶塔添加腳本 發布:2025-08-13 06:41:56 瀏覽:502
ios資料庫存儲 發布:2025-08-13 06:28:10 瀏覽:975