常用方法:
getActiveNetworkInfo() 返回NetworkInfo,当前网络连接的信息
getNetworkInfo(int networkType) 返回一个指定网络的连接信息
getNetworkPreference() 返回首选网络连接的网络类型
setNetworkPreference(int preference)设置首选网络连接的网络类型
NetworkInfo.DetailedState——精确的网络状态
NetworInfo.State——粗略的网路状态
常用函数
isConnected()判断网络连接是否存在
isAvailable()判断网络连接(注:isConnected为true,不代表isAvailable为true)
getDetailedState()(详细)报告当前网络状态
getState()报告当前网络状态
getExtrInfo()报告关于网络状态的额外信息,由较低的网络层提供的
getType()获取当前网络的类型mobile or Wi-Fi
getTypeName() 获取当前网络的类型名 “WIFI” or “MOBILE”
判断当前网络连接状态:
方法1:
public static boolean isNetworkConnected(Context context)
{
ConnectivityManager connMag = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMag.getActiveNetworkInfo();
if(activeNetworkInfo != null){
return activeNetworkInfo.isAvailable();
}
return false;
}
方法2:广播接收器
public BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
Bundle bundle = intent.getExtras();
NetworkInfo aNetworkInfo = (NetworkInfo) bundle.get(ConnectivityManager.EXTRA_NETWORK_INFO);
if (aNetworkInfo.isConnected()){
System.out.println("network normal");
} else{
System.out.println("network problem");
}
}
};
判断网络连接类型与状态:
public static void CheckNetwork(){
ConnectivityManagerconnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetInfo.isConnected()) { Toast.makeText(context, "WIFI网络连接成功", Toast.LENGTH_SHORT).show(); } if (mobNetInfo.isConnected()) { Toast.makeText(context, "手机网络连接成功", Toast.LENGTH_SHORT).show(); } if(!activeNetInfo.isConnected() && !mobNetInfo.isConnected()) { Toast.makeText(context, "网络断开连接", Toast.LENGTH_SHORT).show();
//如果3G网络和wifi网络都未连接,且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接
Builder b = new android.app.AlertDialog.Builder(context).setTitle("没有可用的网络").setMessage("请开启GPRS或WIFI网络连接");
b.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
context.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));//进入无线网络配置界面
//context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //进入手机中的wifi网络设置界面 }}).setNeutralButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}}).create();
b.show();
}
}