码迷,mamicode.com
首页 > 移动开发 > 详细

android设备判断网络连接状态

时间:2015-02-12 18:38:52      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:android   网络   network   状态   

android开发中,在做网络请求前判断当前网络连接状态有时很有必要。本文将介绍如何获取android设备当前网络连接状态!


所需权限(AndroidManifest.xml文件中添加):

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

Java代码(MainActivity.java文件)

package com.example.androidtest;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		boolean bFlag = isNetworkAvailable(this.getApplicationContext());
		if (bFlag) {
			Log.i("Network state - ", "connected");
		} else {
			Log.i("Network state - ", "disconnected");
		}

	}

	/**
	 * 判断网络连接状况
	 * 
	 * @param ctx
	 * @return
	 */
	public boolean isNetworkAvailable(Context ctx) {
		boolean bFlag = false;
		if (ctx != null) {
			ConnectivityManager conMan = (ConnectivityManager) ctx
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (conMan != null) {
				// wifi Network
				NetworkInfo nInfoW = conMan
						.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				if (nInfoW != null) {
					State wifi = nInfoW.getState();
					if (State.CONNECTED == wifi) {
						bFlag = true;
					}
				}
				if (!bFlag) {
					// mobile Network
					NetworkInfo nInfoM = conMan
							.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
					if (nInfoM != null) {
						State mobile = nInfoM.getState();
						if (State.CONNECTED == mobile) {
							bFlag = true;
						}
					}
				}
			}
		}
		return bFlag;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}

isNetworkAvailable方法里先做wifi连接状态判断,如果wifi未连接,再做2g/3g/4g...手机网连接状态判断。




android设备判断网络连接状态

标签:android   网络   network   状态   

原文地址:http://blog.csdn.net/chadeltu/article/details/43763827

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!