Android学习之——项目中的网络连接相关以及Bitmap处理学习


一、网络连接相关
a. 检查网络是否可用
/**
 * 检查网络是否可用
 * 
 * @param context
 * @return
 */
public static boolean detect(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context
            .getApplicationContext().getSystemService(
                    Context.CONNECTIVITY_SERVICE);
    if (manager == null) {
        return false;
    }
    NetworkInfo networkinfo = manager.getActiveNetworkInfo();
 
    if (networkinfo == null || !networkinfo.isAvailable()) {
        return false;
    }
    return true;
}
b. 检查WIFI是否连接
/**
 * 检查当前WIFI是否连接,两层意思——是否连接,连接是不是WIFI
 * @param context
 * @return true表示当前网络处于连接状态,且是WIFI,否则返回false
 */
public static boolean isWifiConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()
    && ConnectivityManager.TYPE_WIFI == info.getType()) {
        return true;
    }
    return false;
}
c. 检查GPRS是否连接
/**
 * 检查当前GPRS是否连接,两层意思——是否连接,连接是不是GPRS
 * @param context
 * @return true表示当前网络处于连接状态,且是GPRS,否则返回false
 */
public static boolean isGprsConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()
    && ConnectivityManager.TYPE_MOBILE == info.getType()) {
        return true;
    }
    return false;
}
d. 检查当前是否连接
/**
 * 检查当前是否连接
 * @param context
 * @return true表示当前网络处于连接状态,否则返回false
 */
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
    .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        return true;
    }
    return false;
}


二、Bitmap 工具类相关记录

