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";
    }

}

Android中常用的工具类01

时间: 2024-10-04 22:25:30

Android中常用的工具类01的相关文章

Android中常用的工具类02

1.读取手机联系人信息 一般用在读取手机通讯录上传,这一块比较多. import java.util.ArrayList; import java.util.List; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.provider.ContactsContract.CommonDataKinds.Phon

java中常用的工具类(二)

下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

java中常用的工具类(三)

继续分享java中常用的一些工具类.前两篇的文章中有人评论使用Apache 的lang包和IO包,或者Google的Guava库.后续的我会加上的!谢谢支持IT江湖 一.连接数据库的综合类 Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

java中常用的工具类(一)

我们java程序员在开发项目的是常常会用到一些工具类.今天我汇总了一下java中常用的工具方法.大家可以在项目中使用.可以收藏!加入IT江湖官方群:383126909 我们一起成长 一.String工具类 Java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 5

java并发编程中常用的工具类 Executor

/***************************************************  * TODO: description .  * @author: gao_chun  * @since:  2015-4-17  * @version: 1.0.0  * @remark: 转载请注明出处  **************************************************/ java.util.concurrent.Executor 使用 Execut

Android中的管理工具类log可以这么些.....

做Android开发的一个重要的工具就是locat,这是代码调试,出错排除定位等必不可少的工具,也是习以为常的, 首先我就来先说一下log吧. 它属于android.util.log类.常用的打印日志的方法有5个如下 : Log.v(tag,message) :   //verbose模式,打印最详细的信息 Log.d(tag,message) :   //debug模式,打印调试的信息 Log.i(tag,message) :    //info Log.w(tag,message) :   

java中常用的工具类

一.String工具类 package com.itjh.javaUtil; import java.util.ArrayList; import java.util.List; /** * * String工具类. <br> * * @author 宋立君 * @date 2014年06月24日 */ public class StringUtil { private static final int INDEX_NOT_FOUND = -1; private static final St

Android开发中常用的工具类整理

来源 http://wujingchao.net/2015/03/16/android_common_utility_class.html 日志 package net.wujingchao.android.utility import android.util.Log; public final class L { private final static int LEVEL = 5; private final static String DEFAULT_TAG = "L"; pr

Android中2D绘图工具类(Canvas,Paint和Color)简介

通常的Android应用开发中都要图片,找美工设计些图片,放到项目中就可以了,不过除了使用现有的图片外,我们也可以用2D绘图,就是在View画一些图案或文字.其中通常要用到的类有Canvas(画布),Paint(画笔)及Color(用来设置画笔颜色)类,当然还可能用到其它很多类,都是根据自己项目中的需要来定的. Canvas:画布,用来直接在View上绘制诸如矩形,圆形,文字,位图等图形.官方api网址:http://developer.android.com/reference/android