附上一张效果图(网络状态为true代表联网成功,false则联网失败)
1.添加一些需要的权限
1 <uses-permission android:name="android.permission.INTERNET"/> 2 <!--允许读取网络状态--> 3 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 4 <!--允许读取wifi网络状态--> 5 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 6 7 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/> 8 9 <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
2.判断手机是否联网(这里返回的是boolean型)
//判断手机是否有网络 public static boolean isOnline() { URL url; try { url = new URL("https://www.baidu.com"); URLConnection conn = url.openConnection(); conn.setConnectTimeout(500); InputStream inputStream = conn.getInputStream(); return true; } catch (MalformedURLException e) { e.printStackTrace(); } catch (Exception a){ a.printStackTrace(); } return false; }
3.判断当前网络的类型(返回的值是int型的)
1 /* 2 * 获取当前网络的类型 3 * 0 没有网络 4 * 1 WIFI网络 5 * 2 2G网络 6 * 3 3G网络 7 * 4 4G网络 8 */ 9 public static int getAPNType(Context context){ 10 //结果返回值 11 int netType = 0; 12 //获取手机所有连接管理对象 13 ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 14 //获取NetWorkinfo对象 15 NetworkInfo info = manager.getActiveNetworkInfo(); 16 //NetworkInfo对象为空,则代表没有网络 17 if(info == null){ 18 return netType; 19 } 20 //否则NetworkInfo对象不为空,则获取该NetworkInfo的类型 21 int nType = info.getType(); 22 if(nType == ConnectivityManager.TYPE_WIFI){ 23 netType = 1; //WIFI 24 }else if(nType == ConnectivityManager.TYPE_MOBILE){ 25 int nSubType = info.getSubtype(); 26 TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 27 28 if(nSubType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming()){ 29 netType = 4; //4G网络 30 }else if(nSubType == TelephonyManager.NETWORK_TYPE_UMTS 31 || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA 32 || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0 33 && !telephonyManager.isNetworkRoaming()){ 34 35 netType = 3; //联通的3G为UMTS或HSDPA 电信的3G为EVDO 36 37 }else if(nSubType == TelephonyManager.NETWORK_TYPE_GPRS 38 || nSubType == TelephonyManager.NETWORK_TYPE_EDGE 39 || nSubType == TelephonyManager.NETWORK_TYPE_CDMA 40 && !telephonyManager.isNetworkRoaming()){ 41 42 netType = 2; //2G 43 44 }else{ 45 netType = 2; 46 } 47 } 48 return netType; 49 }
我把它们写成封装类,方便以后调用
1 public class Connections { 2 3 /* 4 * 判断网络类型 5 * 值为1 -- WIFI 6 * 值为0 -- 手机数据网络 7 * 值为-1 - 断开网络(不包含以上两者) 8 */ 9 public static int getConnectedType(Context context){ 10 if(context != null){ 11 ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 12 NetworkInfo info = manager.getActiveNetworkInfo(); 13 if(info != null && info.isAvailable()){ 14 return info.getType(); 15 } 16 } 17 return -1; 18 } 19 20 /* 21 * 判断网络状态 22 * 有网 - true 23 * 没网 - false 24 */ 25 public static boolean isConnectInternet(Context context){ 26 if(context != null){ 27 //获取手机所有连接管理对象(包括WIFI,NET等连接的管理) 28 ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 29 //获取NetworkInfo对象 30 NetworkInfo info = manager.getActiveNetworkInfo(); 31 //判断NetworkInfo对象是否为空,并且类型是否为MOBILE 32 if(info != null){ 33 return info.isAvailable(); 34 } 35 } 36 return false; 37 } 38 39 /* 40 * 判断MOBIL网络是否可用 41 */ 42 public static boolean isMobileConnected(Context context){ 43 if(context != null){ 44 //获取手机所有连接管理对象(包括WIFI,NET等连接的管理) 45 ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 46 //获取NetworkInfo对象 47 NetworkInfo info = manager.getActiveNetworkInfo(); 48 //判断NetworkInfo对象是否为空,并且类型是否为MOBILE 49 if(info != null && info.getType() == manager.TYPE_MOBILE){ 50 return info.isAvailable(); 51 } 52 } 53 return false; 54 } 55 56 /* 57 * 获取当前网络的类型 58 * 0 没有网络 59 * 1 WIFI网络 60 * 2 2G网络 61 * 3 3G网络 62 * 4 4G网络 63 */ 64 public static int getAPNType(Context context){ 65 //结果返回值 66 int netType = 0; 67 //获取手机所有连接管理对象 68 ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 69 //获取NetWorkinfo对象 70 NetworkInfo info = manager.getActiveNetworkInfo(); 71 //NetworkInfo对象为空,则代表没有网络 72 if(info == null){ 73 return netType; 74 } 75 //否则NetworkInfo对象不为空,则获取该NetworkInfo的类型 76 int nType = info.getType(); 77 if(nType == ConnectivityManager.TYPE_WIFI){ 78 netType = 1; //WIFI 79 }else if(nType == ConnectivityManager.TYPE_MOBILE){ 80 int nSubType = info.getSubtype(); 81 TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 82 83 if(nSubType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming()){ 84 netType = 4; //4G网络 85 }else if(nSubType == TelephonyManager.NETWORK_TYPE_UMTS 86 || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA 87 || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0 88 && !telephonyManager.isNetworkRoaming()){ 89 90 netType = 3; //联通的3G为UMTS或HSDPA 电信的3G为EVDO 91 92 }else if(nSubType == TelephonyManager.NETWORK_TYPE_GPRS 93 || nSubType == TelephonyManager.NETWORK_TYPE_EDGE 94 || nSubType == TelephonyManager.NETWORK_TYPE_CDMA 95 && !telephonyManager.isNetworkRoaming()){ 96 97 netType = 2; //2G 98 99 }else{ 100 netType = 2; 101 } 102 } 103 return netType; 104 } 105 106 //判断手机是否有网络 107 public static boolean isOnline() { 108 URL url; 109 try { 110 url = new URL("https://www.baidu.com"); 111 URLConnection conn = url.openConnection(); 112 conn.setConnectTimeout(500); 113 InputStream inputStream = conn.getInputStream(); 114 return true; 115 } catch (MalformedURLException e) { 116 e.printStackTrace(); 117 } catch (Exception a){ 118 a.printStackTrace(); 119 } 120 return false; 121 } 122 123 124 }
然后附上效果图的MainActivity类,布局文件就不加了
1 public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 2 private TextView tv_status,tv_type; 3 private Button btnTest; 4 private String TAG = "DEBUG"; 5 private Handler handler = new Handler(); 6 private ProgressDialog dialog; 7 8 @Override 9 protected void onCreate(Bundle savedInstanceState) { 10 super.onCreate(savedInstanceState); 11 setContentView(R.layout.activity_main); 12 initView(); 13 } 14 15 private void initView(){ 16 btnTest = (Button)findViewById(R.id.btnTest); 17 tv_type = (TextView)findViewById(R.id.net_type); 18 tv_status = (TextView)findViewById(R.id.net_status); 19 btnTest.setOnClickListener(this); 20 btnTest.setVisibility(View.GONE); 21 initNetWork(); 22 initDialog(); 23 } 24 25 26 @Override 27 public void onClick(View view) { 28 dialog.show(); 29 handler.postDelayed(new Runnable() { 30 @Override 31 public void run() { 32 dialog.dismiss(); 33 initNetWork(); 34 initDialog(); 35 boolean status = Connections.isOnline(); 36 if(status == true){ 37 Toast.makeText(MainActivity.this, "网络连接成功", Toast.LENGTH_SHORT).show(); 38 }else{ 39 Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show(); 40 } 41 } 42 },2000); //耗时2秒 43 } 44 45 /* 46 * 0 没有网络 47 * 1 WIFI网络 48 * 2 2G网络 49 * 3 3G网络 50 * 4 4G网络 51 */ 52 private void initNetType(){ 53 final int type = Connections.getAPNType(this); 54 runOnUiThread(new Runnable() { 55 @Override 56 public void run() { 57 switch (type){ 58 case 0: 59 tv_type.setText("没有网络"); 60 break; 61 case 1: 62 tv_type.setText("WIFI网络"); 63 break; 64 case 2: 65 tv_type.setText("2G网络"); 66 break; 67 case 3: 68 tv_type.setText("3G网络"); 69 break; 70 case 4: 71 tv_type.setText("4G网络"); 72 break; 73 default: 74 tv_type.setText("其他网络"); 75 break; 76 } 77 } 78 }); 79 } 80 81 private void initNetWork(){ 82 ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 83 manager.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback(){ 84 @Override 85 public void onLost(@NonNull Network network) { 86 super.onLost(network); 87 //网络不可用 88 Log.d(TAG, "网络不可用" + Connections.isOnline()); 89 runUi(Connections.isOnline()); 90 } 91 92 @Override 93 public void onAvailable(@NonNull Network network) { 94 super.onAvailable(network); 95 //网络可用 96 Log.d(TAG, "网络可用" + Connections.isOnline()); 97 runUi(Connections.isOnline()); 98 } 99 }); 100 } 101 102 private void runUi(final boolean status){ 103 runOnUiThread(new Runnable() { 104 @Override 105 public void run() { 106 tv_status.setText(String.valueOf(status)); 107 if(status == false){ 108 btnTest.setVisibility(View.VISIBLE); 109 }else{ 110 btnTest.setVisibility(View.GONE); 111 } 112 Log.d(TAG, "状态:" + status); 113 } 114 }); 115 initNetType(); 116 } 117 118 //加载Dialog 119 private void initDialog(){ 120 dialog = new ProgressDialog(this); 121 dialog.setIndeterminate(false); //循环滚动 122 dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 123 dialog.setMessage("网络重新连接中..."); 124 dialog.setCancelable(false); //false不能取消显示,true可以取消显示 125 } 126 }