android里面有很多应用都需要连接网络才能够运行,所以在运行软件前需要判断一下网络是否连接,还有就是连接类型是什么,是不是wifi连接。
//判断是否连接和连接类型
public static int getAPNType(Context context){
int CMNET = 1;
int CMWAP = 2;
int WIFI = 3;
int netType = -1;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo==null){return netType;}
int nType = networkInfo.getType();
if(nType==ConnectivityManager.TYPE_MOBILE){
Log.e(“networkInfo.getExtraInfo()”, “networkInfo.getExtraInfo() is “+networkInfo.getExtraInfo());
if(networkInfo.getExtraInfo().toLowerCase().equals(“cmnet”)){
netType = CMNET;
}else{
netType = CMWAP;
}
}else if(nType==ConnectivityManager.TYPE_WIFI){
netType = WIFI;
}
return netType;
}
使用判断连接类型
int aa = getAPNType(this);
if(aa == 1 || aa==2){Toast.makeText(MainActivity.this,”手机卡网络连接”,Toast.LENGTH_SHORT).show();}
if(aa == 3){Toast.makeText(MainActivity.this,”wifi连接”,Toast.LENGTH_SHORT).show();}
if(aa == -1){Toast.makeText(MainActivity.this,”没有网络连接”,Toast.LENGTH_SHORT).show();}