技术总结--android篇(四)--工具类总结

StringUtil(视个人需要进行添加)

public class StringUtil {
	
	public static boolean isMail(String string) {
		if (null != string) {
			if (string.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$")) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 判断手机号码的正确性
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNumber(String mobiles) {
		
		if (null != mobiles) {
			Pattern p = Pattern
					.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
			Matcher m = p.matcher(mobiles);
			return m.matches();
		}else {
			return false;
		}
	}

	/**
	 * 是否为 null 或者为空字符串
	 * @param string
	 * @return false if null || ""
	 */
	public static boolean isNotNull(String string) {
		
		if (string == null || "".equals(string)) {
			return false;
		}else {
			return true;
		}
	}
	
	/**
	 * 判断字符串是否是整数
	 */
	public static boolean isInteger(String value) {
		try {
			Integer.parseInt(value);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	
	/**
	 * 字符串长度补齐,方便打印时对齐,美化打印页面,不过中文计算好像有点问题
	 * 
	 * @param strs
	 *            源字符
	 * @param len
	 *            指定字符长度
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static String Fix_String_Lenth(int type ,String strs, int len) {
		String strtemp = strs;
		int len1 = strs.length();
		switch (type) {
		case 0:
			while (strtemp.length() < len*"我".length()) {
				strtemp += " ";}
			break;
			case 1:
				while (strtemp.length() < len) {
					strtemp += " ";}
				break;
		default:
			
			break;
		}		
		return strtemp;
	}
	
}

ImageUtil

public class ImageUtil
{
	public static byte[] getimage(String path) throws Exception
	{
		URL url = new URL(path);// 设置URL
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 打开链接
		conn.setRequestMethod("GET");// 设置链接方式
		conn.setConnectTimeout(5 * 1000);// 设置链接超时
		InputStream inStream = conn.getInputStream();// 得到输入泿

		byte[] data = readinputStream(inStream);
		return data;
	}

	public static byte[] readinputStream(InputStream inputStream)
	{
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int lns = 0;
		try {
			while ((lns = inputStream.read(buffer)) != -1)
			{
				outputStream.write(buffer, 0, lns);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outputStream.toByteArray();
	}

	public static Bitmap getBitmapFromBase64String(String imageString)
	{
		// 对字节数组字符串进行Base64解码并生成图燿
		if (imageString == null) // 图像数据为空
			return null;
		byte[] data = Base64.decode(imageString, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(data, 0, data.length);
	}
	

	public static String getBitmapString(String image)
	{
		Bitmap bitmap = BitmapFactory.decodeFile(image);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		byte[] data = baos.toByteArray();

		return Base64.encodeToString(data, Base64.DEFAULT);// 返回Base64编码过的字节数组字符
	}
	

	public static String getBase64StringFromFile(String imageFile)
	{
		// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try
		{
			in = new FileInputStream(imageFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		return Base64.encodeToString(data, Base64.DEFAULT);// 返回Base64编码过的字节数组字符
	}
	
	
	/**
	 * drawable -> Bitmap
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {  
        
        Bitmap bitmap = Bitmap  
                        .createBitmap(  
                                        drawable.getIntrinsicWidth(),  
                                        drawable.getIntrinsicHeight(),  
                                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  
                                                        : Bitmap.Config.RGB_565);  
        Canvas canvas = new Canvas(bitmap);  
        //canvas.setBitmap(bitmap);  
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
        drawable.draw(canvas);  
        return bitmap;  
	}
	
	/**
	 * resource - > Bitmap
	 * @param context
	 * @param resId
	 * @return
	 */
	public static Bitmap resourceToBitmap(Context context ,int resId){
		Resources res = context.getResources();
		Bitmap bitmap = BitmapFactory.decodeResource(res, resId);
		return bitmap;  
	}
	
	
	/**
	 * Bitmap   - > Bytes
	 * @param bm
	 * @return
	 */
	public static byte[] Bitmap2Bytes(Bitmap bm){  
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();    
	    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    
	    return baos.toByteArray();  
	}
	
	/**
	 * Bytes  - > Bitmap
	 * @param b
	 * @return
	 */
	public static Bitmap Bytes2Bitmap(byte[] b){  
        if(b.length!=0){  
            return BitmapFactory.decodeByteArray(b, 0, b.length);  
        }  
        else {  
            return null;  
        }  
  }  
	/**
	 * bitmap -> Base64
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {  
		  
	    String result = null;  
	    ByteArrayOutputStream baos = null;  
	    try {  
	        if (bitmap != null) {  
	            baos = new ByteArrayOutputStream();  
	            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);  
	  
	            baos.flush();  
	            baos.close();  
	  
	            byte[] bitmapBytes = baos.toByteArray();  
	            result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);  
	        }  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        try {  
	            if (baos != null) {  
	                baos.flush();  
	                baos.close();  
	            }  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }  
	    }  
	    return result;  
	}
	
	//获取图片
	public static Bitmap getimage(ContentResolver cr, Uri uri, int screeWidth,int screeHeight) {
		try {
			Bitmap bitmap = null;
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			// options.inJustDecodeBounds=true,图片不加载到内存中
			newOpts.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(cr.openInputStream(uri), null, newOpts);

			newOpts.inJustDecodeBounds = false;
			int imgWidth = newOpts.outWidth;
			int imgHeight = newOpts.outHeight;
			// 缩放比,1表示不缩放
			int scale = 1;

			if (imgWidth > imgHeight && imgWidth > screeWidth) {
				scale = (int) (imgWidth / screeWidth);
			} else if (imgHeight > imgWidth && imgHeight > screeHeight) {
				scale = (int) (imgHeight / screeHeight);
			}
			newOpts.inSampleSize = scale;// 设置缩放比例
			bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null,newOpts);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
}

DateUtil

public class DateUtil {
	public final static String yyyy = "yyyy";
	public final static String MM_dd = "MM-dd";
	public final static String dd = "dd";
	public final static String yyyy_MM_dd = "yyyy-MM-dd";
	public final static String yyyy_MM_dd_HH_mm = "yyyy-MM-dd HH:mm";
	public final static String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
	public final static String yyyy_MM_dd_HH_mm_ss_SSS = "yyyy-MM-dd HH:mm:ss SSS";
	public final static String MM_dd_HH_mm_ss = "MM-dd  HH:mm:ss";
	public final static String yyyy_MM_dd_HH_mm_local = "yyyy年MM月dd日 HH:mm";

	/**
	 * 返回当天日期的字符串,可以自己定格式,格式如上
	 * @param pattern
	 * @return
	 */
	public static String now(String pattern) {
		SimpleDateFormat df = new SimpleDateFormat(pattern);
		return df.format(Calendar.getInstance().getTime());
	}

	public static String now_yyyy() {
		return now(yyyy);
	}

	public static String now_MM_dd() {
		return now(MM_dd);
	}

	public static String now_dd() {
		return now(dd);
	}

	public static String now_yyyy_MM_dd() {
		return now(yyyy_MM_dd);
	}

	public static String now_yyyy_MM_dd_HH_mm_ss() {
		return now(yyyy_MM_dd_HH_mm_ss);
	}

	public static String now_yyyy_MM_dd_HH_mm_ss_SSS() {
		return now(yyyy_MM_dd_HH_mm_ss_SSS);
	}

	public static String now_MM_dd_HH_mm_ss() {
		return now(MM_dd_HH_mm_ss);
	}

	/**
	 * 获得年龄
	 * @param birth
	 * @return
	 */
	public static String getAge(String birth) { // 传进来的格式一定要对应1991-05-25
		if ("".equals(birth))
			return "";

		int nowAge = 0;
		Date date = strToDateCN_yyyy_MM_dd(birth);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int birth_year = calendar.get(Calendar.YEAR);
		int birth_month = calendar.get(Calendar.MONTH);
		int birth_day = calendar.get(Calendar.DAY_OF_MONTH);
		calendar.setTime(new Date());
		int now_year = calendar.get(Calendar.YEAR);
		int now_month = calendar.get(Calendar.MONTH);
		int now_day = calendar.get(Calendar.DAY_OF_MONTH);
		
		nowAge = now_year - birth_year;
		if (now_month < birth_month) {
			nowAge--;
		} else if (now_month == birth_month && now_day < birth_day) {
			nowAge--;
		}
		if (nowAge < 0)
			nowAge = 0;
		return "" + nowAge;
	}

	public static String getStauts(String stime,String rtime){
		if(stime == null || rtime == null)
			return "";
		String status = "";
		try {
			Date sDate = strToDateLoc_yyyy_MM_dd_HH_mm(stime);
			Date rDate = strToDateLoc_yyyy_MM_dd_HH_mm(rtime);
			Date nDate = new Date();
			if(nDate.getTime() < sDate.getTime())
				status = "准备中";
			else if(nDate.getTime() > rDate.getTime()){
				status = "已结束";
			}
			else
				status = "进行中";
		} catch (Exception e) {
			e.printStackTrace();
			status = "";
		}
		return status;
	}
	
	
	/**
	 * 聊天显示
	 * @param timeString
	 * @return 三小时前、昨天等
	 */
	private static String getRecentTime(String timeString,Date date) { 
		if(timeString == null || "".equals(timeString))
			return "";
		StringBuilder cn_string = new StringBuilder();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DAY_OF_YEAR);         //月份中的日
		int week = calendar.get(Calendar.WEEK_OF_YEAR);          //年中周
		int hour = calendar.get(Calendar.HOUR_OF_DAY);           //时间
		
		int month = calendar.get(Calendar.MONTH)+1;         //月份.显示用
		int day_of_week = calendar.get(Calendar.DAY_OF_WEEK)-1;   //周中的日.显示用
		if(day_of_week == 0) day_of_week = 7;
		int minute = calendar.get(Calendar.MINUTE);             //分钟.显示用
		
		Calendar nowCalendar = Calendar.getInstance();
		nowCalendar.setTime(new Date());
		int now_day = nowCalendar.get(Calendar.DAY_OF_YEAR);
		int now_week = nowCalendar.get(Calendar.WEEK_OF_YEAR);
		int now_hour = nowCalendar.get(Calendar.HOUR_OF_DAY);
		//时间字符串
		StringBuilder hoursString = new StringBuilder(""+hour);
		StringBuilder minutesString = new StringBuilder(""+minute);
		
		if(hour<10)
			hoursString.insert(0, "0");
		if(minute<10)
			minutesString.insert(0, "0");
		
		if(day == now_day && hour == now_hour){
			cn_string.append("刚刚");
		}
		else if((now_day - day >=0) &&(now_day - day < 1) && (now_hour - hour < 24) && (now_hour - hour >0)){
			cn_string.append(now_hour-hour).append("小时前");
		}
		else if(now_day == day){
			cn_string.append("今天").append(hoursString).append(":").append(minutesString);
		}
		else if(now_day - day == 1)
			cn_string.append("昨天").append(hoursString).append(":").append(minutesString);
		else if(now_day - day == 2)
			cn_string.append("前天").append(hoursString).append(":").append(minutesString);
		else if(day - now_day == 1)
			cn_string.append("明天").append(hoursString).append(":").append(minutesString);
		else if(day - now_day == 2)
			cn_string.append("后天").append(hoursString).append(":").append(minutesString);
		else if((week == now_week && day>now_day ) || (week - now_week == 1 && day_of_week == 7))
			cn_string.append("周").append(numToUpper(day_of_week)).append(" ").append(hoursString).append(":").append(minutesString);
		else if(week - now_week ==1)
			cn_string.append("下周").append(numToUpper(day_of_week)).append(" ").append(hoursString).append(":").append(minutesString);
		else{  //直接显示
			StringBuilder monthString = new StringBuilder(""+month);
			int _day = calendar.get(Calendar.DAY_OF_MONTH);         //月份中的日
			StringBuilder dayString = new StringBuilder(""+_day);
			if(month <10)
				monthString.insert(0, "0");
			if(_day<10)
				dayString.insert(0, "0");
			cn_string.append(monthString).append("月").append(dayString).append("日").append(hoursString).append(":").append(minutesString);
		}
		return cn_string.toString();
	}
	
	/**
	 * 02-01 12:11:56
	 * @param timeString
	 * @return
	 */
	public static String getRecentTimeMM_dd_ss(String timeString){ 
		Date date = strToDateMM_dd_ss(timeString);
		return getRecentTime(timeString, date);
	}
	
	/**
	 * 2012年01月03日 12:55
	 * @param timeString
	 * @return
	 */
	public static String getRecentTimeyyyy_MM_dd(String timeString){ 
		Date date = strToDateLoc_yyyy_MM_dd_HH_mm(timeString);
		return getRecentTime(timeString, date);
	}
	
	/**
	 * 2012-01-03 12:55:12
	 * @param timeString
	 * @return
	 */
	public static String getRecentTimeCN_yyyy_MM_dd_HH_mm_ss(String timeString) {
		Date date = strToDateCN_yyyy_MM_dd_HH_mm_ss(timeString);
		return getRecentTime(timeString, date);
	}
	
	
	
	
	/**
	 * 是否超过三天,判断是否能上传图片
	 * @param runtime
	 * @return
	 */
	public static boolean isOver3Day(String runtime){
		boolean is = false;
		Date runDate =  strToDateLoc_yyyy_MM_dd_HH_mm(runtime);
		Date now = new Date();
		if((now.getTime() - runDate.getTime()) > (3*24*60*60*1000)){
			is = true;
		}
		return is;
	}
	
	public static String getHi(){
		int nowHour = new Date().getHours();
		if(nowHour>=0 && nowHour <6){
			return "凌晨好!";
		}
		else if(nowHour>=6 && nowHour<12){
			return "上午好!";
		}
		else if(nowHour>=12 && nowHour<18){
			return "下午好!";
		}
		else{
			return "晚上好!";
		}
	}
	
	public static final String[] zodiacArr = { "猴", "鸡", "狗", "猪", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊" };   
	  
	public static final String[] constellationArr = { "水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",   
	        "天蝎座", "射手座", "魔羯座" };   
	  
	public static final int[] constellationEdgeDay = { 20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22 };   
	  
	/**  
	 * 根据日期获取生肖  
	 * @return  
	 */  
	public static String date2Zodica(String birth) {   
		if ("".equals(birth))
			return "";
	    return zodiacArr[Integer.valueOf(birth.split("-")[0]) % 12];   
	}   
	  
	/**  
	 * 根据日期获取星座  
	 * @param time  
	 * @return  
	 */  
	public static String date2Constellation(String birth) {  // 传进来的格式一定要对应1991-05-25 
		Date date = strToDateCN_yyyy_MM_dd(birth);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
	    
	    if (day < constellationEdgeDay[month]) {   
	        month = month - 1;   
	    }   
	    if (month >= 0) {   
	        return constellationArr[month];   
	    }   
	    //default to return 魔羯   
	    return constellationArr[11];   
	} 
	
	
	
	
	/**
	 * 
	 * @param dateString
	 *            yyyy年MM月dd日 HH:mm
	 * @return like: 明天 15:00
	 */
	public static String ch_time(String dateString) {
//		System.out.println("pppppt-->"+dateString);
		String cn_string = null;
		Date date = DateUtil.strToDate(dateString);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		String hString,mString;
		if (hour < 10) {
			hString = "0" + hour;
		}else {
			hString = ""+hour;
		}
		if (minute < 10) {
			mString = "0"+minute;
		}else {
			mString = ""+minute;
		}
		String time = hString+":"+mString;
		hString = null;
		mString = null;
		//去掉日以下的时间
		calendar.clear(Calendar.HOUR_OF_DAY);
		calendar.clear(Calendar.HOUR);
		calendar.clear(Calendar.MINUTE);
		calendar.clear(Calendar.SECOND);
		calendar.clear(Calendar.MILLISECOND);
		
		Calendar nowCalendar = Calendar.getInstance();
		nowCalendar.clear(Calendar.HOUR_OF_DAY);
		nowCalendar.clear(Calendar.HOUR);
		nowCalendar.clear(Calendar.MINUTE);
		nowCalendar.clear(Calendar.SECOND);
		nowCalendar.clear(Calendar.MILLISECOND);
		
		long flag = (calendar.getTimeInMillis() - nowCalendar.getTimeInMillis()
				) / (1000 * 60 * 60 * 24);
//		System.out.println("ppssss->" + flag);
		if (flag == 0) {
			cn_string = "今天 " + time;
		} else if (flag == 1) {
			cn_string = "明天 " + time;
		} else if (flag == 2) {
			cn_string = "后天 " + time;
		} else if (flag <= getDatePlus() + 7 && flag > 0) {
			if (!getNextWeekDate(calendar).equals("")) {
				cn_string = getNextWeekDate(calendar) + time;
			} else {
				cn_string = dateString;
			}
		} else {
			cn_string = dateString;
		}
		time = null;
		return cn_string;
	}

	/**
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String dateToStr(Date date, String pattern) {
		if(date == null)
			return "";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	/**
	 * 将日期时间型转成字符串 如:" 2002-07-01 11:40:02"
	 * 
	 * @param inDate
	 *            日期时间 " 2002-07-01 11:40:02"
	 * @return String 转换后日期时间字符串
	 */
	public static String dateToStr_yyyy_MM_dd_HH_mm_ss(Date date) {
		return dateToStr(date, yyyy_MM_dd_HH_mm_ss);
	}

	/**
	 * 将日期时间型转成字符串 如:" 2002-07-01 11:40:02"
	 * 
	 * @param inDate
	 *            日期时间 " 2002-07-01 11:40:02"
	 * @return String 转换后日期时间字符串
	 */
	public static String dateToStr_yyyy_MM_dd_HH_mm(Date date) {
		return dateToStr(date, yyyy_MM_dd_HH_mm);
	}

	/**
	 * yyyy年MM月dd日 HH:mm
	 * 
	 * @param date
	 * @return
	 */
	public static String dateToStrLocal(Date date) {
		return dateToStr(date, yyyy_MM_dd_HH_mm_local);
	}

	/**
	 * 将日期时间型转成字符串 如:" 2002-07-01 11:40:02"
	 * 
	 * @param inDate
	 *            日期时间 " 2002-07-01 11:40:02"
	 * @return String 转换后日期时间字符串
	 */
	public static String dateToStr_MM_dd_HH_mm_ss(Date date) {
		return dateToStr(date, MM_dd_HH_mm_ss);
	}

	/**
	 * 将日期型转成字符串 如:"2002-07-01"
	 * 
	 * @param inDate
	 *            日期 "2002-07-01"
	 * @return String 转换后日期字符串
	 */
	public static String dateToStr_yyyy_MM_dd(Date date) {
		return dateToStr(date, yyyy_MM_dd);
	}

	/**
	 * 将字符串型(英文格式)转成日期型 如: "Tue Dec 26 14:45:20 CST 2000"
	 * 
	 * @param DateFormatStr
	 *            字符串 "Tue Dec 26 14:45:20 CST 2000"
	 * @return Date 日期
	 */
	public static Date strToDateEN(String shorDateStr) {
		Date date = null;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(
					"EEE MMM dd hh:mm:ss 'CST' yyyy", java.util.Locale.US);
			return sdf.parse(shorDateStr);
		} catch (Exception e) {
			return new Date();
		}
	}

	/**
	 * 将字符串型(中文格式)转成日期型 如:"2002-07-01 22:09:55"
	 * 
	 * @param datestr
	 *            字符串 "2002-07-01 22:09:55"
	 * @return Date 日期
	 */
	public static Date strToDateCN_yyyy_MM_dd_HH_mm_ss(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}
	
	/**
	 * 将字符串型(中文格式)转成日期型 如:"2002-07-01 22:09"
	 * 
	 * @param datestr
	 *            字符串 "2002-07-01 22:09"
	 * @return Date 日期
	 */
	public static Date strToDateCN_yyyy_MM_dd_HH_mm(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat(yyyy_MM_dd_HH_mm);
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}
	

	/**yyyy_MM_dd_HH_mm
	 * @param datestr
	 * @return
	 */
	public static Date strToDateLoc_yyyy_MM_dd_HH_mm(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat(yyyy_MM_dd_HH_mm_local);
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}
	
	

	/**MM-dd  HH:mm
	 * @param datestr
	 * @return
	 */
	public static Date strToDateMM_dd_ss(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat(MM_dd_HH_mm_ss);
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}

	/**
	 * 
	 * @param datestr
	 * @return
	 */
	public static Date strToDateCN_yyyy_MM_dd(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}

	/**
	 * 
	 * @param datestr
	 *            yyyy年MM月dd日 HH:mm
	 * @return
	 */
	public static Date strToDate(String datestr) {
		Date date = null;
		try {
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
			date = fmt.parse(datestr);
		} catch (Exception e) {
			return date;
		}
		return date;
	}

	/**
	 * 转换util.date-->sql.date
	 * 
	 * @param inDate
	 * @return
	 */
	public static java.sql.Date UtilDateToSqlDate(Date inDate) {
		return new java.sql.Date(getDateTime(inDate));
	}

	private static long getDateTime(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DATE);
		cal.set(year, month, day, 0, 0, 0);
		long result = cal.getTimeInMillis();
		result = result / 1000 * 1000;
		return result;
	}

	/**
	 * 遍历刚从数据库里查出来的Map,将里面Timestamp格式化成指定的pattern
	 * 
	 * @param target
	 *            目标map,就是一般是刚从数据库里查出来的
	 * @param pattern
	 *            格式化规则,从自身取
	 */
	@Deprecated
	public static void formatMapDate(Map target, String pattern) {
		for (Object item : target.entrySet()) {
			Map.Entry entry = (Map.Entry) item;
			if (entry.getValue() instanceof Timestamp) {
				SimpleDateFormat sdf = new SimpleDateFormat(pattern);
				entry.setValue(sdf.format((Timestamp) entry.getValue()));
			}
		}
	}

	/**
	 * 日期转化为大小写 chenjiandong 20090609 add
	 * 
	 * @param date
	 * @param type
	 *            1;2两种样式1为简体中文,2为繁体中文
	 * @return
	 */
	public static String dataToUpper(Date date, int type) {
		Calendar ca = Calendar.getInstance();
		ca.setTime(date);
		int year = ca.get(Calendar.YEAR);
		int month = ca.get(Calendar.MONTH) + 1;
		int day = ca.get(Calendar.DAY_OF_MONTH);
		return numToUpper(year, type) + "年" + monthToUppder(month, type) + "月"
				+ dayToUppder(day, type) + "日";
	}

	/**
	 * 将数字转化为大写
	 * 
	 * @param num
	 * @param type
	 * @return
	 */
	public static String numToUpper(int num, int type) {// type为样式1;2
		String u1[] = { "〇", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		String u2[] = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
		char[] str = String.valueOf(num).toCharArray();
		String rstr = "";
		if (type == 1) {
			for (int i = 0; i < str.length; i++) {
				rstr = rstr + u1[Integer.parseInt(str[i] + "")];
			}
		} else if (type == 2) {
			for (int i = 0; i < str.length; i++) {
				rstr = rstr + u2[Integer.parseInt(str[i] + "")];
			}
		}
		return rstr;
	}
	
	/**
	 * 将数字转化为大写
	 * 
	 * @param num
	 * @return
	 */
	public static String numToUpper(int num) {
		String u1[] = { "〇", "一", "二", "三", "四", "五", "六", "日"};
		char[] str = String.valueOf(num).toCharArray();
		String rstr = "";
		for (int i = 0; i < str.length; i++) {
			rstr = rstr + u1[Integer.parseInt(str[i] + "")];
		}
		return rstr;
	}

	/**
	 * 月转化为大写
	 * 
	 * @param month
	 * @param type
	 * @return
	 */
	public static String monthToUppder(int month, int type) {
		if (month < 10) {
			return numToUpper(month, type);
		} else if (month == 10) {
			return "十";
		} else {
			return "十" + numToUpper((month - 10), type);
		}
	}

	/**
	 * 日转化为大写
	 * 
	 * @param day
	 * @param type
	 * @return
	 */
	public static String dayToUppder(int day, int type) {
		if (day < 20) {
			return monthToUppder(day, type);
		} else {
			char[] str = String.valueOf(day).toCharArray();
			if (str[1] == '0') {
				return numToUpper(Integer.parseInt(str[0] + ""), type) + "十";
			} else {
				return numToUpper(Integer.parseInt(str[0] + ""), type) + "十"
						+ numToUpper(Integer.parseInt(str[1] + ""), type);
			}
		}
	}

	/**
	 * 获得当前日期与本周日相差的天数(视星期日为一周最后一天)
	 * 
	 * @return
	 */
	public static int getDatePlus() {
		Calendar cd = Calendar.getInstance();
		// 获得今天是一周的第几天,星期日是第一天,星期一是第二天......
		int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
		if (dayOfWeek == 1) {
			return 0;
		} else {
			return 8 - dayOfWeek;
		}
	}

	/**
	 * 
	 * @param calendar
	 * @return
	 */
	public static String getNextWeekDate(Calendar calendar) {
		String date = "";
		switch (calendar.get(Calendar.DAY_OF_WEEK)) {
		case 1:
			date = "下周日 ";
			break;
		case 2:
			date = "下周一 ";
			break;
		case 3:
			date = "下周二 ";
			break;
		case 4:
			date = "下周三 ";
			break;
		case 5:
			date = "下周四 ";
			break;
		case 6:
			date = "下周五 ";
			break;
		case 7:
			date = "下周六 ";
			break;
		default:
			break;
		}
		return date;
	}
	
	public static boolean isToday(String datesString){
		boolean isToday = false;
		Date date = strToDateCN_yyyy_MM_dd_HH_mm(datesString);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int day = calendar.get(Calendar.DAY_OF_YEAR);
		Calendar nowCalendar = Calendar.getInstance();
		int nowDay = nowCalendar.get(Calendar.DAY_OF_YEAR);
		if (nowDay == day) {
			isToday = true;
		}
		return isToday;
	}
}

FileUtil

public class FileUtil {
	public final static int IMG = 0;
	public final static int SOUND = 1;
	public final static int APK = 2;
	public final static int PPT = 3;
	public final static int XLS = 4;
	public final static int DOC = 5;
	public final static int PDF = 6;
	public final static int CHM = 7;
	public final static int TXT = 8;
	public final static int MOVIE = 9;
	
	
	
	
	public static String getBase64StringFromFile(String imageFile)
	{
		// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try
		{
			in = new FileInputStream(imageFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		return Base64.encodeToString(data, Base64.DEFAULT);// 返回Base64编码过的字节数组字符
	}
	
	/**
	 * @param fileString base64
	 * @param filePath  保存路径,包括名字
	 * @return
	 */
	public static boolean saveFileByBase64(String fileString, String filePath) {
		// 对字节数组字符串进行Base64解码并生成图燿
		if (fileString == null) // 图像数据为空
			return false;
		byte[] data = Base64.decode(fileString, Base64.DEFAULT);
        saveFileByBytes(data, filePath);
        return true;
    }
	
	/**
	 * @param bitmap bitmap
	 * @param filePath  保存路径,包括名字
	 * @return
	 */
	public static boolean saveFileByBitmap(Bitmap bitmap, String filePath) {
		// 对字节数组字符串进行Base64解码并生成图燿
		if (bitmap == null) // 图像数据为空
			return false;
		byte[] data = ImageUtil.Bitmap2Bytes(bitmap);
        saveFileByBytes(data, filePath);
        return true;
    }
	
	
	/**
	 * @param fileString bytes[]
	 * @param filePath  保存路径,包括名字
	 * @return
	 */
	public static boolean saveFileByBytes(byte[] data,String filePath) {
		// 对字节数组字符串进行Base64解码并生成图燿
        BufferedOutputStream stream = null;
        File file = null;
        try {
        	 file = new File(filePath);
             if (!file.exists()) {
 				File file2 = new File(filePath.substring(0, filePath.lastIndexOf("/")+1));
 				file2.mkdirs();
 			}
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(data);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return true;
    }
	
	/**
	 * imputStream 返回out
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	public static boolean saveFileByInputStream(InputStream inputStream,
			String filePath) {
		File file = null;
		file = new File(filePath);
		if (!file.exists()) {
			File file2 = new File(filePath.substring(0,
					filePath.lastIndexOf("/") + 1));
			file2.mkdirs();
		}
		FileOutputStream outputStream = null;
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		
		try {
			bis = new BufferedInputStream(inputStream);
			outputStream = new FileOutputStream(file);
			bos = new BufferedOutputStream(outputStream);
			int byte_ =0 ;
			while ((byte_ = bis.read()) != -1)
				bos.write(byte_);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally{
			try {
				bos.flush();
				bos.close();
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
	
	
	/**
	 * 根据url得到名称
	 * @param url
	 * @return
	 */
	public static String getFileName(String url) {
		String fileName = "";
		if (url != null) {
			fileName = url.substring(url.lastIndexOf("/") + 1);
		}
		return fileName;
	}
	
	public static boolean renameFile(String path,String oldName,String newName){
		try {
			File file = null;
			file = new File(path + "/" + oldName);
			if (file.exists()) {
				file.renameTo(new File(path + "/" + newName));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 辅助方法,删除文件
	 * @param path
	 * @param context
	 * @param imageName
	 */
	private void delFile(String path, Context context,
			String imageName) {
		File file = null;
		String real_path = "";
		try {
			if (hasSDCard()) {
				real_path = (path != null && path.startsWith("/") ? path : "/"
						+ path);
			} else {
				real_path = getPackagePath(context)
						+ (path != null && path.startsWith("/") ? path : "/"
								+ path);
			}
			file = new File(real_path, imageName);
			if (file != null)
				file.delete();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 根据路径和名称都可以
	 * @param filePath
	 * @return
	 */
	public static int getType(String filePath){  
		if (filePath == null) {
			return -1;
		}
		String end ;
		if(filePath.contains("/")){
			File file = new File(filePath);
			if (!file.exists())
				return -1;
			/* 取得扩展名 */
				end = file
					.getName()
					.substring(file.getName().lastIndexOf(".") + 1,
							file.getName().length()).toLowerCase();
		}else{
			end = filePath.substring(filePath.lastIndexOf(".") + 1,
					filePath.length()).toLowerCase();;
		}
		
		end = end.trim().toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")
				|| end.equals("amr")) {
			return SOUND;
		} else if (end.equals("3gp") || end.equals("mp4")) {
			return MOVIE;
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			return IMG;
		} else if (end.equals("apk")) {
			return APK;
		} else if (end.equals("ppt")) {
			return PPT;
		} else if (end.equals("xls")) {
			return XLS;
		} else if (end.equals("doc")) {
			return DOC;
		} else if (end.equals("pdf")) {
			return PDF;
		} else if (end.equals("chm")) {
			return CHM;
		} else if (end.equals("txt")) {
			return TXT;
		} else {
			return -1;
		}
	} 
	
	
	
	public static Intent openFile(String filePath) {
		if (filePath == null) {
			return null;
		}
		File file = new File(filePath);
		if (!file.exists())
			return null;
		/* 取得扩展名 */
		String end = file
				.getName()
				.substring(file.getName().lastIndexOf(".") + 1,
						file.getName().length()).toLowerCase();
		end = end.trim().toLowerCase();
//		System.out.println(end);
		/* 依扩展名的类型决定MimeType */
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")
				|| end.equals("amr")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("3gp") || end.equals("mp4")) {
			return getAudioFileIntent(filePath);
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			return getImageFileIntent(filePath);
		} else if (end.equals("apk")) {
			return getApkFileIntent(filePath);
		} else if (end.equals("ppt")) {
			return getPptFileIntent(filePath);
		} else if (end.equals("xls")) {
			return getExcelFileIntent(filePath);
		} else if (end.equals("doc")) {
			return getWordFileIntent(filePath);
		} else if (end.equals("pdf")) {
			return getPdfFileIntent(filePath);
		} else if (end.equals("chm")) {
			return getChmFileIntent(filePath);
		} else if (end.equals("txt")) {
			return getTextFileIntent(filePath, false);
		} else {
			return getAllIntent(filePath);
		}
	}

	// Android获取一个用于打开APK文件的intent
	public static Intent getAllIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "*/*");
		return intent;
	}

	// Android获取一个用于打开APK文件的intent
	public static Intent getApkFileIntent(String param) {

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		return intent;
	}

	// Android获取一个用于打开VIDEO文件的intent
	public static Intent getVideoFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "video/*");
		return intent;
	}

	// Android获取一个用于打开AUDIO文件的intent
	public static Intent getAudioFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		intent.putExtra("oneshot", 0);
		intent.putExtra("configchange", 0);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "audio/*");
		return intent;
	}

	// Android获取一个用于打开Html文件的intent
	public static Intent getHtmlFileIntent(String param) {

		Uri uri = Uri.parse(param).buildUpon()
				.encodedAuthority("com.android.htmlfileprovider")
				.scheme("content").encodedPath(param).build();
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.setDataAndType(uri, "text/html");
		return intent;
	}

	// Android获取一个用于打开图片文件的intent
	public static Intent getImageFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "image/*");
		return intent;
	}

	// Android获取一个用于打开PPT文件的intent
	public static Intent getPptFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
		return intent;
	}

	// Android获取一个用于打开Excel文件的intent
	public static Intent getExcelFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}

