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...手机网连接状态判断。