Android中惯用的工具类01

Android中常用的工具类01

1、图片和视频缩略图工具类

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;

/**
 * 缩略图生成工具类
 * @author
 *
 */
public class ThumbnailGenerateUtils {
	private ThumbnailGenerateUtils(){};
	/**
     * 根据指定的图像路径和大小来获取缩略图
     * 此方法有两点好处:
     *     1. 使用较小的内存空间,第一次获取的bitmap实际上为null,只是为了读取宽度和高度,
     *        第二次读取的bitmap是根据比例压缩过的图像,第三次读取的bitmap是所要的缩略图。
     *     2. 缩略图对于原图像来讲没有拉伸,这里使用了2.2版本的新工具ThumbnailUtils,使
     *        用这个工具生成的图像不会被拉伸。
     * @param imagePath 图像的路径
     * @param width 指定输出图像的宽度
     * @param height 指定输出图像的高度
     * @return 生成的缩略图
     */
    public static Bitmap getImageThumbnail(String imagePath, int width, int height) {
            Bitmap bitmap = null;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            // 获取这个图片的宽和高,注意此处的bitmap为null
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            options.inJustDecodeBounds = false; // 设为 false
            // 计算缩放比
            int h = options.outHeight;
            int w = options.outWidth;
            int beWidth = w / width;
            int beHeight = h / height;
            int be = 1;
			if (beWidth < beHeight) {
				be = beWidth;
			} else {
				be = beHeight;
			}
            if (be <= 0) {
                    be = 1;
            }
            options.inSampleSize = be;
            // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            return bitmap;
    }

    /**
     * 获取视频的缩略图
     * 先通过ThumbnailUtils来创建一个视频的缩略图,然后再利用ThumbnailUtils来生成指定大小的缩略图。
     * 如果想要的缩略图的宽和高都小于MICRO_KIND,则类型要使用MICRO_KIND作为kind的值,这样会节省内存。
     * @param videoPath 视频的路径
     * @param width 指定输出视频缩略图的宽度
     * @param height 指定输出视频缩略图的高度度
     * @param kind 参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
     *            其中,MINI_KIND: 512 x 384,MICRO_KIND: 96 x 96
     * @return 指定大小的视频缩略图
     */
    public static Bitmap getVideoThumbnail(String videoPath, int width, int height,int kind) {
            Bitmap bitmap = null;
            // 获取视频的缩略图
            bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
            System.out.println("w"+bitmap.getWidth());
            System.out.println("h"+bitmap.getHeight());
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
            return bitmap;
    }

}

2、密度计算工具类

/**
 * 密度计算工具
 * 
 * @author zbzhangc
 * 
 */
public class DensityUtils {
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
}

3、文件夹创建,文件名替换工具类

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Environment;
/**
 * 文件名称操作工具类
 * @author zhang
 *
 */
public class FileNameOperationUtils {
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
	private FileNameOperationUtils(){};
	/**
	 * 生成文件夹
	 * @return	文件夹路径
	 */
	public static String generateFolderName(String projectName){
		String folderPath = Environment.getExternalStorageDirectory()+"/Province"+"/"+projectName
				+"/"+dateFormat.format(new Date(System.currentTimeMillis()));
		File folder = new File(folderPath);
		if(!folder.exists())//创建文件夹
			folder.mkdirs();
		return folderPath;
		
	}
	/**
	 * 获取图片文件名称
	 * @return
	 */
	public static String getPictrueFileName(){
		return System.currentTimeMillis()/1000+".jpg";
	}
	/**
	 * 获取视频文件名称
	 * @return
	 */
	public static String getVideoFileName(){
		return System.currentTimeMillis()/1000+".mp4";
	}
	/**
	 * 获取音频文件名称
	 * @return
	 */
	public static String getAudioFileName(){
		return System.currentTimeMillis()/1000+".3gp";
	}
	/**
	 * 获取图片文件的全路径名称
	 * @return
	 */
	public static String getPictureAbsoluteFileName(String projectName){
		return generateFolderName(projectName)+"/"+getPictrueFileName();
	}
	/***
	 * 获取音频文件的全路径名称
	 * @param projectName
	 * @return
	 */
	public static String getAudioAbsoluteFileName(String projectName){
		return generateFolderName(projectName)+"/"+getAudioFileName();
	}
	/**
	 * 替换文件夹名称
	 * @param fileName
	 * @param newFolderName
	 * @return
	 */
	public static boolean renameFolder(String fileName,String newFolderName){
		File file = new File(fileName);
		if(!file.isDirectory()){
			String folderPath = file.getPath().substring(0,file.getPath().lastIndexOf("\\"));//当前文件夹名称
			String oldFolderName = folderPath.substring(folderPath.lastIndexOf("\\")+1);//要替换文件夹名称
			return new File(folderPath).renameTo(new File(folderPath.replace(oldFolderName, newFolderName)));
		}else{
			System.out.println(file.getPath());
			String oldFolderName = file.getPath().substring(file.getPath().lastIndexOf("\\")+1);
			System.out.println(oldFolderName);
			return file.renameTo(new File(file.getPath().replace(oldFolderName, newFolderName)));
		}
	}
}

