Android 开发常用的工具类

来源:互联网 发布:歌曲录音软件 编辑:程序博客网 时间:2024/06/05 23:08

(1)最常用的Log 打印类
public class AbLogUtil {

    /** debug开关. */
public static boolean D = true;

/** info开关. */
public static boolean I = true;

/** error开关. */
public static boolean E = true;

/** 起始执行时间. */
public static long startLogTimeInMillis = 0;


/**
* debug日志
* @param tag
* @param message
*/
public static void d(String tag,String message) {
if(D) Log.d(tag, message);
}

/**
* debug日志
* @param context
* @param message
*/
public static void d(Context context,String message) {
String tag = context.getClass().getSimpleName();
d(tag, message);
}

/**
* debug日志
* @param clazz
* @param message
*/
public static void d(Class<?> clazz,String message) {
String tag = clazz.getSimpleName();
d(tag, message);
}

/**
* info日志
* @param tag
* @param message
*/
public static void i(String tag,String message) {
Log.i(tag, message);
}

/**
* info日志
* @param context
* @param message
*/
public static void i(Context context,String message) {
String tag = context.getClass().getSimpleName();
i(tag, message);
}

/**
* info日志
* @param clazz
* @param message
*/
public static void i(Class<?> clazz,String message) {
String tag = clazz.getSimpleName();
i(tag, message);
}



/**
* error日志
* @param tag
* @param message
*/
public static void e(String tag,String message) {
Log.e(tag, message);
}

/**
* error日志
* @param context
* @param message
*/
public static void e(Context context,String message) {
String tag = context.getClass().getSimpleName();
e(tag, message);
}

/**
* error日志
* @param clazz
* @param message
*/
public static void e(Class<?> clazz,String message) {
String tag = clazz.getSimpleName();
e(tag, message);
}

/**
* 描述:记录当前时间毫秒.

*/
public static void prepareLog(String tag) {
Calendar current = Calendar.getInstance();
startLogTimeInMillis = current.getTimeInMillis();
Log.d(tag,"日志计时开始:"+startLogTimeInMillis);
}

/**
* 描述:记录当前时间毫秒.

*/
public static void prepareLog(Context context) {
String tag = context.getClass().getSimpleName();
prepareLog(tag);
}

/**
* 描述:记录当前时间毫秒.

*/
public static void prepareLog(Class<?> clazz) {
String tag = clazz.getSimpleName();
prepareLog(tag);
}

/**
* 描述:打印这次的执行时间毫秒,需要首先调用prepareLog().
*
* @param tag 标记
* @param message 描述
* @param printTime 是否打印时间
*/
public static void d(String tag, String message,boolean printTime) {
Calendar current = Calendar.getInstance();
long endLogTimeInMillis = current.getTimeInMillis();
Log.d(tag,message+":"+(endLogTimeInMillis-startLogTimeInMillis)+"ms");
}


/**
* 描述:打印这次的执行时间毫秒,需要首先调用prepareLog().
*
* @param tag 标记
* @param message 描述
* @param printTime 是否打印时间
*/
public static void d(Context context,String message,boolean printTime) {
String tag = context.getClass().getSimpleName();
   d(tag,message,printTime);
}

/**
* 描述:打印这次的执行时间毫秒,需要首先调用prepareLog().
*
* @param clazz 标记
* @param message 描述
* @param printTime 是否打印时间
*/
public static void d(Class<?> clazz,String message,boolean printTime) {
String tag = clazz.getSimpleName();
d(tag,message,printTime);
}


/**
* debug日志的开关
* @param d
*/
public static void debug(boolean d) {
D  = d;
}

/**
* info日志的开关
* @param i
*/
public static void info(boolean i) {
I  = i;
}

/**
* error日志的开关
* @param e
*/
public static void error(boolean e) {
E  = e;
}

/**
* 设置日志的开关
* @param e
*/
public static void setVerbose(boolean d,boolean i,boolean e) {
D  = d;
I  = i;
E  = e;
}

/**
* 打开所有日志,默认全打开
* @param d
*/
public static void openAll() {
D  = true;
I  = true;
E  = true;
}

/**
* 关闭所有日志
* @param d
*/
public static void closeAll() {
D  = false;
I  = false;
E  = false;
}




}


(2)字符串的处理类
public class AbStrUtil {
    
    /**
     * 描述:将null转化为“”.
     *
     * @param str 指定的字符串
     * @return 字符串的String类型
     */
    public static String parseEmpty(String str) {
        if(str==null || "null".equals(str.trim())){
        str = "";
        }
        return str.trim();
    }
    
    /**
     * 描述:判断一个字符串是否为null或空值.
     *
     * @param str 指定的字符串
     * @return true or false
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }
    
    /**
     * 获取字符串中文字符的长度(每个中文算2个字符).
     *
     * @param str 指定的字符串
     * @return 中文字符的长度
     */
    public static int chineseLength(String str) {
        int valueLength = 0;
        String chinese = "[\u0391-\uFFE5]";
        /* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
        if(!isEmpty(str)){
       for (int i = 0; i < str.length(); i++) {
           /* 获取一个字符 */
           String temp = str.substring(i, i + 1);
           /* 判断是否为中文字符 */
           if (temp.matches(chinese)) {
               valueLength += 2;
           }
       }
        }
        return valueLength;
    }
    
    /**
     * 描述:获取字符串的长度.
     *
     * @param str 指定的字符串
     * @return  字符串的长度(中文字符计2个)
     */
     public static int strLength(String str) {
         int valueLength = 0;
         String chinese = "[\u0391-\uFFE5]";
         if(!isEmpty(str)){
        //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
        for (int i = 0; i < str.length(); i++) {
            //获取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否为中文字符
            if (temp.matches(chinese)) {
                //中文字符长度为2
                valueLength += 2;
            } else {
                //其他字符长度为1
                valueLength += 1;
            }
        }
         }
         return valueLength;
     }
     
     /**
      * 描述:获取指定长度的字符所在位置.
      *
      * @param str 指定的字符串
      * @param maxL 要取到的长度(字符长度,中文字符计2个)
      * @return 字符的所在位置
      */
     public static int subStringLength(String str,int maxL) {
    int currentIndex = 0;
         int valueLength = 0;
         String chinese = "[\u0391-\uFFE5]";
         //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
         for (int i = 0; i < str.length(); i++) {
             //获取一个字符
             String temp = str.substring(i, i + 1);
             //判断是否为中文字符
             if (temp.matches(chinese)) {
                 //中文字符长度为2
                 valueLength += 2;
             } else {
                 //其他字符长度为1
                 valueLength += 1;
             }
             if(valueLength >= maxL){
            currentIndex = i;
            break;
             }
         }
         return currentIndex;
     }
     
    /**
     * 描述:手机号格式验证.
     *
     * @param str 指定的手机号码字符串
     * @return 是否为手机号码格式:是为true,否则false
     */
  public static Boolean isMobileNo(String str) {
  Boolean isMobileNo = false;
  try {
Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
Matcher m = p.matcher(str);
isMobileNo = m.matches();
} catch (Exception e) {
e.printStackTrace();
}
  return isMobileNo;
  }
 
  /**
 * 描述:是否只是字母和数字.
 *
 * @param str 指定的字符串
 * @return 是否只是字母和数字:是为true,否则false
 */
  public static Boolean isNumberLetter(String str) {
  Boolean isNoLetter = false;
  String expr = "^[A-Za-z0-9]+$";
  if (str.matches(expr)) {
  isNoLetter = true;
  }
  return isNoLetter;
  }
 
  /**
 * 描述:是否只是数字.
 *
 * @param str 指定的字符串
 * @return 是否只是数字:是为true,否则false
 */
  public static Boolean isNumber(String str) {
  Boolean isNumber = false;
  String expr = "^[0-9]+$";
  if (str.matches(expr)) {
  isNumber = true;
  }
  return isNumber;
  }
 
  /**
 * 描述:是否是邮箱.
 *
 * @param str 指定的字符串
 * @return 是否是邮箱:是为true,否则false
 */
  public static Boolean isEmail(String str) {
  Boolean isEmail = false;
  String expr = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
  if (str.matches(expr)) {
  isEmail = true;
  }
  return isEmail;
  }
 
  /**
 * 描述:是否是中文.
 *
 * @param str 指定的字符串
 * @return  是否是中文:是为true,否则false
 */
    public static Boolean isChinese(String str) {
    Boolean isChinese = true;
        String chinese = "[\u0391-\uFFE5]";
        if(!isEmpty(str)){
        //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
        for (int i = 0; i < str.length(); i++) {
            //获取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否为中文字符
            if (temp.matches(chinese)) {
            }else{
            isChinese = false;
            }
        }
        }
        return isChinese;
    }
    
    /**
     * 描述:是否包含中文.
     *
     * @param str 指定的字符串
     * @return  是否包含中文:是为true,否则false
     */
    public static Boolean isContainChinese(String str) {
    Boolean isChinese = false;
        String chinese = "[\u0391-\uFFE5]";
        if(!isEmpty(str)){
        //获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
        for (int i = 0; i < str.length(); i++) {
            //获取一个字符
            String temp = str.substring(i, i + 1);
            //判断是否为中文字符
            if (temp.matches(chinese)) {
            isChinese = true;
            }else{
             
            }
        }
        }
        return isChinese;
    }
 
  /**
 * 描述:从输入流中获得String.
 *
 * @param is 输入流
 * @return 获得的String
 */
  public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

