Android全面的項目工具類,我替你總結(jié)了

在平時的項目開發(fā)中,總有那么一個包是必不可少的。我要說的就是utils包。沒了這個,代碼怎么公用,功能怎么公用,所謂磨刀不誤砍柴工,充分的準(zhǔn)備是快速開發(fā)的前提。utils包對項目而言,就像人體的肺,沒了肺,怎么呼吸?今天,老夫就將我珍藏多年的...,不是,積累的工具類我替你總結(jié)了,看你手指精奇,是個寫程序的奇才,拿走不謝,持續(xù)更新中。

github代碼直通車

啥也不說了,先上效果圖:


文件列表

1.Bitmap處理工具類:包括bitmap保存本地;bytebuffer轉(zhuǎn)bitmap;對bitmap高效高斯模糊;bitmap二次采樣;bitmap圖片壓縮;

public class BitmapUtils {

    /**
     * 將bitmap保存為文件
     * @param bitmap
     * @param file
     * @return
     */
    public static boolean bitmapToFile(Bitmap bitmap, File file) {
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 將byteBuffer轉(zhuǎn)為Bitmap
     * @param byteBuffer
     * @param width
     * @param height
     * @return
     */
    public static Bitmap byteBufferToBitmap(ByteBuffer byteBuffer, int width, int height) {
        IntBuffer intBuffer = byteBuffer.asIntBuffer();
        final int[] ret = new int[byteBuffer.limit() / 4];
        IntBuffer retBuffer = IntBuffer.wrap(ret);
        retBuffer.put(intBuffer);

        for (int i = 0; i < ret.length; i++) {
            int src = ret[i];
            int dest = (src & 0xFF) << 24 | (src & 0xFF000000) >> 8 | (src & 0xFF0000) >> 8 | (src & 0xFF00) >> 8;
            ret[i] = dest;
        }

        Bitmap bitmap = Bitmap.createBitmap(ret, width, height, Bitmap.Config.ARGB_8888);
        return bitmap;
    }

    /**
     * 高效率Bitmap高斯模糊
     * 還需在build.gradle加入 defaultConfig {
        renderscriptTargetApi 19
        renderscriptSupportModeEnabled true
     }
     * @param context
     * @param ivBlurBg
     * @param bitmap
     * param scaleRatio  bitmap分辨率縮小比例,計算速度更快,范圍 1-10
     *
     */
    public static void bitmapBlur(Context context, ImageView ivBlurBg, Bitmap bitmap, int scaleRatio){
        int x = (int) ivBlurBg.getX();
        int y = (int) ivBlurBg.getY();
        int bitmapX = bitmap.getWidth();
        int bitmapY = bitmap.getHeight();
        Bitmap bitmapNew = Bitmap.createBitmap(bitmap,x,y,bitmapX-x,bitmapY-y);

        if(bitmap != null){
            Bitmap overlay = Bitmap.createScaledBitmap(bitmapNew, bitmapNew.getWidth() / scaleRatio, bitmapNew.getHeight() / scaleRatio, false);
            overlay = handleGlassblur(context,overlay,15);
            ivBlurBg.setImageBitmap(overlay);
        }
        bitmap.recycle();
    }

    public static Bitmap handleGlassblur(Context context, Bitmap originBitmap, int radius){
        RenderScript renderScript = RenderScript.create(context);
        Allocation input = Allocation.createFromBitmap(renderScript,originBitmap);
        Allocation output = Allocation.createTyped(renderScript,input.getType());
        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        scriptIntrinsicBlur.setRadius(radius);
        scriptIntrinsicBlur.setInput(input);
        scriptIntrinsicBlur.forEach(output);
        output.copyTo(originBitmap);

        return originBitmap;
    }

    /**
     * 根據(jù)指定的寬、高,對圖片進行二次采樣
     * @param bytes
     * @return
     */
    public static Bitmap ScaleBitmap(byte[] bytes,int width,int height){
        //獲取圖片的解碼參數(shù)設(shè)置
        BitmapFactory.Options options = new BitmapFactory.Options();
        //設(shè)置為true僅僅解碼圖片的邊緣
        options.inJustDecodeBounds = true;
        //對圖片進行解碼,如果指定了inJustDecodeBounds=true,decodeByteArray將返回為空
        BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;

        int sampleSizeX = width/outWidth;
        int sampleSizeY = height/outHeight;
        int simpleSize = sampleSizeX < sampleSizeY ? sampleSizeX : sampleSizeY;
        //設(shè)置inJustDecodeBounds為false重新將圖片讀進內(nèi)存中
        options.inJustDecodeBounds = false;
        //實際要進行縮放的比例
        options.inSampleSize = simpleSize;
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    }

    /**
     * 圖片質(zhì)量壓縮
     * @param bitmap  需要質(zhì)量壓縮的圖片
     * @param size    指定最大要壓縮成的大小,單位為k
     * @return
     */
    public static Bitmap compressBitmap(Bitmap bitmap,int size){
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        //將壓縮后的數(shù)據(jù)放入bos中
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
        int quality = 100;
        while(bos.toByteArray().length / 1024 > size){
            //循環(huán)判斷如果壓縮后的圖片大于100k,則清空bos,質(zhì)量壓縮比減小10%
            bos.reset();
            quality -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG,quality,bos);
        }
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        //通過字節(jié)輸入流轉(zhuǎn)為bitmap
        return BitmapFactory.decodeStream(bis,null,null);
    }

}