4、防止用户的连续点击

package com.iss.starwish.util;

import android.content.Context;
import android.widget.Toast;

/**
 * 防止按钮连续点击
 * @author zhang
 *
 */
public class Utils {
	private static long lastClickTime;
	/**
	* 防止用户在800ms里面的连续点击
	**/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
	/**
	 * 显示Toast
	 * @param context
	 * @param content
	 */
	public static void show(Context context,String content){
		Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
	}
	/**
	 * 显示Toast
	 * @param context
	 * @param content
	 */
	public static void show(Context context,int strId){
		Toast.makeText(context, strId, Toast.LENGTH_SHORT).show();
	}
}

5、汉字转换成拼音

这个和pinyin4j-2.5.0.jar一块使用(也是我在网上找的比较靠谱的转换方式)
package net.tianyouwang.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class ChineseToPinyinUtil {
	private ChineseToPinyinUtil() {
	}
	/***
	 * 汉子转换成拼音
	 * @param src
	 * @return
	 */
	public static String getPingYin(String src) {

		char[] t1 = null;

		t1 = src.toCharArray();

		String[] t2 = new String[t1.length];

		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();

		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);

		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

		t3.setVCharType(HanyuPinyinVCharType.WITH_V);

		String t4 = "";

		int t0 = t1.length;

		try {

			for (int i = 0; i < t0; i++)

			{

				// 判断是否为汉字字符

				if (java.lang.Character.toString(t1[i]).matches(
						"[\\u4E00-\\u9FA5]+"))

				{

					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);

					t4 += t2[0];

				}

				else

					t4 += java.lang.Character.toString(t1[i]);

			}

			// System.out.println(t4);

			return t4;

		}

		catch (BadHanyuPinyinOutputFormatCombination e1) {

			e1.printStackTrace();

		}

		return t4;

	}

	// 返回中文的首字母

	public static String getPinYinHeadChar(String str) {

		String convert = "";

		for (int j = 0; j < str.length(); j++) {

			char word = str.charAt(j);

			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);

			if (pinyinArray != null) {

				convert += pinyinArray[0].charAt(0);

			} else {

				convert += word;

			}

		}

		return convert;

	}

}

6、判断当前网络连接类型和网络是否可用

package net.tianyouwang.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class NetUtils {

    /***
     * 判断当前网络是否连接
     * 
     * @param con
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {

        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null)
            return false;
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if (netinfo == null) {
            return false;
        }
        if (netinfo.isConnected()) {
            return true;
        }
        return false;
    }
    
    /****
     * 获取当前的网络类型
     * @param context
     * @return
     */
    public static String getNetWorkType(Context context){
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null)
            return "";
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if(netinfo != null){
            int type = netinfo.getType();
            if(type == 0){//手机
                int subtype = netinfo.getSubtype();
                if(subtype == TelephonyManager.NETWORK_TYPE_CDMA){//电信2G
                    return "2g";
                } else if(subtype == TelephonyManager.NETWORK_TYPE_EVDO_0 || subtype == TelephonyManager.NETWORK_TYPE_EVDO_A
                        || subtype == TelephonyManager.NETWORK_TYPE_EVDO_B){//电信3G
                    return "3g";
                } else if(subtype == TelephonyManager.NETWORK_TYPE_GPRS){//联通2g
                    return "2g";
                } else if(subtype == TelephonyManager.NETWORK_TYPE_EDGE){//移动2G
                    return "2g";
                } else if(subtype == TelephonyManager.NETWORK_TYPE_HSDPA ||
                        subtype == TelephonyManager.NETWORK_TYPE_UMTS){//联通3g
                    return "3g";
                } 
            } else if(type == 1){//wifi
                return "wifi";
            }
        }
        return "3g";
    }

}