package com.example.syc_util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.PorterDuff.Mode;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class BitmapTools {

	/**
	 * 根据输入流获取位图对象
	 * 
	 * @param is
	 * @return
	 */
	public static Bitmap getBitmap(InputStream is) {
		return BitmapFactory.decodeStream(is);
	}

	/**
	 * 根据输入流和 缩小比例 获取位图对象
	 * 
	 * @param is
	 * @param scale
	 * @return
	 */
	public static Bitmap getBitmap(InputStream is, int scale) {
		Bitmap bitmap = null;
		Options opts = new Options();
		opts.inSampleSize = scale;
		bitmap = BitmapFactory.decodeStream(is, null, opts);
		return bitmap;
	}

	/**
	 * 根据指定的宽高 保持纵横比 缩小读取指定图片
	 * 
	 * @param bytes
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap getBitmap(byte[] bytes, int width, int height) {
		Bitmap bitmap = null;
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
		opts.inJustDecodeBounds = false;
		int scaleX = opts.outWidth / width;
		int scaleY = opts.outHeight / height;
		int scale = scaleX > scaleY ? scaleX : scaleY;
		opts.inSampleSize = scale;
		Log.i("info", "scale : " + scale);
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
		return bitmap;
	}

	/**
	 * 根据指定的宽高 等比例 缩小读取指定路径的图片
	 * 
	 * @param fileName
	 *            文件名
	 * @param width
	 *            宽
	 * @param height
	 *            高
	 * @return
	 */
	public static Bitmap getBitmap(String fileName, int width, int height) {
		// 绝对路径
		String abPath =fileName;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 通过这个bitmap获取图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeFile(abPath, options);
		// if (bitmap == null)
		// {
		// System.out.println("bitmap为空");
		// }
		float realWidth = options.outWidth;
		float realHeight = options.outHeight;
		if (realHeight == 0 || realWidth == 0) {
			return null;
		}
		// System.out.println("真实图片高度:" + realHeight + "宽度:" + realWidth);
		// 计算缩放比
		int scaleX = options.outWidth / width;
		int scaleY = options.outHeight / height;
		int scale = scaleX > scaleY ? scaleX : scaleY;
		options.inSampleSize = scale;
		// }
		// else if(flag==1){
		// options.outWidth=width;
		// options.outHeight=height;
		// }
		options.inJustDecodeBounds = false;
		// 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。
		bitmap = BitmapFactory.decodeFile(abPath, options);
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		System.out.println("缩略图高度:" + h + "宽度:" + w);
		return bitmap;
	}
	/**
	 * 根据指定的宽高 缩小读取指定路径的图片
	 * 
	 * @param fileName
	 *            文件名
	 * @param width
	 *            宽
	 * @param height
	 *            高
	 * @return
	 */
	public static Bitmap getBitmapDeng(String fileName, int width, int height) {
		// 绝对路径
		String abPath =  fileName;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		// 通过这个bitmap获取图片的宽和高
		Bitmap bitmap = BitmapFactory.decodeFile(abPath, options);
		// if (bitmap == null)
		// {
		// System.out.println("bitmap为空");
		// }
		float realWidth = options.outWidth;
		float realHeight = options.outHeight;
		if (realHeight == 0 || realWidth == 0) {
			return null;
		}
		// System.out.println("真实图片高度:" + realHeight + "宽度:" + realWidth);
		// 计算缩放比
		float scaleX = width/realWidth ;
		float scaleY =  height/realHeight ;
		int scale = (int) (scaleX > scaleY ? scaleX : scaleY);
		options.inSampleSize = scale;
		Matrix matrix = new Matrix();
		// float scaleWidth = ((float) w / width);
		// float scaleHeight = ((float) h / height);
		matrix.postScale(scaleX, scaleY);
		// }
		// else if(flag==1){
		// options.outWidth=width;
		// options.outHeight=height;
		// }
		options.inJustDecodeBounds = false;
		// 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。
		bitmap = BitmapFactory.decodeFile(abPath, options);
		bitmap=Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
//		int w = bitmap.getWidth();
//		int h = bitmap.getHeight();
//		System.out.println("缩略图高度:" + h + "宽度:" + w);
		return bitmap;
	}


	/**
	 * 根据指定的高度比例,拉伸读取指定图片
	 * 
	 * @param bytes
	 * @param width
	 * @param height
	 * @return
	 */
	public static Bitmap getBitmap(byte[] bytes, int height) {
		Bitmap bitmap = null;
		Options opts = new Options();
		opts.inJustDecodeBounds = true;
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
		opts.inJustDecodeBounds = false;
		// int scaleX = opts.outWidth / width;
		// int scaleY = opts.outHeight / height;
		// int scale = scaleX > scaleY ? scaleX : scaleY;
		opts.outHeight = opts.outHeight * height;

		// Log.i("info", "scale : " + scale);
		bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
		return bitmap;
	}

	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/**
	 * 根据路径 从文件中读取位图对象
	 * 
	 * @param path
	 * @return
	 */
	public static Bitmap getbiBitmap(String path) {
		Bitmap bitmap = null;
		bitmap = BitmapFactory.decodeFile(path);
		return bitmap;
	}

	/**
	 * 保存位图对象到指定位置
	 * 
	 * @param path
	 * @param bitmap
	 * @throws IOException
	 */
	public static void saveBitmap(String path, Bitmap bitmap)
			throws IOException {
		if (path != null && bitmap != null) {
			File file = new File(path);
			if (!file.exists()) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}

			OutputStream stream = new FileOutputStream(file);
			String name = file.getName();
			String end = name.substring(name.lastIndexOf(".") + 1);
			if ("png".equals(end)) {
				bitmap.compress(CompressFormat.PNG, 100, stream);
			} else {
				bitmap.compress(CompressFormat.JPEG, 100, stream);
			}
		}
	}

	/**
	 * @param 将图片内容解析成字节数组
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	/**
	 * @param 将字节数组转换为ImageView可调用的Bitmap对象
	 * @param bytes
	 * @param opts
	 * @return Bitmap
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 * @param 图片缩放
	 * @param bitmap
	 *            对象
	 * @param w
	 *            要缩放的宽度
	 * @param h
	 *            要缩放的高度
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newBmp;
	}

	/**
	 * @param 等比图片缩放
	 * @param bitmap
	 *            对象
	 * @param w
	 *            要缩放的宽度
	 * @param h
	 *            要缩放的高度
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmapDeng(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		float scale = scaleWidth > scaleHeight ? scaleWidth : scaleHeight;
		matrix.postScale(scale, scale);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		bitmap.recycle();
		return newBmp;
	}

	/**
	 * @param 等比图片缩放
	 * @param bitmap
	 *            对象
	 * @param scale
	 *            等比缩放的比例
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, float scale) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		// float scaleWidth = ((float) w / width);
		// float scaleHeight = ((float) h / height);
		matrix.postScale(scale, scale);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newBmp;
	}

	/**
	 * // * 把Bitmap转Byte // * @Author HEH // * @EditTime 2010-07-19 上午11:45:56
	 * //
	 */
	// public static byte[] Bitmap2Bytes(Bitmap bm){
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
	// return baos.toByteArray();
	// }
	/**
	 * 把字节数组保存为一个文件
	 * 
	 * @Author HEH
	 * @EditTime 2010-07-19 上午11:45:56
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}
	/**
	 * 获取圆角位图的方法
	 * 
	 * @param bitmap
	 *            需要转化成圆角的位图
	 * @param pixels
	 *            圆角的度数,数值越大,圆角越大
	 * @return 处理后的圆角位图
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
//		final int color = 0x00FFFFFF;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
//		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}
	/**
	 * 得到图片路径
	 * 
	 * @param fileItem
	 * @return 图片路径
	 */
	public static String getPicture(int fileItem, Context context) {
		String status = Environment.getExternalStorageState();
		if (!status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
			Toast.makeText(context, "请插入SD卡", Toast.LENGTH_LONG).show();
			return null;
		}
//		String date = MyDate.getMyNowDate("yyyy_MM_dd_");
//		
//		BMapApiDemoApp app=(BMapApiDemoApp) context.getApplicationContext();
//		// 文件名
//		String fileName = date + fileItem+"_"+app.getName() + ".png";
//		File f = new File(YinShiToadyAct.PHOTO_DIR, fileName);
		//boolean exist = f.exists();
//		if (!exist) {
//			return null;
//		}
		// Log.i("exist", exist+"");
		//return fileName;
		return null;
	}

}


Mr.傅:学习笔记
欢迎转载,转载注明出处,谢谢

Android学习之——项目中的网络连接相关以及Bitmap处理学习,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。