2.萬能接口回調(diào)類,一個類能回調(diào)任何數(shù)據(jù)類型,從此不需要再創(chuàng)建其他單一回調(diào)接口。

public abstract class CallBackimpl implements IcallBack{

    @Override
    public void callBack(List datas) {

    }

    @Override
    public void callBack(List list, boolean charge) {

    }

    @Override
    public void callBack(String str) {

    }

    @Override
    public void callBack(String str, int code) {

    }

    @Override
    public void callBack(byte[] bytes) {

    }

    @Override
    public void callBack(Bitmap bitmap) {

    }

    @Override
    public void confirmHandle() {

    }

    @Override
    public void callBack(int progress) {

    }

    @Override
    public void callBack(float num) {

    }

    @Override
    public void callBack(int page,int subpage) {

    }

    @Override
    public void callBack(boolean boo) {

    }

    @Override
    public void callBack(JSONObject obj) {

    }

    @Override
    public void callBack(String... args) {

    }

    @Override
    public void onFail() {

    }
}

3.異常崩潰處理類:當(dāng)程序發(fā)生未處理異常時,該類將版本號,版本名,設(shè)備號,Android版本,生產(chǎn)信息進行記錄日志并發(fā)送至服務(wù)器。

public class CrashHandler implements Thread.UncaughtExceptionHandler{

    private Thread.UncaughtExceptionHandler exceptionHandler;
    private MyApp myApp;
    /** 錯誤日志保存名稱 */
    private Map<String, String> infos = new HashMap<>();
    /** 錯誤日志文件名 */
    private final String LOGFILE_NAME = FileUtils.getCacheDir() + "crash.txt";

    public CrashHandler(MyApp myApp){
        exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        this.myApp = myApp;
    }

    /**
     * 當(dāng)未捕獲的異常發(fā)生時會傳入此方中處理
     * @param thread
     * @param ex
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if(!handException(ex) && exceptionHandler != null){
            exceptionHandler.uncaughtException(thread,ex);
        }else{
            //異常處理并結(jié)束程序
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    /**
     * 異常處理方法,處理了返回true,未處理返回false
     * @param ex  異常
     * @return
     */
    private boolean handException(final Throwable ex){
        if(ex == null) return true;
        ex.printStackTrace();
        Toast.makeText(myApp, "應(yīng)用發(fā)生異常,即將退出!", Toast.LENGTH_LONG).show();
        collectVersionInfo(myApp);
        collectDeviceInfo();
        saveCrashInfoToFile(ex);
        return true;
    }

    /**
     * 收集版本信息信息
     * @param context
     */
    private void collectVersionInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存錯誤日志到文件中
     * @param ex
     */
    private void saveCrashInfoToFile(Throwable ex) {
        //換行符
        String lineFeed = "\r\n";
        StringBuffer sb = new StringBuffer();
        for(Map.Entry<String,String> entry: infos.entrySet()){
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + lineFeed);
        }

