网络连接判断的工具类,判断是wifi网络, 还是蜂窝网络,或者无网络;
package example.com.untils03; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * author:Created by WangZhiQiang on 2018/1/26. */ public class NetUntils { //判断网络 public static int getNetType(Context context) { //设置一个无网络状态值 int noState = -1; //获取系统网络管理类 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //得到NetWorkInfo NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); //如果activeNetworkInfo为空,说明没网络 if (activeNetworkInfo == null) { return noState; } //否则就获取网路类型 int type = activeNetworkInfo.getType(); if (type == ConnectivityManager.TYPE_WIFI) {//网络类型是WiFi return 1; } else if (type == connectivityManager.TYPE_MOBILE) {//网络类型是手机网络 return 0; } return noState; } //请求网络文字 public static String getText(String urlString) { try { //得到网络请求的路径 URL url = new URL(urlString); //获取网络连接 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //获取响应码 int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String temp = ""; while ((temp = bufferedReader.readLine()) != null) { stringBuilder.append(temp); } String result = stringBuilder.toString(); return result; } } catch (Exception e) { e.printStackTrace(); } return ""; } //请求网络图片 public static Bitmap getBitmap(String urlBitmap) { try { //得到网络请求的路径 URL url = new URL(urlBitmap); //获取网络连接 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //获取响应码 int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { //连接到输入流 InputStream inputStream = urlConnection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (Exception e) { e.printStackTrace(); } return null; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。