Android之网络连接判断
16lz
2022-08-04
Android进行网络联网的一些操作时,经常会对网络是否已经连接成功进行判断。我们通常会对wifi和移动网络进行判断,我们需要判断网络设备是否开启,是否连接成功,这里做个笔记哈。
- packagecom.example.util;
- importandroid.content.Context;
- importandroid.net.ConnectivityManager;
- importandroid.net.NetworkInfo;
- importandroid.net.wifi.WifiManager;
- importandroid.telephony.TelephonyManager;
- importandroid.util.Log;
- /**
- *
- *@authorXuZhiwei(xuzw13@gmail.com)
- *Weibo:http://weibo.com/xzw1989
- *Createat2012-9-22上午11:25:04
- */
- publicclassNetUtil{
- /**
- *判断Network是否开启(包括移动网络和wifi)
- *
- *@return
- */
- publicstaticbooleanisNetworkEnabled(ContextmContext){
- return(isNetEnabled(mContext)||isWIFIEnabled(mContext));
- }
- /**
- *判断Network是否连接成功(包括移动网络和wifi)
- *@return
- */
- publicstaticbooleanisNetworkConnected(ContextmContext){
- return(isWifiContected(mContext)||isNetContected(mContext));
- }
- /**
- *判断移动网络是否开启
- *
- *@return
- */
- publicstaticbooleanisNetEnabled(Contextcontext){
- booleanenable=false;
- TelephonyManagertelephonyManager=(TelephonyManager)context
- .getSystemService(Context.TELEPHONY_SERVICE);
- if(telephonyManager!=null){
- if(telephonyManager.getNetworkType()!=TelephonyManager.NETWORK_TYPE_UNKNOWN){
- enable=true;
- Log.i(Thread.currentThread().getName(),"isNetEnabled");
- }
- }
- returnenable;
- }
- /**
- *判断wifi是否开启
- */
- publicstaticbooleanisWIFIEnabled(Contextcontext){
- booleanenable=false;
- WifiManagerwifiManager=(WifiManager)context
- .getSystemService(Context.WIFI_SERVICE);
- if(wifiManager.isWifiEnabled()){
- enable=true;
- Log.i(Thread.currentThread().getName(),"isWifiEnabled");
- }
- Log.i(Thread.currentThread().getName(),"isWifiDisabled");
- returnenable;
- }
- /**
- *判断移动网络是否连接成功!
- *@paramcontext
- *@return
- */
- publicstaticbooleanisNetContected(Contextcontext){
- ConnectivityManagerconnectivityManager
- =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfomobileNetworkInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
- if(mobileNetworkInfo.isConnected())
- {
- Log.i(Thread.currentThread().getName(),"isNetContected");
- returntrue;
- }
- Log.i(Thread.currentThread().getName(),"isNetDisconnected");
- returnfalse;
- }
- /**
- *判断wifi是否连接成功
- *@paramcontext
- *@return
- */
- publicstaticbooleanisWifiContected(Contextcontext){
- ConnectivityManagerconnectivityManager
- =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfowifiNetworkInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
- if(wifiNetworkInfo.isConnected())
- {
- Log.i(Thread.currentThread().getName(),"isWifiContected");
- returntrue;
- }
- Log.i(Thread.currentThread().getName(),"isWifiDisconnected");
- returnfalse;
- }
- }
更多相关文章
- Android使用Retrofit进行网络请求
- Android(安卓)热点开关状态的判断和获取热点ssid
- Android中判断网络功能是否可用
- Android的网络状态判断
- Android打开/关闭数据流量
- 重定向android log
- Android(安卓)7.0 https/tls证书配置问题
- 【android测试】值得学习的android测试知识连接
- Android(安卓)startActivityForResult的使用