	// Android获取一个用于打开Word文件的intent
	public static Intent getWordFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}

	// Android获取一个用于打开CHM文件的intent
	public static Intent getChmFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/x-chm");
		return intent;
	}

	// Android获取一个用于打开文本文件的intent
	public static Intent getTextFileIntent(String param, boolean paramBoolean) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else {
			Uri uri2 = Uri.fromFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	}

	// Android获取一个用于打开PDF文件的intent
	public static Intent getPdfFileIntent(String param) {

		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}
	
	/**
	 * 判断是否有sdcard
	 * 
	 * @return
	 */
	public static boolean hasSDCard() {
		boolean b = false;
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			b = true;
		}
		return b;
	}

	/**
	 * 得到sdcard路径
	 * 
	 * @return
	 */
	public static String getExtPath() {
		String path = "";
		if (hasSDCard()) {
			path = Environment.getExternalStorageDirectory().getPath();
		}
		return path;
	}

	/**
	 * 得到/data/data/com.d3studio.together目录
	 * 
	 * @param mActivity
	 * @return
	 */
	public static String getPackagePath(Context mActivity) {
		return mActivity.getFilesDir().toString();
	}

	/**
	 * 根据url得到图片
	 * 
	 * @param url
	 * @return
	 */
	public static String getImageName(String url) {
		String imageName = "";
		if (url != null) {
			imageName = url.substring(url.lastIndexOf("/") + 1);
		}
		return imageName;
	}
	
}


InputTools

public class InputTools {

	// 隐藏虚拟键盘
	public static void HideKeyboard(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
		}
	}

	// 显示虚拟键盘
	public static void ShowKeyboard(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
	}

	// 强制显示或者关闭系统键盘
	public static void KeyBoard(final EditText txtSearchKey, final String status) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				InputMethodManager m = (InputMethodManager) txtSearchKey.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				if (status.equals("open")) {
					m.showSoftInput(txtSearchKey,InputMethodManager.SHOW_FORCED);
				} else {
					m.hideSoftInputFromWindow(txtSearchKey.getWindowToken(), 0);
				}
			}
		}, 300);
	}

	// 通过定时器强制隐藏虚拟键盘
	public static void TimerHideKeyboard(final View v) {
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					imm.hideSoftInputFromWindow(v.getApplicationWindowToken(),0);
				}
			}
		}, 10);
	}

	// 输入法是否显示着
	public static boolean KeyBoard(EditText edittext) {
		boolean bool = false;
		InputMethodManager imm = (InputMethodManager) edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			bool = true;
		}
		return bool;
	}
}



你可能感兴趣的:(android,工具类)