//最后一个\n删除
if(sb.indexOf("\n")!=-1 && sb.lastIndexOf("\n") == sb.length()-1){
sb.delete(sb.lastIndexOf("\n"), sb.lastIndexOf("\n")+1);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
 
  /**
 * 描述:标准化日期时间类型的数据,不足两位的补0.
 *
 * @param dateTime 预格式的时间字符串,如:2012-3-2 12:2:20
 * @return String 格式化好的时间字符串,如:2012-03-20 12:02:20
 */
  public static String dateTimeFormat(String dateTime) {
StringBuilder sb = new StringBuilder();
try {
if(isEmpty(dateTime)){
return null;
}
String[] dateAndTime = dateTime.split(" ");
if(dateAndTime.length>0){
 for(String str : dateAndTime){
if(str.indexOf("-")!=-1){
String[] date =  str.split("-");
for(int i=0;i<date.length;i++){
 String str1 = date[i];
 sb.append(strFormat2(str1));
 if(i< date.length-1){
 sb.append("-");
 }
}
}else if(str.indexOf(":")!=-1){
sb.append(" ");
String[] date =  str.split(":");
for(int i=0;i<date.length;i++){
 String str1 = date[i];
 sb.append(strFormat2(str1));
 if(i< date.length-1){
 sb.append(":");
 }
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return null;

return sb.toString();
}
 
  /**
 * 描述:不足2个字符的在前面补“0”.
 *
 * @param str 指定的字符串
 * @return 至少2个字符的字符串
 */
    public static String strFormat2(String str) {
try {
if(str.length()<=1){
str = "0"+str;
}
} catch (Exception e) {
e.printStackTrace();

return str;
}
    
    /**
     * 描述:截取字符串到指定字节长度.
     *
     * @param str the str
     * @param length 指定字节长度
     * @return 截取后的字符串
     */
    public static String cutString(String str,int length){
return cutString(str, length,"");
}
    
    /**
     * 描述:截取字符串到指定字节长度.
     *
     * @param str 文本
     * @param length 字节长度
     * @param dot 省略符号
     * @return 截取后的字符串
     */
public static String cutString(String str,int length,String dot){
int strBLen = strlen(str,"GBK");
if( strBLen <= length ){
      return str;
      }
int temp = 0;
StringBuffer sb = new StringBuffer(length);
char[] ch = str.toCharArray();
for ( char c : ch ) {
sb.append( c );
if ( c > 256 ) {
    temp += 2;
    } else {
    temp += 1;
    }
if (temp >= length) {
if( dot != null) {
sb.append( dot );
}
           break;
       }
}
return sb.toString();
    }

/**
* 描述:截取字符串从第一个指定字符.
*
* @param str1 原文本
* @param str2 指定字符
* @param offset 偏移的索引
* @return 截取后的字符串
*/
public static String cutStringFromChar(String str1,String str2,int offset){
if(isEmpty(str1)){
return "";
}
int start = str1.indexOf(str2);
if(start!=-1){
if(str1.length()>start+offset){
return str1.substring(start+offset);
}
}
return "";
    }

/**
* 描述:获取字节长度.
*
* @param str 文本
* @param charset 字符集(GBK)
* @return the int
*/
public static int strlen(String str,String charset){
if(str==null||str.length()==0){
return 0;
}
int length=0;
try {
length = str.getBytes(charset).length;
} catch (Exception e) {
e.printStackTrace();
}
return length;
}
    
/**
* 获取大小的描述.
*
* @param size 字节个数
* @return  大小的描述
*/
    public static String getSizeDesc(long size) {
  String suffix = "B";
  if (size >= 1024){
suffix = "K";
size = size>>10;
if (size >= 1024){
suffix = "M";
//size /= 1024;
size = size>>10;
if (size >= 1024){
           suffix = "G";
           size = size>>10;
           //size /= 1024;
       }
}
  }
        return size+suffix;
    }
    
    /**
     * 描述:ip地址转换为10进制数.
     *
     * @param ip the ip
     * @return the long
     */
    public static long ip2int(String ip){ 
    ip = ip.replace(".", ",");
    String[]items = ip.split(","); 
    return Long.valueOf(items[0])<<24 |Long.valueOf(items[1])<<16 |Long.valueOf(items[2])<<8 |Long.valueOf(items[3]); 
    } 

    /**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {
System.out.println(dateTimeFormat("2012-3-2 12:2:20"));
}


}


(3)提示(toast)的封装类
public class AbToastUtil {
    
    /** 上下文. */
    private static Context mContext = null;
    
    /** 显示Toast. */
    public static final int SHOW_TOAST = 0;
    
    /**
* 主要Handler类,在线程中可用
* what:0.提示文本信息
*/
private static Handler baseHandler = new Handler() {


@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_TOAST:
showToast(mContext,msg.getData().getString("TEXT"));
break;
default:
break;
}
}
};
    
    /**
     * 描述:Toast提示文本.
     * @param text  文本
     */
public static void showToast(Context context,String text) {
mContext = context;
if(!AbStrUtil.isEmpty(text)){
Toast.makeText(context,text, Toast.LENGTH_SHORT).show();
}

}

/**
     * 描述:Toast提示文本.
     * @param resId  文本的资源ID
     */
public static void showToast(Context context,int resId) {
mContext = context;
Toast.makeText(context,""+context.getResources().getText(resId), Toast.LENGTH_SHORT).show();
}
    
    /**
* 描述:在线程中提示文本信息.
* @param resId 要提示的字符串资源ID,消息what值为0,
*/
public static void showToastInThread(Context context,int resId) {
mContext = context;
Message msg = baseHandler.obtainMessage(SHOW_TOAST);
Bundle bundle = new Bundle();
bundle.putString("TEXT", context.getResources().getString(resId));
msg.setData(bundle);
baseHandler.sendMessage(msg);
}

/**
* 描述:在线程中提示文本信息.
* @param toast 消息what值为0
*/
public static void showToastInThread(Context context,String text) {
mContext = context;
Message msg = baseHandler.obtainMessage(SHOW_TOAST);
Bundle bundle = new Bundle();
bundle.putString("TEXT", text);
msg.setData(bundle);
baseHandler.sendMessage(msg);
}
    


}


(4)本地保存数据的类(SharedPreferences)


public class AbSharedUtil {


private static final String SHARED_PATH = AbAppConfig.SHARED_PATH;


public static SharedPreferences getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(SHARED_PATH, Context.MODE_PRIVATE);
}

public static void putInt(Context context,String key, int value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putInt(key, value);
edit.commit();
}


public static int getInt(Context context,String key) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getInt(key, 0);
}

public static void putString(Context context,String key, String value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putString(key, value);
edit.commit();
}


public static String getString(Context context,String key) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getString(key,null);
}

public static void putBoolean(Context context,String key, boolean value) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
Editor edit = sharedPreferences.edit();
edit.putBoolean(key, value);
edit.commit();
}


public static boolean getBoolean(Context context,String key,boolean defValue) {
SharedPreferences sharedPreferences = getDefaultSharedPreferences(context);
return sharedPreferences.getBoolean(key,defValue);
}


}
(5)都写文件相关的操作。