        StackTraceElement[] stack = ex.getStackTrace();
        String message = ex.getMessage();
        //準(zhǔn)備錯誤日志文件
        File logFile = new File(LOGFILE_NAME);
        if(!logFile.getParentFile().exists()){
            logFile.getParentFile().mkdirs();
        }
        //寫入錯誤日志
        FileWriter writer = null;
        try {
            //獲取當(dāng)前時間、異常message信息,異常棧跟蹤信息寫入日志文件
            writer = new FileWriter(logFile);
            writer.write("創(chuàng)建時間:" + StrUtils.currentTime("yy-MM-dd hh:mm:ss").toString()+lineFeed+lineFeed);
            writer.write(message+lineFeed);
            for(int i=0;i<stack.length;i++){
                writer.write(stack[i].toString() + lineFeed);
            }
            writer.write(lineFeed);
            writer.write(sb.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != writer){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 根據(jù)Build類搜集設(shè)備信息
     */
    private void collectDeviceInfo(){
        Field[] fields = Build.class.getDeclaredFields();
        for(Field field : fields){
            try {
                field.setAccessible(true);
                infos.put(field.getName(),field.get(null).toString());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

}

4.簡單的下載工具類,也可以用封裝的okhttp下載工具,親測都好用。

public class DownLoadUtils {

    /**
     * 帶最大值,進度值,結(jié)果的下載
     * @param url
     * @param maxLen
     * @param progress
     * @param result
     */
    public static void downloadFile(final String url, final CallBackimpl maxLen, final CallBackimpl progress, final CallBackimpl result){
        new Thread(){
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    if(conn.getResponseCode() == 200){
                        InputStream inputStream = conn.getInputStream();
                        byte[] bytes = new byte[1024 * 500];
                        int len = -1;
                        maxLen.callBack(conn.getContentLength());
                        int currentLen = 0;  //當(dāng)前進度
                        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while((len = inputStream.read(bytes)) != -1){
                            baos.write(bytes,0,len);
                            currentLen+=len;
                            progress.callBack(currentLen);
                        }
                        result.callBack(baos.toByteArray());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 下載方法
     * @param url  地址
     * @param callBackimpl  下載完成回調(diào)
     */
    public static void downloadFile(final String url, final String fileName, final CallBackimpl callBackimpl){
        new Thread(){
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    if(conn.getResponseCode() == 200){
                        InputStream inputStream = conn.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len = -1;
                        File file = new File(fileName);
                        if(!file.getParentFile().exists()){
                            file.getParentFile().mkdirs();
                        }
                        FileOutputStream fos = new FileOutputStream(fileName);
                        while((len = inputStream.read(bytes)) != -1){
                            fos.write(bytes, 0, len);
                        }
                        fos.close();
                        callBackimpl.confirmHandle();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}

5.文件操作工具類:包括判斷sd卡可用;獲取項目根目錄;數(shù)據(jù)寫文件;獲取文件大??;刪除文件;從raw資源文件讀取到流;判斷空間是否足夠。

public class FileUtils {

    /**
     * 判斷sd卡是否可用
     * @return
     */
    public static boolean isHaveSDcard(){
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 設(shè)置App緩存根目錄
     * @return
     */
    public static String getCacheDir(){
        String sdDir = null;
        if(isHaveSDcard()){
            sdDir = Environment.getExternalStorageDirectory().getPath() + "/AppName/";
        }
        return sdDir;
    }

    /**
     * 將data數(shù)據(jù)寫入指定文件里
     * @param data
     * @param fileName
     * @throws IOException
     */
    public static void saveFileToSDcard(byte[] data,String fileName){
        String filePath = getCacheDir();
        File dir = new File(filePath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(filePath+"/"+fileName);
        try {
            if(!file.exists()){
                file.createNewFile();
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bos.write(data);
                bos.flush();
                bos.close();
                fos.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 遞歸累計獲取文件/文件夾大小
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSize(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    /**
     * 遞歸刪除文件/文件夾
     * @param file
     */
    public static void delFile(File file){
        if(file.isFile()){
            file.delete();
        }else if(file.isDirectory()){
            File file1s[] = file.listFiles();
            for(int i=0;i<file1s.length;i++){
                delFile(file1s[i]);
            }
            file.delete();
        }
    }

    /**
     * 從raw資源文件中獲取
     *
     * @return
     */
    private String getAddress(Context context,int rawRes) {
        StringBuilder sb = new StringBuilder();
        try {
            InputStream inputStream = context.getResources().openRawResource(rawRes);
            byte[] buffer = new byte[1024];
            while (inputStream.read(buffer) != -1) {
                sb.append(new String(buffer, "UTF-8"));
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 是否有足夠的空間
     * @param size in B
     * @return
     */
    public boolean haveSpace(Context context, int size){
        //判斷sdcard存儲空間是否滿足文件的存儲
        File sdcard_filedir = Environment.getExternalStorageDirectory();//得到sdcard的目錄作為一個文件對象
        long usableSpace = sdcard_filedir.getUsableSpace();//獲取文件目錄對象剩余空間
        long totalSpace = sdcard_filedir.getTotalSpace();

        //將一個long類型的文件大小格式化成用戶可以看懂的M,G字符串
        String usableSpace_str = Formatter.formatFileSize(context, usableSpace);
        String totalSpace_str = Formatter.formatFileSize(context, totalSpace);

        if(usableSpace < size+20*1024*1024){//判斷剩余空間是否小于size
            Toast.makeText(context, "sdcard剩余空間不足,無法滿足下載;剩余空間為:"+usableSpace_str,Toast.LENGTH_SHORT).show();
            return false;
        }else{
            return true;
        }
    }

}

6.日志管理工具類:通過設(shè)置全局變量LOGLEVEL的值進行開啟或關(guān)閉log,如-1開啟,6關(guān)閉;

public class LogUtils {
    private static int LOGLEVEL = 6;
    private static int VERBOSE = 1;
    private static int DEBUG = 2;
    private static int INFO = 3;
    private static int WARN = 4;
    private static int ERROR = 5;

    public static void v(String tag, String msg){
        if(LOGLEVEL > VERBOSE) Log.v(tag,msg);
    }

    public static void d(String tag, String msg){
        if(LOGLEVEL > DEBUG) Log.d(tag, msg);
    }

    public static void i(String tag, String msg){
        if(LOGLEVEL > INFO) Log.i(tag, msg);
    }

    public static void w(String tag, String msg){
        if(LOGLEVEL > WARN) Log.w(tag, msg);
    }

    public static void e(String tag, String msg){
        if(LOGLEVEL > ERROR) Log.e(tag,msg);
    }

}

7.網(wǎng)絡(luò)判斷工具類:包括網(wǎng)絡(luò)是否可用;獲取當(dāng)前網(wǎng)絡(luò)類型;

public class NetWorkUtils {

    /**
     * 判斷網(wǎng)路是否可用
     * @param context
     * @return
     */
    public static boolean isNetWorkAvailable(Context context){
        ConnectivityManager manager  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //獲取所有可用的網(wǎng)絡(luò)連接信息
        NetworkInfo[] infos = manager.getAllNetworkInfo();
        if(null != infos){
            for(NetworkInfo info : infos){
                if(info.getState() == NetworkInfo.State.CONNECTED){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 返回網(wǎng)絡(luò)類型
     * @return
     */
    public static NetWorkState getNetworkState(Context context){
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(manager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI){
            return NetWorkState.WIFI;
        }else if(manager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE){
            return NetWorkState.MOBILE;
        }else {
            return NetWorkState.NONE;
        }
    }

    public enum NetWorkState {
        WIFI,MOBILE,NONE
    }
}

8.尺寸工具類:包括獲取屏幕寬高,密度,dp、px互轉(zhuǎn),px、sp互轉(zhuǎn)。

public class ScreenUtils {

    /**
     * 獲取屏幕寬度
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context){
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 獲取屏幕高度
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context){
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 獲取屏幕密度
     * @param context
     * @return
     */
    public static float getScreenDensity(Context context){
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * dp轉(zhuǎn)px
     * @param context
     * @param dpValue
     * @return
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px轉(zhuǎn)dp
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * sp轉(zhuǎn)px
     * @param context
     * @param spVal
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px轉(zhuǎn)sp
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

}

9.SharedPreferences存取操作類:傳任意類型自動能存取數(shù)據(jù)。

public class SharedPrefUtils {
    public static final String SHAREFRE_FILENAME = "sharefile";

    /**
     * 保存數(shù)據(jù)到共享參數(shù)中
     * @param context
     * @param key  鍵
     * @param object  值
     */
    public static void setParams(Context context, String key, Object object){

        SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREFRE_FILENAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        if(object instanceof String){
            editor.putString(key, (String) object);
        }else if(object instanceof Integer){
            editor.putInt(key, (Integer) object);
        }else if(object instanceof Boolean){
            editor.putBoolean(key, (Boolean) object);
        }else if(object instanceof Float){
            editor.putFloat(key, (Float) object);
        }else if(object instanceof Long){
            editor.putLong(key, (Long) object);
        }

        editor.commit();
    }

    /**
     *  獲取共享參數(shù),根據(jù)默認數(shù)據(jù)類型獲取相對應(yīng)key的值
     * @param context
     * @param key  鍵
     * @param defaultObject  默認值
     * @return
     */
    public static Object getParams(Context context, String key, Object defaultObject){

        SharedPreferences sharedPreferences = context.getSharedPreferences(SHAREFRE_FILENAME, Context.MODE_PRIVATE);

        if(defaultObject instanceof String){
            return sharedPreferences.getString(key, (String) defaultObject);
        }else if(defaultObject instanceof Integer){
            return sharedPreferences.getInt(key, (Integer) defaultObject);
        }else if(defaultObject instanceof Boolean){
            return sharedPreferences.getBoolean(key, (Boolean) defaultObject);
        }else if(defaultObject instanceof Float){
            return sharedPreferences.getFloat(key, (Float) defaultObject);
        }else if(defaultObject instanceof Long){
            return sharedPreferences.getLong(key, (Long) defaultObject);
        }
        return null;
    }

}

10.字符串操作工具類:獲取時間;時間戳轉(zhuǎn)日期;保留指定位小數(shù)點;字符串判空等。

public class StrUtils {

    private static String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
    private static String phonePatter = "^1\\d{10}$";

    /** 獲得當(dāng)前時間 */
    public static CharSequence currentTime(CharSequence inFormat) {
        return DateFormat.format(inFormat, System.currentTimeMillis());
    }

    /**
     * 時間戳轉(zhuǎn) yyyy年MM月dd日 HH:mm
     * @param longTime
     * @return
     */
    public static String getDateTime(String longTime){
        long time = Long.valueOf(longTime)*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        return  sdf.format(new Date(time));
    }

    /**
     * 時間戳轉(zhuǎn) yyy年MM月dd日 HH:mm:ss
     * @param longTime
     * @return
     */
    public static String getDateSec(String longTime){
        long time = Long.valueOf(longTime)*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        return  sdf.format(new Date(time));
    }

    /**
     * 時間戳轉(zhuǎn) MM月dd日 HH:mm
     * @param longTime
     * @return
     */
    public static String getDateMinite(String longTime){
        long time = Long.valueOf(longTime)*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        return  sdf.format(new Date(time));
    }

    /**
     * 時間戳轉(zhuǎn) yyyy-MM-dd HH:mm
     * @param longTime
     * @return
     */
    public static String getTime(String longTime){
        long time = Long.valueOf(longTime)*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return  sdf.format(new Date(time));
    }

    /**
     * 時間戳轉(zhuǎn) yyyy-MM-dd
     * @param longTime
     * @return
     */
    public static String getdate(String longTime){
        long time = Long.valueOf(longTime)*1000;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(new Date(time));
    }

    /**
     * 日期轉(zhuǎn)時間戳
     * @return
     */
    public static String getTimeStamp(String dateTime, String format){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            return String.valueOf(simpleDateFormat.parse(dateTime).getTime()/1000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 從短信中截取驗證碼
     * @param patternContent
     * @return
     */
    public static String patternCode(String patternContent) {
        if (TextUtils.isEmpty(patternContent)) {
            return null;
        }
        Pattern p = Pattern.compile(patternCoder);
        Matcher matcher = p.matcher(patternContent);
        if (matcher.find()) {
            return matcher.group();
        }
        return null;
    }

    /**
     * 檢測手機號碼
     * @param patternContent
     * @return
     */
    public static boolean checkPhone(String patternContent){
        Pattern pattern = Pattern.compile(phonePatter);
        Matcher matcher =  pattern.matcher(patternContent);
        return matcher.matches();
    }

    /**
     * 保留指定小數(shù)點位數(shù),format傳 "0.0" "0.00"形式分別保存一位,兩位小數(shù)
     * @param num
     * @param format
     * @return
     */
    public static String doubleRound(double num, String format){
        DecimalFormat df = new DecimalFormat(format);
        return df.format(num);
    }

    /**
     * 判斷單個字符串是否為空
     * @param str
     * @return
     */
    public static boolean isStr(String str){
        if(null != str && str.length() != 0) return true;
        return false;
    }

    /**
     * 判斷多個字符串是否為空
     * @param str
     * @return
     */
    public static boolean isArrStr(String... str){
        if(null == str) return false;
        for(String s : str){
            if(!isStr(s)) return false;
        }
        return true;
    }
}

哇塞,你看完了,做做眼保健操放松放松眼睛吧。好啦,本期節(jié)目就到此為止了,下期節(jié)目再見!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容