android开发离不开网络,在我们的程序中就需要判断当前网络是否处理连接状态,如果没有任何网络连接,则程序会弹出一个对话框,询问用户是否进行相关的网络配置。现在将这些功能封装在一个类中,在项目中可以直接使用。代码如下:
public class NetWorkUtils {
/**
* 判断当前网络是否处于连接状态
* @param context
* @return true表示有连接,可以上网 ;false表示无连接,不能上网
*/
public static boolean isconnected(Context context) {
ConnectivityManager conMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMan != null) {
// 获取网络连接管理的对象
NetworkInfo info = conMan.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 判断当前网络是否已经连接
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
/*
// mobile 3G Data Network
State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
// wifi
State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
// 如果3G网络和wifi网络都未连接,且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
if (mobile == State.CONNECTED || mobile == State.CONNECTING)
return true;
if (wifi == State.CONNECTED || wifi == State.CONNECTING)
return true;
*/
return false;
}
/**
* 无网络连接时,弹出对话框
* @param context
*/
public static void showConfigNetWorkDialog(Context context) {
final Context cxt = context;
AlertDialog.Builder builder = new AlertDialog.Builder(cxt);
builder.setMessage("当前无任何网络连接,请进行相关设置")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
cxt.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
如:在新浪微博程序中,程序启动后就需要检查网络连接状态然后做出相应的处理。