public class AbFileUtil {

/** 默认APP根目录. */
private static  String downloadRootDir = null;

    /** 默认下载图片文件目录. */
private static  String imageDownloadDir = null;
    
    /** 默认下载文件目录. */
private static  String fileDownloadDir = null;

/** 默认缓存目录. */
private static  String cacheDownloadDir = null;

/** 默认下载数据库文件的目录. */
private static  String dbDownloadDir = null;

/** 剩余空间大于200M才使用SD缓存. */
private static int freeSdSpaceNeededToCache = 200*1024*1024;
 
/**
 * 描述:通过文件的网络地址从SD卡中读取图片,如果SD中没有则自动下载并保存.
 * @param url 文件的网络地址
 * @param type 图片的处理类型(剪切或者缩放到指定大小,参考AbImageUtil类)
 * 如果设置为原图,则后边参数无效,得到原图
 * @param desiredWidth 新图片的宽
 * @param desiredHeight 新图片的高
 * @return Bitmap 新图片
 */
public static Bitmap getBitmapFromSD(String url,int type,int desiredWidth, int desiredHeight){
Bitmap bitmap = null;
try {
if(AbStrUtil.isEmpty(url)){
    return null;
    }
 
//SD卡不存在 或者剩余空间不足了就不缓存到SD卡了
if(!isCanUseSD() || freeSdSpaceNeededToCache < freeSpaceOnSD()){
bitmap = getBitmapFromURL(url,type,desiredWidth,desiredHeight);
return bitmap;
    }
//下载文件,如果不存在就下载,存在直接返回地址
String downFilePath = downloadFile(url,imageDownloadDir);
if(downFilePath != null){
//获取图片
return getBitmapFromSD(new File(downFilePath),type,desiredWidth,desiredHeight);
}else{
return null;
}


} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
 
 
/**
  * 描述:通过文件的本地地址从SD卡读取图片.
  *
  * @param file the file
  * @param type 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类)
  * 如果设置为原图,则后边参数无效,得到原图
  * @param desiredWidth 新图片的宽
  * @param desiredHeight 新图片的高
  * @return Bitmap 新图片
  */
public static Bitmap getBitmapFromSD(File file,int type,int desiredWidth, int desiredHeight){
Bitmap bitmap = null;
try {
//SD卡是否存在
if(!isCanUseSD()){
    return null;
    }
 
//文件是否存在
if(!file.exists()){
return null;
}
 
//文件存在
if(type == AbImageUtil.CUTIMG){
bitmap = AbImageUtil.cutImg(file,desiredWidth,desiredHeight);
}else if(type == AbImageUtil.SCALEIMG){
bitmap = AbImageUtil.scaleImg(file,desiredWidth,desiredHeight);
}else{
bitmap = AbImageUtil.getBitmap(file);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
 
/**
     * 描述:通过文件的本地地址从SD卡读取图片.
     *
     * @param file the file
     * @return Bitmap 图片
     */
     public static Bitmap getBitmapFromSD(File file){
         Bitmap bitmap = null;
         try {
             //SD卡是否存在
             if(!isCanUseSD()){
                return null;
             }
             //文件是否存在
             if(!file.exists()){
                 return null;
             }
             //文件存在
             bitmap = AbImageUtil.getBitmap(file);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
     }
 
 
/**
 * 描述:将图片的byte[]写入本地文件.
 * @param imgByte 图片的byte[]形势
 * @param fileName 文件名称,需要包含后缀,如.jpg
 * @param type 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类)
 * @param desiredWidth 新图片的宽
 * @param desiredHeight 新图片的高
 * @return Bitmap 新图片
 */
     public static Bitmap getBitmapFromByte(byte[] imgByte,String fileName,int type,int desiredWidth, int desiredHeight){
      FileOutputStream fos = null;
      DataInputStream dis = null;
      ByteArrayInputStream bis = null;
      Bitmap bitmap = null;
      File file = null;
      try {
      if(imgByte!=null){
      
      file = new File(imageDownloadDir+fileName);
      if(!file.exists()){
           file.createNewFile();
      }
      fos = new FileOutputStream(file);
      int readLength = 0;
      bis = new ByteArrayInputStream(imgByte);
      dis = new DataInputStream(bis);
      byte[] buffer = new byte[1024];
      
      while ((readLength = dis.read(buffer))!=-1) {
      fos.write(buffer, 0, readLength);
          try {
    Thread.sleep(500);
      } catch (Exception e) {
      }
      }
      fos.flush();
      
      bitmap = getBitmapFromSD(file,type,desiredWidth,desiredHeight);
      }
  
} catch (Exception e) {
e.printStackTrace();
}finally{
if(dis!=null){
try {
dis.close();
} catch (Exception e) {
}
}    
if(bis!=null){
try {
bis.close();
} catch (Exception e) {
}
}
if(fos!=null){
try {
fos.close();
} catch (Exception e) {
}
}
}
        return  bitmap;
     }
   
/**
* 描述:根据URL从互连网获取图片.
* @param url 要下载文件的网络地址
* @param type 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类)
* @param desiredWidth 新图片的宽
* @param desiredHeight 新图片的高
* @return Bitmap 新图片
*/
public static Bitmap getBitmapFromURL(String url,int type,int desiredWidth, int desiredHeight){
Bitmap bit = null;
try {
bit = AbImageUtil.getBitmap(url, type, desiredWidth, desiredHeight);
   } catch (Exception e) {
    AbLogUtil.d(AbFileUtil.class, "下载图片异常:"+e.getMessage());
}
return bit;
}

/**
* 描述:获取src中的图片资源.
*
* @param src 图片的src路径,如(“image/arrow.png”)
* @return Bitmap 图片
*/
public static Bitmap getBitmapFromSrc(String src){
Bitmap bit = null;
try {
bit = BitmapFactory.decodeStream(AbFileUtil.class.getResourceAsStream(src));
   } catch (Exception e) {
    AbLogUtil.d(AbFileUtil.class, "获取图片异常:"+e.getMessage());
}
return bit;
}

/**
* 描述:获取Asset中的图片资源.
*
* @param context the context
* @param fileName the file name
* @return Bitmap 图片
*/
public static Bitmap getBitmapFromAsset(Context context,String fileName){
Bitmap bit = null;
try {
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
bit = BitmapFactory.decodeStream(is);
   } catch (Exception e) {
    AbLogUtil.d(AbFileUtil.class, "获取图片异常:"+e.getMessage());
}
return bit;
}

/**
* 描述:获取Asset中的图片资源.
*
* @param context the context
* @param fileName the file name
* @return Drawable 图片
*/
public static Drawable getDrawableFromAsset(Context context,String fileName){
Drawable drawable = null;
try {
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
drawable = Drawable.createFromStream(is,null);
   } catch (Exception e) {
    AbLogUtil.d(AbFileUtil.class, "获取图片异常:"+e.getMessage());
}
return drawable;
}

     /**
  * 下载网络文件到SD卡中.如果SD中存在同名文件将不再下载
  *
  * @param url 要下载文件的网络地址
  * @param dirPath the dir path
  * @return 下载好的本地文件地址
  */
  public static String downloadFile(String url,String dirPath){
  InputStream in = null;
  FileOutputStream fileOutputStream = null;
  HttpURLConnection connection = null;
  String downFilePath = null;
  File file = null;
  try {
      if(!isCanUseSD()){
      return null;
      }
             //先判断SD卡中有没有这个文件,不比较后缀部分比较
             String fileNameNoMIME  = getCacheFileNameFromUrl(url);
             File parentFile = new File(imageDownloadDir);
             File[] files = parentFile.listFiles();
             for(int i = 0; i < files.length; ++i){
                  String fileName = files[i].getName();
                  String name = fileName.substring(0,fileName.lastIndexOf("."));
                  if(name.equals(fileNameNoMIME)){
                      //文件已存在
                      return files[i].getPath();
                  }
             } 
             
  URL mUrl = new URL(url);
  connection = (HttpURLConnection)mUrl.openConnection();
  connection.connect();
             //获取文件名,下载文件
             String fileName  = getCacheFileNameFromUrl(url,connection);
             
             file = new File(imageDownloadDir,fileName);
             downFilePath = file.getPath();
             if(!file.exists()){
                 file.createNewFile();
             }else{
                 //文件已存在
                 return file.getPath();
             }
  in = connection.getInputStream();
  fileOutputStream = new FileOutputStream(file);
  byte[] b = new byte[1024];
  int temp = 0;
  while((temp=in.read(b))!=-1){
  fileOutputStream.write(b, 0, temp);
  }
  }catch(Exception e){
  e.printStackTrace();
  AbLogUtil.e(AbFileUtil.class, "有文件下载出错了,已删除");
  //检查文件大小,如果文件为0B说明网络不好没有下载成功,要将建立的空文件删除
  if(file != null){
  file.delete();
  }
  file = null;
  downFilePath = null;
  }finally{
  try {
  if(in!=null){
  in.close();
  }
  } catch (Exception e) {
  e.printStackTrace();
  }
  try {
  if(fileOutputStream!=null){
  fileOutputStream.close();
  }
  } catch (Exception e) {
  e.printStackTrace();
  }
  try {
  if(connection!=null){
     connection.disconnect();
  }
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
  return downFilePath;
  }

/**
* 描述:获取网络文件的大小.
*
* @param Url 图片的网络路径
* @return int 网络文件的大小
*/
public static int getContentLengthFromUrl(String Url){
int mContentLength = 0;
try {
URL url = new URL(Url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
mHttpURLConnection.setConnectTimeout(5 * 1000);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
mHttpURLConnection.setRequestProperty("Referer", Url);
mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
mHttpURLConnection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == 200){
// 根据响应获取文件大小
mContentLength = mHttpURLConnection.getContentLength();
}
   } catch (Exception e) {
    e.printStackTrace();
    AbLogUtil.d(AbFileUtil.class, "获取长度异常:"+e.getMessage());
}
return mContentLength;
}

/**
     * 获取文件名,通过网络获取.
     * @param url 文件地址
     * @return 文件名
     */
    public static String getRealFileNameFromUrl(String url){
        String name = null;
        try {
            if(AbStrUtil.isEmpty(url)){
                return name;
            }
            
            URL mUrl = new URL(url);
            HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mHttpURLConnection.setConnectTimeout(5 * 1000);
            mHttpURLConnection.setRequestMethod("GET");
            mHttpURLConnection.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
            mHttpURLConnection.setRequestProperty("Referer", url);
            mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
            mHttpURLConnection.setRequestProperty("User-Agent","");
            mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            mHttpURLConnection.connect();
            if (mHttpURLConnection.getResponseCode() == 200){
                for (int i = 0;; i++) {
                        String mine = mHttpURLConnection.getHeaderField(i);
                        if (mine == null){
                            break;
                        }
                        if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                            Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                            if (m.find())
                                return m.group(1).replace("\"", "");
                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            AbLogUtil.e(AbFileUtil.class, "网络上获取文件名失败");
        }
        return name;
    }

 
/**
* 获取真实文件名(xx.后缀),通过网络获取.
* @param connection 连接
* @return 文件名
*/
public static String getRealFileName(HttpURLConnection connection){
String name = null;
try {
if(connection == null){
return name;
}
if (connection.getResponseCode() == 200){
for (int i = 0;; i++) {
String mime = connection.getHeaderField(i);
if (mime == null){
break;
}
// "Content-Disposition","attachment; filename=1.txt"
// Content-Length
if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
if (m.find()){
return m.group(1).replace("\"", "");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
AbLogUtil.e(AbFileUtil.class, "网络上获取文件名失败");
}
return name;
    }

/**
* 获取真实文件名(xx.后缀),通过网络获取.
*
* @param response the response
* @return 文件名
*/
    public static String getRealFileName(HttpResponse response){
        String name = null;
        try {
            if(response == null){
                return name;
            }
            //获取文件名
            Header[] headers = response.getHeaders("content-disposition");
            for(int i=0;i<headers.length;i++){
                 Matcher m = Pattern.compile(".*filename=(.*)").matcher(headers[i].getValue());
                 if (m.find()){
                     name =  m.group(1).replace("\"", "");
                 }
            }
        } catch (Exception e) {
            e.printStackTrace();
            AbLogUtil.e(AbFileUtil.class, "网络上获取文件名失败");
        }
        return name;
    }
    
    /**
     * 获取文件名(不含后缀).
     *
     * @param url 文件地址
     * @return 文件名
     */
    public static String getCacheFileNameFromUrl(String url){
        if(AbStrUtil.isEmpty(url)){
            return null;
        }
        String name = null;
        try {
            name = AbMd5.MD5(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }
    

/**
* 获取文件名(.后缀),外链模式和通过网络获取.
*
* @param url 文件地址
* @param response the response
* @return 文件名
*/
    public static String getCacheFileNameFromUrl(String url,HttpResponse response){
        if(AbStrUtil.isEmpty(url)){
            return null;
        }
        String name = null;
        try {
            //获取后缀
            String suffix = getMIMEFromUrl(url,response);
            if(AbStrUtil.isEmpty(suffix)){
                suffix = ".ab";
            }
            name = AbMd5.MD5(url)+suffix;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }


/**
* 获取文件名(.后缀),外链模式和通过网络获取.
*
* @param url 文件地址
* @param connection the connection
* @return 文件名
*/
public static String getCacheFileNameFromUrl(String url,HttpURLConnection connection){
if(AbStrUtil.isEmpty(url)){
return null;
}
String name = null;
try {
//获取后缀
String suffix = getMIMEFromUrl(url,connection);
if(AbStrUtil.isEmpty(suffix)){
suffix = ".ab";
}
name = AbMd5.MD5(url)+suffix;
} catch (Exception e) {
e.printStackTrace();
}
return name;
    }


/**
* 获取文件后缀,本地.
*
* @param url 文件地址
* @param connection the connection
* @return 文件后缀
*/
public static String getMIMEFromUrl(String url,HttpURLConnection connection){

if(AbStrUtil.isEmpty(url)){
return null;
}
String suffix = null;
try {
//获取后缀
if(url.lastIndexOf(".")!=-1){
suffix = url.substring(url.lastIndexOf("."));
if(suffix.indexOf("/")!=-1 || suffix.indexOf("?")!=-1 || suffix.indexOf("&")!=-1){
suffix = null;
}
}
if(AbStrUtil.isEmpty(suffix)){
//获取文件名  这个效率不高
String fileName = getRealFileName(connection);
if(fileName!=null && fileName.lastIndexOf(".")!=-1){
suffix = fileName.substring(fileName.lastIndexOf("."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return suffix;
    }

/**
* 获取文件后缀,本地和网络.
*
* @param url 文件地址
* @param response the response
* @return 文件后缀
*/
    public static String getMIMEFromUrl(String url,HttpResponse response){
        
        if(AbStrUtil.isEmpty(url)){
            return null;
        }
        String mime = null;
        try {
            //获取后缀
            if(url.lastIndexOf(".")!=-1){
                mime = url.substring(url.lastIndexOf("."));
                 if(mime.indexOf("/")!=-1 || mime.indexOf("?")!=-1 || mime.indexOf("&")!=-1){
                     mime = null;
                 }
            }
            if(AbStrUtil.isEmpty(mime)){
                 //获取文件名  这个效率不高
                 String fileName = getRealFileName(response);
                 if(fileName!=null && fileName.lastIndexOf(".")!=-1){
                     mime = fileName.substring(fileName.lastIndexOf("."));
                 }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mime;
    }

/**
* 描述:从sd卡中的文件读取到byte[].
*
* @param path sd卡中文件路径
* @return byte[]
*/
public static byte[] getByteArrayFromSD(String path) {  
byte[] bytes = null; 
ByteArrayOutputStream out = null;
   try {
    File file = new File(path);  
    //SD卡是否存在
if(!isCanUseSD()){
return null;
   }
//文件是否存在
if(!file.exists()){
return null;
}
   
    long fileSize = file.length();  
    if (fileSize > Integer.MAX_VALUE) {  
         return null;  
    }  


FileInputStream in = new FileInputStream(path);  
   out = new ByteArrayOutputStream(1024);  
byte[] buffer = new byte[1024];  
int size=0;  
while((size=in.read(buffer))!=-1) {  
  out.write(buffer,0,size);  
}  
in.close();  
            bytes = out.toByteArray();  
   
} catch (Exception e) {
e.printStackTrace();
} finally{
if(out!=null){
try {
out.close();
} catch (Exception e) {
}
}
}
   return bytes;
    }  

/**
* 描述:将byte数组写入文件.
*
* @param path the path
* @param content the content
* @param create the create
*/
public static void writeByteArrayToSD(String path, byte[] content,boolean create){  
   
FileOutputStream fos = null;
try {
    File file = new File(path);  
    //SD卡是否存在
if(!isCanUseSD()){
return;
   }
//文件是否存在
if(!file.exists()){
if(create){
File parent = file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
file.createNewFile();
}
}else{
   return;
}
}
fos = new FileOutputStream(path);  
fos.write(content);  

} catch (Exception e) {
e.printStackTrace();
}finally{
if(fos!=null){
try {
fos.close();
} catch (Exception e) {
}
}
}
   }  
 
/**
* 描述:SD卡是否能用.
*
* @return true 可用,false不可用
*/
public static boolean isCanUseSD() { 
   try { 
       return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); 
   } catch (Exception e) { 
       e.printStackTrace(); 
   } 
   return false; 
    } 


/**
* 描述:初始化存储目录.
*
* @param context the context
*/
public static void initFileDir(Context context){

PackageInfo info = AbAppUtil.getPackageInfo(context);

//默认下载文件根目录. 
String downloadRootPath = File.separator + AbAppConfig.DOWNLOAD_ROOT_DIR + File.separator + info.packageName + File.separator;

   //默认下载图片文件目录. 
String imageDownloadPath = downloadRootPath + AbAppConfig.DOWNLOAD_IMAGE_DIR + File.separator;
   
   //默认下载文件目录.
String fileDownloadPath = downloadRootPath + AbAppConfig.DOWNLOAD_FILE_DIR + File.separator;

//默认缓存目录.
String cacheDownloadPath = downloadRootPath + AbAppConfig.CACHE_DIR + File.separator;

//默认DB目录.
String dbDownloadPath = downloadRootPath + AbAppConfig.DB_DIR + File.separator;
   
try {
if(!isCanUseSD()){
return;
}else{

File root = Environment.getExternalStorageDirectory();
File downloadDir = new File(root.getAbsolutePath() + downloadRootPath);
if(!downloadDir.exists()){
downloadDir.mkdirs();
}
downloadRootDir = downloadDir.getPath();

File cacheDownloadDirFile = new File(root.getAbsolutePath() + cacheDownloadPath);
if(!cacheDownloadDirFile.exists()){
cacheDownloadDirFile.mkdirs();
}
cacheDownloadDir = cacheDownloadDirFile.getPath();

File imageDownloadDirFile = new File(root.getAbsolutePath() + imageDownloadPath);
if(!imageDownloadDirFile.exists()){
imageDownloadDirFile.mkdirs();
}
imageDownloadDir = imageDownloadDirFile.getPath();

File fileDownloadDirFile = new File(root.getAbsolutePath() + fileDownloadPath);
if(!fileDownloadDirFile.exists()){
fileDownloadDirFile.mkdirs();
}
fileDownloadDir = fileDownloadDirFile.getPath();

File dbDownloadDirFile = new File(root.getAbsolutePath() + dbDownloadPath);
if(!dbDownloadDirFile.exists()){
dbDownloadDirFile.mkdirs();
}
dbDownloadDir = dbDownloadDirFile.getPath();

}
} catch (Exception e) {
e.printStackTrace();
}
}


    /**
     * 计算sdcard上的剩余空间.
     *
     * @return the int
     */
    public static int freeSpaceOnSD() {
       StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
       double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / 1024*1024;
       return (int) sdFreeMB;
    }

    /**
     * 根据文件的最后修改时间进行排序.
     */
    public static class FileLastModifSort implements Comparator<File> {
        
        /* (non-Javadoc)
         * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
         */
        public int compare(File arg0, File arg1) {
            if (arg0.lastModified() > arg1.lastModified()) {
                return 1;
            } else if (arg0.lastModified() == arg1.lastModified()) {
                return 0;
            } else {
                return -1;
            }
        }
    }



/**
* 删除所有缓存文件.
*
* @return true, if successful
*/
    public static boolean clearDownloadFile() {
   
       try {
  if(!isCanUseSD()){
return false;
  }
  
  File path = Environment.getExternalStorageDirectory();
  File fileDirectory = new File(path.getAbsolutePath() + downloadRootDir);
      File[] files = fileDirectory.listFiles();
      if (files == null) {
           return true;
      }
           for (int i = 0; i < files.length; i++) {
               files[i].delete();
           }
  } catch (Exception e) {
  e.printStackTrace();
  return false;
  }
       return true;
    }
    
    
    /**
     * 描述:读取Assets目录的文件内容.
     *
     * @param context the context
     * @param name the name
     * @param encoding the encoding
     * @return the string
     */
    public static String readAssetsByName(Context context,String name,String encoding){
    String text = null;
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {  
    inputReader = new InputStreamReader(context.getAssets().open(name));
    bufReader = new BufferedReader(inputReader);
    String line = null;
    StringBuffer buffer = new StringBuffer();
    while((line = bufReader.readLine()) != null){
    buffer.append(line);
    }
    text = new String(buffer.toString().getBytes(), encoding);
         } catch (Exception e) {  
        e.printStackTrace();
         } finally{
try {
if(bufReader!=null){
bufReader.close();
}
if(inputReader!=null){
inputReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
    return text;
    }
    
    /**
     * 描述:读取Raw目录的文件内容.
     *
     * @param context the context
     * @param id the id
     * @param encoding the encoding
     * @return the string
     */
    public static String readRawByName(Context context,int id,String encoding){
    String text = null;
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
        try {
inputReader = new InputStreamReader(context.getResources().openRawResource(id));
bufReader = new BufferedReader(inputReader);
String line = null;
StringBuffer buffer = new StringBuffer();
while((line = bufReader.readLine()) != null){
buffer.append(line);
}
            text = new String(buffer.toString().getBytes(),encoding);
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bufReader!=null){
bufReader.close();
}
if(inputReader!=null){
inputReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
        return text;
    }




/**
* Gets the download root dir.
*
* @param context the context
* @return the download root dir
*/
public static String getDownloadRootDir(Context context) {
if(downloadRootDir == null){
initFileDir(context);
}
return downloadRootDir;
}




/**
* Gets the image download dir.
*
* @param context the context
* @return the image download dir
*/
public static String getImageDownloadDir(Context context) {
if(downloadRootDir == null){
initFileDir(context);
}
return imageDownloadDir;
}




/**
* Gets the file download dir.
*
* @param context the context
* @return the file download dir
*/
public static String getFileDownloadDir(Context context) {
if(downloadRootDir == null){
initFileDir(context);
}
return fileDownloadDir;
}




/**
* Gets the cache download dir.
*
* @param context the context
* @return the cache download dir
*/
public static String getCacheDownloadDir(Context context) {
if(downloadRootDir == null){
initFileDir(context);
}
return cacheDownloadDir;
}


/**
* Gets the db download dir.
*
* @param context the context
* @return the db download dir
*/
public static String getDbDownloadDir(Context context) {
if(downloadRootDir == null){
initFileDir(context);
}
return dbDownloadDir;
}




/**
* Gets the free sd space needed to cache.
*
* @return the free sd space needed to cache
*/
public static int getFreeSdSpaceNeededToCache() {
return freeSdSpaceNeededToCache;
}




}


(6)Dialog 相关的类


public class AbDialogUtil {

/** dialog tag*/
private static String mDialogTag = "dialog";

/**
* 全屏显示一个Fragment
* @param view
* @return
*/
public static AbSampleDialogFragment showFragment(View view) {

removeDialog(view);

FragmentActivity activity = (FragmentActivity)view.getContext();
        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        
        // 作为全屏显示,使用“content”作为fragment容器的基本视图,这始终是Activity的基本视图  
        ft.add(android.R.id.content, newFragment, mDialogTag).addToBackStack(null).commit(); 
        
        return newFragment;
    }

/**
* 显示一个自定义的对话框(有背景层)
* @param view
*/
public static AbSampleDialogFragment showDialog(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

/**
* 显示一个自定义的对话框(有背景层)
* @param view
* @param animEnter
* @param animExit
* @param animPopEnter
* @param animPopExit
* @return
*/
public static AbSampleDialogFragment showDialog(View view,int animEnter, int animExit, int animPopEnter, int animPopExit) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
        newFragment.setContentView(view);
        
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        ft.setCustomAnimations(animEnter,animExit,animPopEnter,animPopExit);
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

/**
* 显示一个自定义的对话框(有背景层)
* @param view
* @param onCancelListener
* @return
*/
public static AbSampleDialogFragment showDialog(View view,DialogInterface.OnCancelListener onCancelListener) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.setOnCancelListener(onCancelListener);
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

/**
* 显示一个自定义的对话框(有背景层)
* @param view
* @param animEnter
* @param animExit
* @param animPopEnter
* @param animPopExit
* @param onCancelListener
* @return
*/
public static AbSampleDialogFragment showDialog(View view,int animEnter, int animExit, int animPopEnter, int animPopExit,DialogInterface.OnCancelListener onCancelListener) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        ft.setCustomAnimations(animEnter,animExit,animPopEnter,animPopExit);
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.setOnCancelListener(onCancelListener);
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

/**
* 显示一个自定义的对话框(无背景层)
* @param view
*/
public static AbSampleDialogFragment showPanel(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }

/**
* 显示一个自定义的对话框(无背景层)
* @param view
* @param onCancelListener
* @return
*/
public static AbSampleDialogFragment showPanel(View view,DialogInterface.OnCancelListener onCancelListener) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);


        // Create and show the dialog.
        AbSampleDialogFragment newFragment = AbSampleDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
        newFragment.setContentView(view);
        FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
        newFragment.setOnCancelListener(onCancelListener);
        newFragment.show(ft, mDialogTag);
        return newFragment;
    }


/**
* 描述:对话框dialog (图标,标题,String内容).
* @param context
* @param icon
* @param title 对话框标题内容
* @param view  对话框提示内容
*/
public static AbAlertDialogFragment showAlertDialog(Context context,int icon,String title,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(icon,title,message,null,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
   // 指定一个过渡动画  
   ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 显示一个一般的对话框(图标,标题,string内容,确认,取消).
* @param context
* @param icon
* @param title 对话框标题内容
* @param message 对话框提示内容
* @param onClickListener 点击确认按钮的事件监听
*/
public static AbAlertDialogFragment showAlertDialog(Context context,int icon,String title,String message,AbDialogOnClickListener onClickListener) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(icon,title,message,null,onClickListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}


/**
* 显示一个一般的对话框(标题,String内容,确认,取消).
* @param context
* @param title 对话框标题内容
* @param message 对话框提示内容
* @param onClickListener 点击确认按钮的事件监听
*/
public static AbAlertDialogFragment showAlertDialog(Context context,String title,String message,AbDialogOnClickListener onClickListener) {
FragmentActivity activity = (FragmentActivity)context;
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,title,message,null,onClickListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 显示一个一般的对话框(View内容).
* @param view 对话框标题内容
*/
public static AbAlertDialogFragment showAlertDialog(View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,null,null,view,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 显示一个一般的对话框(String内容).
* @param context
* @param title 对话框标题内容
*/
public static AbAlertDialogFragment showAlertDialog(Context context,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,null,message,null,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 描述:对话框dialog (图标,标题,View内容).
* @param icon
* @param title 对话框标题内容
* @param view  对话框提示内容
*/
public static AbAlertDialogFragment showAlertDialog(int icon,String title,View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(icon,title,null,view,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 显示一个一般的对话框(图标,标题,View内容,确认,取消).
* @param icon
* @param title 对话框标题内容
* @param view 对话框提示内容
* @param onClickListener 点击确认按钮的事件监听
*/
public static AbAlertDialogFragment showAlertDialog(int icon,String title,View view,AbDialogOnClickListener onClickListener) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(icon,title,null,view,onClickListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 描述:对话框dialog (标题,View内容).
* @param title 对话框标题内容
* @param view  对话框提示内容
*/
public static AbAlertDialogFragment showAlertDialog(String title,View view) {
FragmentActivity activity = (FragmentActivity)view.getContext();
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,title,null,view,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 显示一个一般的对话框(标题,View内容,确认,取消).
* @param title 对话框标题内容
* @param view 对话框提示内容
* @param onClickListener 点击确认按钮的事件监听
*/
public static AbAlertDialogFragment showAlertDialog(String title,View view,AbDialogOnClickListener onClickListener) {
FragmentActivity activity = (FragmentActivity)view.getContext(); 
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,title,null,view,onClickListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}

/**
* 描述:对话框dialog (标题,String内容).
* @param context
* @param title 对话框标题内容
* @param view  对话框提示内容
*/
public static AbAlertDialogFragment showAlertDialog(Context context,String title,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbAlertDialogFragment newFragment = AbAlertDialogFragment.newInstance(0,title,message,null,null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
}


/**
* 描述:显示进度框.
* @param context the context
* @param indeterminateDrawable 用默认请写0
* @param message the message
*/
public static AbProgressDialogFragment showProgressDialog(Context context,int indeterminateDrawable,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbProgressDialogFragment newFragment = AbProgressDialogFragment.newInstance(indeterminateDrawable,message);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示加载框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
*/
public static AbLoadDialogFragment showLoadDialog(Context context,int indeterminateDrawable,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbLoadDialogFragment newFragment = AbLoadDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
   newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示加载框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
*/
public static AbLoadDialogFragment showLoadDialog(Context context,int indeterminateDrawable,String message,AbDialogOnLoadListener abDialogOnLoadListener) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbLoadDialogFragment newFragment = AbLoadDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(abDialogOnLoadListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
   newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示加载框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
*/
public static AbLoadDialogFragment showLoadPanel(Context context,int indeterminateDrawable,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbLoadDialogFragment newFragment = AbLoadDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
   newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示加载框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
* @param abDialogOnRefreshListener
*/
public static AbLoadDialogFragment showLoadPanel(Context context,int indeterminateDrawable,String message,AbDialogOnLoadListener abDialogOnLoadListener) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbLoadDialogFragment newFragment = AbLoadDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(abDialogOnLoadListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
   newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示刷新框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
* @param abDialogOnRefreshListener
*/
public static AbRefreshDialogFragment showRefreshDialog(Context context,int indeterminateDrawable,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbRefreshDialogFragment newFragment = AbRefreshDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
   newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示刷新框.
* @param context
* @param indeterminateDrawable
* @param message
* @param abDialogOnRefreshListener
* @return
*/
public static AbRefreshDialogFragment showRefreshDialog(Context context,int indeterminateDrawable,String message,AbDialogOnLoadListener abDialogOnLoadListener) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbRefreshDialogFragment newFragment = AbRefreshDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Holo_Light_Dialog);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(abDialogOnLoadListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示刷新框.
* @param context the context
* @param indeterminateDrawable
* @param message the message
*/
public static AbRefreshDialogFragment showRefreshPanel(Context context,int indeterminateDrawable,String message) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbRefreshDialogFragment newFragment = AbRefreshDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(null);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
    }

/**
* 描述:显示刷新框.
* @param context
* @param indeterminateDrawable
* @param message
* @param abDialogOnRefreshListener
* @return
*/
public static AbRefreshDialogFragment showRefreshPanel(Context context,int indeterminateDrawable,String message,AbDialogOnLoadListener abDialogOnLoadListener) {
FragmentActivity activity = (FragmentActivity)context; 
removeDialog(activity);
AbRefreshDialogFragment newFragment = AbRefreshDialogFragment.newInstance(DialogFragment.STYLE_NO_TITLE,android.R.style.Theme_Light_Panel);
newFragment.setIndeterminateDrawable(indeterminateDrawable);
newFragment.setMessage(message);
newFragment.setAbDialogOnLoadListener(abDialogOnLoadListener);
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
        // 指定一个过渡动画  
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);  
newFragment.show(ft, mDialogTag);
   return newFragment;
    }


/**
* 描述:移除Fragment.
* @param context the context
*/
public static void removeDialog(Context context){
try {
FragmentActivity activity = (FragmentActivity)context; 
FragmentTransaction ft = activity.getFragmentManager().beginTransaction();
       // 指定一个过渡动画  
       ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);  
Fragment prev = activity.getFragmentManager().findFragmentByTag(mDialogTag);
if (prev != null) {
   ft.remove(prev);
}
ft.addToBackStack(null);
   ft.commit();
} catch (Exception e) {
//可能有Activity已经被销毁的异常
e.printStackTrace();
}
}

/**
* 描述:移除Fragment和View
* @param view
*/
public static void removeDialog(View view){
removeDialog(view.getContext());
AbViewUtil.removeSelfFromParent(view);
}



}






(7) 日期处理类


public class AbDateUtil {

/** 时间日期格式化到年月日时分秒. */
public static final String dateFormatYMDHMS = "yyyy-MM-dd HH:mm:ss";

/** 时间日期格式化到年月日. */
public static final String dateFormatYMD = "yyyy-MM-dd";

/** 时间日期格式化到年月. */
public static final String dateFormatYM = "yyyy-MM";

/** 时间日期格式化到年月日时分. */
public static final String dateFormatYMDHM = "yyyy-MM-dd HH:mm";

/** 时间日期格式化到月日. */
public static final String dateFormatMD = "MM/dd";

/** 时分秒. */
public static final String dateFormatHMS = "HH:mm:ss";

/** 时分. */
public static final String dateFormatHM = "HH:mm";

/** 上午. */
    public static final String AM = "AM";


    /** 下午. */
    public static final String PM = "PM";




    /**
* 描述:String类型的日期时间转化为Date类型.
*
* @param strDate String形式的日期时间
* @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @return Date Date类型日期时间
*/
public static Date getDateByFormat(String strDate, String format) {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
Date date = null;
try {
date = mSimpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}

/**
* 描述:获取偏移之后的Date.
* @param date 日期时间
* @param calendarField Calendar属性,对应offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小时)
* @param offset 偏移(值大于0,表示+,值小于0,表示-)
* @return Date 偏移之后的日期时间
*/
public Date getDateByOffset(Date date,int calendarField,int offset) {
Calendar c = new GregorianCalendar();
try {
c.setTime(date);
c.add(calendarField, offset);
} catch (Exception e) {
e.printStackTrace();
}
return c.getTime();
}

/**
* 描述:获取指定日期时间的字符串(可偏移).
*
* @param strDate String形式的日期时间
* @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @param calendarField Calendar属性,对应offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小时)
* @param offset 偏移(值大于0,表示+,值小于0,表示-)
* @return String String类型的日期时间
*/
public static String getStringByOffset(String strDate, String format,int calendarField,int offset) {
String mDateTime = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
c.setTime(mSimpleDateFormat.parse(strDate));
c.add(calendarField, offset);
mDateTime = mSimpleDateFormat.format(c.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return mDateTime;
}

/**
* 描述:Date类型转化为String类型(可偏移).
*
* @param date the date
* @param format the format
* @param calendarField the calendar field
* @param offset the offset
* @return String String类型日期时间
*/
public static String getStringByOffset(Date date, String format,int calendarField,int offset) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
c.setTime(date);
c.add(calendarField, offset);
strDate = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}



/**
* 描述:Date类型转化为String类型.
*
* @param date the date
* @param format the format
* @return String String类型日期时间
*/
public static String getStringByFormat(Date date, String format) {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
String strDate = null;
try {
strDate = mSimpleDateFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}

/**
* 描述:获取指定日期时间的字符串,用于导出想要的格式.
*
* @param strDate String形式的日期时间,必须为yyyy-MM-dd HH:mm:ss格式
* @param format 输出格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @return String 转换后的String类型的日期时间
*/
public static String getStringByFormat(String strDate, String format) {
String mDateTime = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormatYMDHMS);
c.setTime(mSimpleDateFormat.parse(strDate));
SimpleDateFormat mSimpleDateFormat2 = new SimpleDateFormat(format);
mDateTime = mSimpleDateFormat2.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return mDateTime;
}

/**
* 描述:获取milliseconds表示的日期时间的字符串.
*
* @param milliseconds the milliseconds
* @param format  格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @return String 日期时间字符串
*/
public static String getStringByFormat(long milliseconds,String format) {
String thisDateTime = null;
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
thisDateTime = mSimpleDateFormat.format(milliseconds);
} catch (Exception e) {
e.printStackTrace();
}
return thisDateTime;
}

/**
* 描述:获取表示当前日期时间的字符串.
*
* @param format  格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @return String String类型的当前日期时间
*/
public static String getCurrentDate(String format) {
AbLogUtil.d(AbDateUtil.class, "getCurrentDate:"+format);
String curDateTime = null;
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
Calendar c = new GregorianCalendar();
curDateTime = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return curDateTime;


}


/**
* 描述:获取表示当前日期时间的字符串(可偏移).
*
* @param format 格式化字符串,如:"yyyy-MM-dd HH:mm:ss"
* @param calendarField Calendar属性,对应offset的值, 如(Calendar.DATE,表示+offset天,Calendar.HOUR_OF_DAY,表示+offset小时)
* @param offset 偏移(值大于0,表示+,值小于0,表示-)
* @return String String类型的日期时间
*/
public static String getCurrentDateByOffset(String format,int calendarField,int offset) {
String mDateTime = null;
try {
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
Calendar c = new GregorianCalendar();
c.add(calendarField, offset);
mDateTime = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return mDateTime;


}


/**
* 描述:计算两个日期所差的天数.
*
* @param milliseconds1 the milliseconds1
* @param milliseconds2 the milliseconds2
* @return int 所差的天数
*/
public static int getOffectDay(long milliseconds1, long milliseconds2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(milliseconds1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(milliseconds2);
//先判断是否同年
int y1 = calendar1.get(Calendar.YEAR);
int y2 = calendar2.get(Calendar.YEAR);
int d1 = calendar1.get(Calendar.DAY_OF_YEAR);
int d2 = calendar2.get(Calendar.DAY_OF_YEAR);
int maxDays = 0;
int day = 0;
if (y1 - y2 > 0) {
maxDays = calendar2.getActualMaximum(Calendar.DAY_OF_YEAR);
day = d1 - d2 + maxDays;
} else if (y1 - y2 < 0) {
maxDays = calendar1.getActualMaximum(Calendar.DAY_OF_YEAR);
day = d1 - d2 - maxDays;
} else {
day = d1 - d2;
}
return day;
}

/**
* 描述:计算两个日期所差的小时数.
*
* @param date1 第一个时间的毫秒表示
* @param date2 第二个时间的毫秒表示
* @return int 所差的小时数
*/
public static int getOffectHour(long date1, long date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
int h1 = calendar1.get(Calendar.HOUR_OF_DAY);
int h2 = calendar2.get(Calendar.HOUR_OF_DAY);
int h = 0;
int day = getOffectDay(date1, date2);
h = h1-h2+day*24;
return h;
}

/**
* 描述:计算两个日期所差的分钟数.
*
* @param date1 第一个时间的毫秒表示
* @param date2 第二个时间的毫秒表示
* @return int 所差的分钟数
*/
public static int getOffectMinutes(long date1, long date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeInMillis(date2);
int m1 = calendar1.get(Calendar.MINUTE);
int m2 = calendar2.get(Calendar.MINUTE);
int h = getOffectHour(date1, date2);
int m = 0;
m = m1-m2+h*60;
return m;
}


/**
* 描述:获取本周一.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getFirstDayOfWeek(String format) {
return getDayOfWeek(format,Calendar.MONDAY);
}


/**
* 描述:获取本周日.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getLastDayOfWeek(String format) {
return getDayOfWeek(format,Calendar.SUNDAY);
}


/**
* 描述:获取本周的某一天.
*
* @param format the format
* @param calendarField the calendar field
* @return String String类型日期时间
*/
private static String getDayOfWeek(String format,int calendarField) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
int week = c.get(Calendar.DAY_OF_WEEK);
if (week == calendarField){
strDate = mSimpleDateFormat.format(c.getTime());
}else{
int offectDay = calendarField - week;
if (calendarField == Calendar.SUNDAY) {
offectDay = 7-Math.abs(offectDay);

c.add(Calendar.DATE, offectDay);
strDate = mSimpleDateFormat.format(c.getTime());
}
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}

/**
* 描述:获取本月第一天.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getFirstDayOfMonth(String format) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
//当前月的第一天
c.set(GregorianCalendar.DAY_OF_MONTH, 1);
strDate = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return strDate;


}


/**
* 描述:获取本月最后一天.
*
* @param format the format
* @return String String类型日期时间
*/
public static String getLastDayOfMonth(String format) {
String strDate = null;
try {
Calendar c = new GregorianCalendar();
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(format);
// 当前月的最后一天
c.set(Calendar.DATE, 1);
c.roll(Calendar.DATE, -1);
strDate = mSimpleDateFormat.format(c.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return strDate;
}





/**
* 描述:获取表示当前日期的0点时间毫秒数.
*
* @return the first time of day
*/
public static long getFirstTimeOfDay() {
Date date = null;
try {
String currentDate = getCurrentDate(dateFormatYMD);
date = getDateByFormat(currentDate+" 00:00:00",dateFormatYMDHMS);
return date.getTime();
} catch (Exception e) {
}
return -1;
}

/**
* 描述:获取表示当前日期24点时间毫秒数.
*
* @return the last time of day
*/
public static long getLastTimeOfDay() {
Date date = null;
try {
String currentDate = getCurrentDate(dateFormatYMD);
date = getDateByFormat(currentDate+" 24:00:00",dateFormatYMDHMS);
return date.getTime();
} catch (Exception e) {
}
return -1;
}

/**
* 描述:判断是否是闰年()
* <p>(year能被4整除 并且 不能被100整除) 或者 year能被400整除,则该年为闰年.
*
* @param year 年代(如2012)
* @return boolean 是否为闰年
*/
public static boolean isLeapYear(int year) {
if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
return true;
} else {
return false;
}
}

/**
* 描述:根据时间返回格式化后的时间的描述.
* 小于1小时显示多少分钟前  大于1小时显示今天+实际日期,大于今天全部显示实际时间
*
* @param strDate the str date
* @param outFormat the out format
* @return the string
*/
public static String formatDateStr2Desc(String strDate,String outFormat) {

DateFormat df = new SimpleDateFormat(dateFormatYMDHMS);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
try {
c2.setTime(df.parse(strDate));
c1.setTime(new Date());
int d = getOffectDay(c1.getTimeInMillis(), c2.getTimeInMillis());
if(d==0){
int h = getOffectHour(c1.getTimeInMillis(), c2.getTimeInMillis());
if(h>0){
return "今天"+getStringByFormat(strDate,dateFormatHM);
//return h + "小时前";
}else if(h<0){
//return Math.abs(h) + "小时后";
}else if(h==0){
int m = getOffectMinutes(c1.getTimeInMillis(), c2.getTimeInMillis());
if(m>0){
return m + "分钟前";
}else if(m<0){
//return Math.abs(m) + "分钟后";
}else{
return "刚刚";
}
}

}else if(d>0){
if(d == 1){
//return "昨天"+getStringByFormat(strDate,outFormat);
}else if(d==2){
//return "前天"+getStringByFormat(strDate,outFormat);
}
}else if(d<0){
if(d == -1){
//return "明天"+getStringByFormat(strDate,outFormat);
}else if(d== -2){
//return "后天"+getStringByFormat(strDate,outFormat);
}else{
   //return Math.abs(d) + "天后"+getStringByFormat(strDate,outFormat);
}
}

String out = getStringByFormat(strDate,outFormat);
if(!AbStrUtil.isEmpty(out)){
return out;
}
} catch (Exception e) {
}

return strDate;
}


/**
* 取指定日期为星期几.
*
* @param strDate 指定日期
* @param inFormat 指定日期格式
* @return String   星期几
*/
    public static String getWeekNumber(String strDate,String inFormat) {
      String week = "星期日";
      Calendar calendar = new GregorianCalendar();
      DateFormat df = new SimpleDateFormat(inFormat);
      try {
  calendar.setTime(df.parse(strDate));
 } catch (Exception e) {
 return "错误";
 }
      int intTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1;
      switch (intTemp){
        case 0:
          week = "星期日";
          break;
        case 1:
          week = "星期一";
          break;
        case 2:
          week = "星期二";
          break;
        case 3:
          week = "星期三";
          break;
        case 4:
          week = "星期四";
          break;
        case 5:
          week = "星期五";
          break;
        case 6:
          week = "星期六";
          break;
      }
      return week;
    }
    
    /**
     * 根据给定的日期判断是否为上下午.
     *
     * @param strDate the str date
     * @param format the format
     * @return the time quantum
     */
    public static String getTimeQuantum(String strDate, String format) {
        Date mDate = getDateByFormat(strDate, format);
        int hour  = mDate.getHours();
        if(hour >=12)
           return "PM";
        else
           return "AM";
    }
    
    /**
     * 根据给定的毫秒数算得时间的描述.
     *
     * @param milliseconds the milliseconds
     * @return the time description
     */
    public static String getTimeDescription(long milliseconds) {
        if(milliseconds > 1000){
            //大于一分
            if(milliseconds/1000/60>1){
                long minute = milliseconds/1000/60;
                long second = milliseconds/1000%60;
                return minute+"分"+second+"秒";
            }else{
                //显示秒
                return milliseconds/1000+"秒";
            }
        }else{
            return milliseconds+"毫秒";
        }
    }

/**
     * The main method.
     *
     * @param args the arguments
     */
    public static void main(String[] args) {
System.out.println(formatDateStr2Desc("2012-3-2 12:2:20","MM月dd日  HH:mm"));
}


}

0 0
原创粉丝点击