Android常用工具类

先推荐一款工具类框架
http://www.jianshu.com/p/72494773aace
compile 'com.blankj:utilcode:1.9.6'
屏幕尺寸相关
public class DensityUtils {
    public static int dip2px(Context context, float dipValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }

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

    //获取屏幕宽高
    public static Point getScreenMetrics(Context context){
        DisplayMetrics dm =context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);

    }
    public static int getScreenWidth(Context context){
        DisplayMetrics dm =context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        return w_screen;
    }

    public static int getScreenHeight(Context context){
        DisplayMetrics dm =context.getResources().getDisplayMetrics();
        int h_screen = dm.heightPixels;
        return h_screen;
    }
    //获取长宽比
    public static float getScreenRate(Context context){
        Point P = getScreenMetrics(context);
        float H = P.y;
        float W = P.x;
        return (H/W);
    }
}
图片相关
public class ImageUtils {
    //bitmap 和byte[]的互相转换
    public static byte[] bitmapToByte(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, o);
        return o.toByteArray();
    }
    public static Bitmap byteToBitmap(byte[] b) {
        return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);
    }

    //bitmap和drawable的互相转换
    public static Bitmap drawableToBitmap(Drawable drawable) {
        return drawable == null ? null : ((BitmapDrawable)drawable).getBitmap();
    }
    @Deprecated
    public static Drawable bitmapToDrawable(Bitmap bitmap) {
        return bitmap == null ? null : new BitmapDrawable(bitmap);
    }
    public static Drawable bitmapToDrawable(Resources res,Bitmap bitmap) {
        return bitmap == null ? null : new BitmapDrawable(res,bitmap);
    }

    //drawable和byte[]的互相转换
    public static byte[] drawableToByte(Drawable d) {
        return bitmapToByte(drawableToBitmap(d));
    }
    public static Drawable byteToDrawable(byte[] b) {
        return bitmapToDrawable(byteToBitmap(b));
    }

    //bitmap的放大和缩小
    public static Bitmap scaleImageTo(Bitmap bitmap, int newWidth, int newHeight) {
        return scaleImage(bitmap, (float) newWidth / bitmap.getWidth(), (float) newHeight / bitmap.getHeight());
    }

    public static Bitmap scaleImage(Bitmap bitmap, float scaleWidth, float scaleHeight) {
        if (bitmap == null) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }
}
Log相关
public class LogUtils {
    //log开关
    private static boolean isShowLog = true;
    //当前优先级的标志位,只有大于等于该优先级的log会被打印
    private static int priority = 1;
    public static final String COLON = ":";
    public static final String TAG = "meee";
    public static final String VERTICAL = "|";
    public static final int PRINTLN = 1;
    public static final int VERBOSE = 2;
    public static final int DEBUG = 3;
    public static final int INFO = 4;
    public static final int WARN = 5;
    public static final int ERROR = 6;
    public static final int ASSERT = 7;
    public static final String TAG_FORMAT = "%s.%s(L:%d)";

    public static void setShowLog(boolean isShowLog) {
        LogUtils.isShowLog = isShowLog;
    }
    public static boolean isShowLog() {
        return isShowLog;
    }

    public static int getPriority() {
        return priority;
    }
    public static void setPriority(int priority) {
        LogUtils.priority = priority;
    }

    //堆栈相关
    private static String generateTag(StackTraceElement caller) {
        String tag = TAG_FORMAT;
        String callerClazzName = caller.getClassName();
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
        tag = String.format(tag,new Object[] { callerClazzName, caller.getMethodName(),Integer.valueOf(caller.getLineNumber()) });
        return new StringBuilder().append(TAG).append(VERTICAL).append(tag).toString();
    }
    public static StackTraceElement getStackTraceElement(int n) {
        return Thread.currentThread().getStackTrace()[n];
    }
    private static String getCallerStackLogTag(){
        return generateTag(getStackTraceElement(5));
    }
    private static String getStackTraceString(Throwable t){
        return Log.getStackTraceString(t);
    }

    //Log.v
    public static void v(String msg) {
        if (isShowLog && priority <= VERBOSE)
            Log.v(getCallerStackLogTag(), String.valueOf(msg));

    }

    public static void v(Throwable t) {
        if (isShowLog && priority <= VERBOSE)
            Log.v(getCallerStackLogTag(), getStackTraceString(t));
    }

    public static void v(String msg,Throwable t) {
        if (isShowLog && priority <= VERBOSE)
            Log.v(getCallerStackLogTag(), String.valueOf(msg), t);
    }

    //debug
    public static void d(String msg) {
        if (isShowLog && priority <= DEBUG)
            Log.d(getCallerStackLogTag(), String.valueOf(msg));
    }
    public static void d(Throwable t) {
        if (isShowLog && priority <= DEBUG)
            Log.d(getCallerStackLogTag(), getStackTraceString(t));
    }
    public static void d(String msg,Throwable t) {
        if (isShowLog && priority <= DEBUG)
            Log.d(getCallerStackLogTag(), String.valueOf(msg), t);
    }

    //Log.i
    public static void i(String msg) {
        if (isShowLog && priority <= INFO)
            Log.i(getCallerStackLogTag(), String.valueOf(msg));
    }

    public static void i(Throwable t) {
        if (isShowLog && priority <= INFO)
            Log.i(getCallerStackLogTag(), getStackTraceString(t));
    }

    public static void i(String msg,Throwable t) {
        if (isShowLog && priority <= INFO)
            Log.i(getCallerStackLogTag(), String.valueOf(msg), t);
    }


    //warning
    public static void w(String msg) {
        if (isShowLog && priority <= WARN)
            Log.w(getCallerStackLogTag(), String.valueOf(msg));
    }
    public static void w(Throwable t) {
        if (isShowLog && priority <= WARN)
            Log.w(getCallerStackLogTag(), getStackTraceString(t));
    }
    public static void w(String msg,Throwable t) {
        if (isShowLog && priority <= WARN)
            Log.w(getCallerStackLogTag(), String.valueOf(msg), t);
    }

    //error
    public static void e(String msg) {
        if (isShowLog && priority <= ERROR)
            Log.e(getCallerStackLogTag(), String.valueOf(msg));
    }

    public static void e(Throwable t) {
        if (isShowLog && priority <= ERROR)
            Log.e(getCallerStackLogTag(), getStackTraceString(t));
    }

    public static void e(String msg,Throwable t) {
        if (isShowLog && priority <= ERROR)
            Log.e(getCallerStackLogTag(), String.valueOf(msg), t);
    }
    //wtf
    public static void wtf(String msg) {
        if (isShowLog && priority <= ASSERT)
            Log.wtf(getCallerStackLogTag(), String.valueOf(msg));
    }
    public static void wtf(Throwable t) {
        if (isShowLog && priority <= ASSERT)
            Log.wtf(getCallerStackLogTag(), getStackTraceString(t));
    }
    public static void wtf(String msg,Throwable t) {
        if (isShowLog && priority <= ASSERT)
            Log.wtf(getCallerStackLogTag(), String.valueOf(msg), t);
    }

    //print
    public static void print(String msg) {
        if (isShowLog && priority <= PRINTLN)
            System.out.print(msg);
    }

    public static void print(Object obj) {
        if (isShowLog && priority <= PRINTLN)
            System.out.print(obj);
    }

    //printf
    public static void printf(String msg) {
        if (isShowLog && priority <= PRINTLN)
            System.out.printf(msg);
    }

    // println
    public static void println(String msg) {
        if (isShowLog && priority <= PRINTLN)
            System.out.println(msg);
    }
    public static void println(Object obj) {
        if (isShowLog && priority <= PRINTLN)
            System.out.println(obj);
    }
}
ListView GridView根据item总高度设置高度
public class AdapterViewUtil {

    public static void setListViewHeightBasedOnChildren(GridView listView,int col) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽,有多少列
        int totalHeight = 0;
        // i每次加4,相当于listAdapter.getCount()小于等于4时 循环一次,计算一次item的高度,
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
            totalHeight += listView.getVerticalSpacing();
            if (i==listAdapter.getCount()-1) {
                totalHeight += listView.getVerticalSpacing();
            }
        }
        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }

    public static void setListViewHeightBasedOnChildren(ListView lv){  
        ListAdapter listAdapter = lv.getAdapter();
        int listViewHeight = 0;  
        int adaptCount = listAdapter.getCount();  
        for(int i=0;i<adaptCount;i++){  
            View temp = listAdapter.getView(i,null,lv);  
            temp.measure(0,0);  
            listViewHeight += temp.getMeasuredHeight();  
        }  
        LayoutParams layoutParams = lv.getLayoutParams();  
        layoutParams.width = LayoutParams.MATCH_PARENT;  
        layoutParams.height = listViewHeight;  
        lv.setLayoutParams(layoutParams);  
    }

}
SharePreference相关
public class SharedPreferencesUtils {

    public static final String PREF_NAME = "SHAREDPREFERENCE_FILE_NAME";

    public static SharedPreferences getSharedPreferences(Context context){
        return getSharedPreferences(context, PREF_NAME);
    }
    public static SharedPreferences getSharedPreferences(Context context, String prefName){
        return context.getSharedPreferences(prefName, Context.MODE_PRIVATE);
    }

    //Int
    public static void put(Context context,String key,int value){
        getSharedPreferences(context).edit().putInt(key, value).commit();
    }
    public static int getInt(Context context,String key,int defValue){
        return getSharedPreferences(context).getInt(key, defValue);
    }
    public static int getInt(Context context,String key){
        return getInt(context,key,0);
    }

    //Float
    public static void put(Context context,String key,float value){
        getSharedPreferences(context).edit().putFloat(key, value).commit();
    }

    public static float getFloat(Context context,String key,float defValue){
        return getSharedPreferences(context).getFloat(key, defValue);
    }
    public static float getFloat(Context context,String key){
        return getFloat(context, key, 0);
    }

    //Long
    public static void put(Context context,String key,long value){
        getSharedPreferences(context).edit().putLong(key, value).commit();
    }
    public static long getLong(Context context,String key,long defValue){
        return getSharedPreferences(context).getLong(key, defValue);
    }
    public static long getLong(Context context,String key){
        return getLong(context, key, 0);
    }

    //Boolean
    public static void put(Context context,String key,boolean value){
        getSharedPreferences(context).edit().putBoolean(key, value).commit();
    }
    public static boolean getBoolean(Context context,String key,boolean defValue){
        return getSharedPreferences(context).getBoolean(key, defValue);
    }
    public static boolean getBoolean(Context context,String key){
        return getBoolean(context, key, false);
    }

    //String
    public static void put(Context context,String key,String value){
        getSharedPreferences(context).edit().putString(key, value).commit();
    }
    public static String getString(Context context,String key,String defValue){
        return getSharedPreferences(context).getString(key, defValue);
    }
    public static String getString(Context context,String key){
        return getString(context, key, null);
    }

    //Set<String>
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void put(Context context, String key, Set<String> value){
        getSharedPreferences(context).edit().putStringSet(key, value).commit();
    }
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static Set<String> getStringSet(Context context, String key, Set<String> defValue){
        return getSharedPreferences(context).getStringSet(key, defValue);
    }
    public static Set<String> getStringSet(Context context,String key){
        return getStringSet(context, key, null);
    }

    //Map
    @SuppressLint("CommitPrefEdits")
    public static void putMapString(Context context,Map<String,String> map){
        if(map!=null){
            SharedPreferences.Editor editor = getSharedPreferences(context).edit();
            for(Entry<String, String> entry: map.entrySet()){
                if(!TextUtils.isEmpty(entry.getKey()))
                    editor.putString(entry.getKey(), entry.getValue());
            }
            editor.commit();
        }
    }

    //--------------------------Increase int
    public static void increase(Context context,String key){
        increase(context, key,1);
    }
    public static void increase(Context context,String key,int deltaValue){
        put(context,key,getInt(context, key)+deltaValue);
    }
}
String相关
public class StringUtils {
    //是否为空
    public static boolean isEmpty(CharSequence str) {
        return TextUtils.isEmpty(str);
    }
    public static boolean isEmpty(String str) {
        return TextUtils.isEmpty(str);
    }

    public static int length(CharSequence str) {
        return str == null ? 0 : str.length();
    }
    public static int length(String str) {
        return str == null ? 0 : str.length();
    }
    //是否不为空
    public static boolean isNotEmpty(Object str){
        if(str == null){
            return false;
        }else{
            if(String.valueOf(str).trim().length() == 0){
                return false;
            }
        }
        return true;
    }
    //是否相等
    public static boolean equals(String str1,String str2){
        return str1 != null ? str1.equals(str2) : str2 == null;
    }
}
吐司相关
public class ToastUtils {
    private static Toast toast;
    //获取资源文件中的string
    public static void toast(Context context,@StringRes int resId){
        toast(context,context.getResources().getString(resId));
    }

    public static void toast(Context context,@StringRes int resId,int duration){
        showToast(context,context.getResources().getString(resId),duration);
    }

    public static void toast(Context context,CharSequence text){
        showToast(context,text,Toast.LENGTH_SHORT);
    }

    public static void toast(Context context,String text,int duration,Object...args){
        showToast(context,String.format(text,args),duration);
    }

    public static void showToast(Context context,CharSequence text,int duration){
        if(toast == null){
            toast =  Toast.makeText(context,text,duration);
        }else{
            toast.setText(text);
            toast.setDuration(duration);
        }
        toast.show();
    }
}
时间格式化相关
public class TimeUtils {
    public static final String FORMAT_Y_TO_S = "yyyyMMddHHmmss";
    public static final String FORMAT_Y_TO_S_EN = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_Y_TO_D = "yyyy-MM-dd";
    public static final String FORMAT_YMD = "yyyyMMdd";
    public static final String FORMAT_HMS = "HHmmss";
    public static final String FORMAT_H_TO_MIN = "HH:mm";
    public static String FORMAT_Y_M_D = "yyyy/MM/dd/ HH:mm:ss";
    public static String FORMAT_H_M_S = "HH:mm:ss";

    //改变日期的格式
    public static String formatDate(String time, String fromFormat,
                                    String toFormat) {
        if (TextUtils.isEmpty(time)) {
            return null;
        } else if (TextUtils.isEmpty(fromFormat)
                || TextUtils.isEmpty(toFormat)) {
            return time;
        }

        String dateTime = time;
        String dataStr = null;
        try {
            SimpleDateFormat oldFormat = new SimpleDateFormat(fromFormat);
            SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
            dataStr = newFormat.format(oldFormat.parse(dateTime));
        } catch (ParseException e) {
            return time;
        }
        return dataStr;
    }
    public static String formatDate(String time, String toFormat) {
        if (time == null || "".equals(time.trim()))
            return "";

        String fromFormat = null;
        if (time.length() == 6) {
            fromFormat = "HHmmss";
        } else if (time.length() == 8) {
            fromFormat = "yyyyMMdd";
        } else if (time.length() == 14) {
            fromFormat = "yyyyMMddHHmmss";
        } else {
            return time;
        }
        try {
            SimpleDateFormat oldFormat = new SimpleDateFormat(fromFormat);
            SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
            return newFormat.format(oldFormat.parse(time));
        } catch (ParseException e) {
            return time;
        }
    }
    //将时间戳转换成格式化string
    public static String formatDate(long time, String toFormat)  throws ParseException{
        Date date = new Date(time);
        SimpleDateFormat newFormat = new SimpleDateFormat(toFormat);
        return newFormat.format(date);
    }

    //获取当前的事件
    public static String getCurrentDate() throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(FORMAT_Y_TO_S_EN);
        return format.format(new Date());
    }
    public static String getCurrentDate(String formatStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(new Date());
    }
    public static String formatDate(Date date, String formatStr) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }
}
Android系统应用相关
public class SystemUtils {

    //开启子线程执行任务
    public static void newThread(Runnable runnable){
        new Thread(runnable).start();
    }

    //判断网络是否可用
    public static boolean isNetWorkActive(Context context){
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.isConnected();
    }


    //EditText 发起删除按键事件
    public static void deleteClick(EditText et) {
        final KeyEvent keyEventDown = new KeyEvent(KeyEvent.ACTION_DOWN,
                KeyEvent.KEYCODE_DEL);
        et.onKeyDown(KeyEvent.KEYCODE_DEL, keyEventDown);
    }



    //打开电话界面
    public static void call(Context context, String phoneNumber) {

        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(String.format("tel:%s", phoneNumber)));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(intent);
    }



    //打开信息的界面 发送短信
    public static void sendSMS(Context context, String phoneNumber) {

        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(String.format("smsto:%s", phoneNumber)));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.startActivity(intent);
    }
    public static void sendSMS(String phoneNumber, String msg) {

        SmsManager sm = SmsManager.getDefault();

        List<String> msgs = sm.divideMessage(msg);

        for (String text : msgs) {
            sm.sendTextMessage(phoneNumber, null, text, null, null);
        }

    }


    //拍照
    public static void imageCapture(Activity activity, int requestCode) {
        imageCapture(activity, null, requestCode);
    }
    public static void imageCapture(Activity activity, String path,
                                    int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (!TextUtils.isEmpty(path)) {
            Uri uri = Uri.fromFile(new File(path));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        activity.startActivityForResult(intent, requestCode);
    }
    public static void imageCapture(Fragment fragment, String path,
                                    int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (!TextUtils.isEmpty(path)) {
            Uri uri = Uri.fromFile(new File(path));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        fragment.startActivityForResult(intent, requestCode);
    }


    //获取包的信息
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            LogUtils.e(e);
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return packageInfo;
    }


    //获取应用的版本名称和版本号
    public static String getVersionName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        return packageInfo != null ? packageInfo.versionName : null;
    }
    public static int getVersionCode(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        return packageInfo != null ? packageInfo.versionCode : 0;
    }


    //跳转到app设置详情页面
    public static void startAppDetailSetings(Context context){
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,uri);
        context.startActivity(intent);
    }

    //安装和卸载apk文件
    public static void installApk(Context context,String path){
        installApk(context,new File(path));
    }
    public static void installApk(Context context,File file){

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uriData = Uri.fromFile(file);
        String type = "application/vnd.android.package-archive";

        intent.setDataAndType(uriData, type);
        context.startActivity(intent);
    }
    public static void uninstallApk(Context context,String packageName){

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uriData = Uri.parse("package:" + packageName);
        intent.setData(uriData);
        context.startActivity(intent);
    }
    public static void uninstallApk(Context context){
        uninstallApk(context,context.getPackageName());
    }

    //检测权限 申请权限 显示申请权限的界面
    public static boolean checkSelfPermission(Context context, @NonNull String permission){
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }
    public static void requestPermission(Activity activity, @NonNull String permission, int requestCode){
        ActivityCompat.requestPermissions(activity,new String[]{permission}, requestCode);
    }
    public static void shouldShowRequestPermissionRationale(Activity activity, @NonNull String permission){
        ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
    }

    //显示和隐藏软键盘
    public static void hideInputMethod(Context context,EditText v) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(),0);

    }
    public static void showInputMethod(Context context,EditText v) {
        v.requestFocus();
        InputMethodManager imm = (InputMethodManager)context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v,InputMethodManager.SHOW_IMPLICIT);
    }
}
Base64相关
public class Base64Utils {
    //String 与Base64String的互相转换
    public static String string2Base64(String string){
        byte[] bytes = string.getBytes();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }
    public static String Base642String(String base64string){
        byte[] bytes = Base64.decode(base64string, Base64.DEFAULT);
        return bytes.toString();
    }
    //Bitmap 与Base64String的转换
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                //如果有透明的部分,解码后该背景会变黑
                //有需要就将格式改为png
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length );
    }
}
SD卡相关
public class SDCardUtils  {
    //判断sd是否可用
    public static boolean isSDCardEnable()  {
        return Environment.getExternalStorageState().equals(  
                Environment.MEDIA_MOUNTED);  
    }

    //获取sd卡的绝对路径
    public static String getSDCardPath()  {
        return Environment.getExternalStorageDirectory().getAbsolutePath()  
                + File.separator;  
    }

    //获取SD卡的剩余容量 单位byte
    public static long getSDCardAvailableCapacity()   {
        if (isSDCardEnable())  
        {  
            StatFs stat = new StatFs(getSDCardPath());  
            // 获取空闲的数据块的数量  
            long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
            // 获取单个数据块的大小(byte)  
            long freeBlocks = stat.getAvailableBlocks();  
            return freeBlocks * availableBlocks;  
        }  
        return 0;  
    }  

    //获取指定路径所在空间的剩余可用容量字节数,单位byte
    public static long getFreeBytes(String filePath)   {
        // 如果是sd卡的下的路径,则获取sd卡可用容量  
        if (filePath.startsWith(getSDCardPath()))  
        {  
            filePath = getSDCardPath();  
        } else  
        {// 如果是内部存储的路径,则获取内存存储的可用容量  
            filePath = Environment.getDataDirectory().getAbsolutePath();  
        }  
        StatFs stat = new StatFs(filePath);  
        long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
        return stat.getBlockSize() * availableBlocks;  
    }  

    //获取系统存储路径
    public static String getRootDirectoryPath()  {
        return Environment.getRootDirectory().getAbsolutePath();  
    }  
}
屏幕相关
public class ScreenUtils  {
    public static int getScreenWidth(Context context)  {
        WindowManager wm = (WindowManager) context  
                .getSystemService(Context.WINDOW_SERVICE);  
        DisplayMetrics outMetrics = new DisplayMetrics();  
        wm.getDefaultDisplay().getMetrics(outMetrics);  
        return outMetrics.widthPixels;  
    }  
    public static int getScreenHeight(Context context)  {
        WindowManager wm = (WindowManager) context  
                .getSystemService(Context.WINDOW_SERVICE);  
        DisplayMetrics outMetrics = new DisplayMetrics();  
        wm.getDefaultDisplay().getMetrics(outMetrics);  
        return outMetrics.heightPixels;  
    }  


    //获得状态栏的高度
    public static int getStatusHeight(Context context)  {

        int statusHeight = -1;  
        try  
        {  
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");  
            Object object = clazz.newInstance();  
            int height = Integer.parseInt(clazz.getField("status_bar_height")  
                    .get(object).toString());  
            statusHeight = context.getResources().getDimensionPixelSize(height);  
        } catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
        return statusHeight;  
    }  

    //截图,包含状态栏
    public static Bitmap snapShotWithStatusBar(Activity activity)  
    {  
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap bmp = view.getDrawingCache();  
        int width = getScreenWidth(activity);  
        int height = getScreenHeight(activity);  
        Bitmap bp = null;  
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);  
        view.destroyDrawingCache();  
        return bp;  

    }  

    //获取当前屏幕截图,不包含状态栏
    public static Bitmap snapShotWithoutStatusBar(Activity activity)  {
        View view = activity.getWindow().getDecorView();  
        view.setDrawingCacheEnabled(true);  
        view.buildDrawingCache();  
        Bitmap bmp = view.getDrawingCache();  
        Rect frame = new Rect();  
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
        int statusBarHeight = frame.top;  

        int width = getScreenWidth(activity);  
        int height = getScreenHeight(activity);  
        Bitmap bp = null;  
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height  
                - statusBarHeight);  
        view.destroyDrawingCache();  
        return bp;  
    }
}
随机数工具类
public class RandomUtils {

    public static final String NUMBERS_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String NUMBERS             = "0123456789";
    public static final String LETTERS             = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String CAPITAL_LETTERS     = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final String LOWER_CASE_LETTERS  = "abcdefghijklmnopqrstuvwxyz";

    //获取随机排序的[0-9][a-z][A-Z]
    public static String getRandomNumbersAndLetters(int length) {
        return getRandom(NUMBERS_AND_LETTERS, length);
    }


    //获取随机排序的0-10String
    public static String getRandomNumbers(int length) {
        return getRandom(NUMBERS, length);
    }


    //获取大小写共52位的随机string
    public static String getRandomLetters(int length) {
        return getRandom(LETTERS, length);
    }

    //获取随机顺序的大写26字母的
    public static String getRandomCapitalLetters(int length) {
        return getRandom(CAPITAL_LETTERS, length);
    }
    //获取随机顺序的小写26字母的
    public static String getRandomLowerCaseLetters(int length) {
        return getRandom(LOWER_CASE_LETTERS, length);
    }

    //打乱字符串中的内容
    public static String getRandom(String source, int length) {
        return StringUtils.isEmpty(source) ? null : getRandom(source.toCharArray(), length);
    }
    public static String getRandom(char[] sourceChar, int length) {
        if (sourceChar == null || sourceChar.length == 0 || length < 0) {
            return null;
        }

        StringBuilder str = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            str.append(sourceChar[random.nextInt(sourceChar.length)]);
        }
        return str.toString();
    }


    //获取指定区间的随机int
    public static int getRandom(int max) {
        return getRandom(0, max);
    }
    public static int getRandom(int min, int max) {
        if (min > max) {
            return 0;
        }
        if (min == max) {
            return min;
        }
        return min + new Random().nextInt(max - min);
    }

    //打乱obj数组
    public static boolean shuffle(Object[] objArray) {
        if (objArray == null) {
            return false;
        }

        return shuffle(objArray, getRandom(objArray.length));
    }
    public static boolean shuffle(Object[] objArray, int shuffleCount) {
        int length;
        if (objArray == null || shuffleCount < 0 || (length = objArray.length) < shuffleCount) {
            return false;
        }

        for (int i = 1; i <= shuffleCount; i++) {
            int random = getRandom(length - i);
            Object temp = objArray[length - i];
            objArray[length - i] = objArray[random];
            objArray[random] = temp;
        }
        return true;
    }

    //打乱int数组
    public static int[] shuffle(int[] intArray) {
        if (intArray == null) {
            return null;
        }
        return shuffle(intArray, getRandom(intArray.length));
    }

    //打乱指定长度的int数组
    public static int[] shuffle(int[] intArray, int shuffleCount) {
        int length;
        if (intArray == null || shuffleCount < 0 || (length = intArray.length) < shuffleCount) {
            return null;
        }

        int[] out = new int[shuffleCount];
        for (int i = 1; i <= shuffleCount; i++) {
            int random = getRandom(length - i);
            out[i - 1] = intArray[random];
            int temp = intArray[length - i];
            intArray[length - i] = intArray[random];
            intArray[random] = temp;
        }
        return out;
    }
}
网络状态相关工具类
public class NetWorkUtils {

    public static boolean isConnected(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {

            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (cm == null)
            return false;
        return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

    }

    public static void openNetworkSetting(Activity activity) {
        Intent intent = new Intent("/");
        ComponentName cm = new ComponentName("com.android.settings",
                "com.android.settings.WirelessSettings");
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");
        activity.startActivityForResult(intent, 0);
    }
}
软键盘开关工具类
public class KeyBoardUtils  
{  
    public static void openKeybord(EditText mEditText, Context mContext)
    {  
        InputMethodManager imm = (InputMethodManager) mContext  
                .getSystemService(Context.INPUT_METHOD_SERVICE);  
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);  
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,  
                InputMethodManager.HIDE_IMPLICIT_ONLY);  
    }  
    public static void closeKeybord(EditText mEditText, Context mContext)
    {  
        InputMethodManager imm = (InputMethodManager) mContext  
                .getSystemService(Context.INPUT_METHOD_SERVICE);  

        imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);  
    }  
}  
原生网络请求封装工具类
public class HttpUtils {

    private static final int TIMEOUT_IN_MILLIONS = 5000;

    public interface CallBack {
        void onRequestComplete(String result);
    }


    /**
     * 异步的Get请求
     *
     * @param urlStr
     * @param callBack
     */
    public static void doGetAsyn(final String urlStr, final CallBack callBack) {
        new Thread() {
            public void run() {
                try {
                    String result = doGet(urlStr);
                    if (callBack != null) {
                        callBack.onRequestComplete(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            ;
        }.start();
    }

    /**
     * 异步的Post请求
     *
     * @param urlStr
     * @param params
     * @param callBack
     * @throws Exception
     */
    public static void doPostAsyn(final String urlStr, final String params,
                                  final CallBack callBack) throws Exception {
        new Thread() {
            public void run() {
                try {
                    String result = doPost(urlStr, params);
                    if (callBack != null) {
                        callBack.onRequestComplete(result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            ;
        }.start();

    }

    /**
     * Get请求,获得返回数据
     *
     * @param urlStr
     * @return
     * @throws Exception
     */
    public static String doGet(String urlStr) {
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toString();
            } else {
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
            }
            conn.disconnect();
        }

        return null;

    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     * @throws Exception
     */
    public static String doPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接  
            HttpURLConnection conn = (HttpURLConnection) realUrl
                    .openConnection();
            // 设置通用的请求属性  
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            conn.setRequestProperty("charset", "utf-8");
            conn.setUseCaches(false);
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

            if (param != null && !param.trim().equals("")) {
                // 获取URLConnection对象对应的输出流  
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数  
                out.print(param);
                // flush输出流的缓冲  
                out.flush();
            }
            // 定义BufferedReader输入流来读取URL的响应  
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流  
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}  
文件相关
public class FileUtils {
    private static FileUtils util;

    public static FileUtils getInstance() {
        if (util == null)
            util = new FileUtils();
        return util;
    }

    private Context context = null;

    public void setContext(Context c) {
        this.context = c;
    }

    public Context getContext() {
        return context;
    }

    public File creatFileIfNotExist(String path) {
        System.out.println("cr");
        File file = new File(path);
        if (!file.exists()) {
            try {
                new File(path.substring(0, path.lastIndexOf(File.separator)))
                        .mkdirs();
                file.createNewFile();

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

            }
        }
        return file;
    }

    public File creatDirIfNotExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.mkdirs();

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

            }
        }
        return file;
    }

    public boolean IsExist(String path) {
        File file = new File(path);
        if (!file.exists())
            return false;
        else
            return true;
    }

    public File creatNewFile(String path) {
        File file = new File(path);
        if (IsExist(path))
            file.delete();
        creatFileIfNotExist(path);
        return file;
    }

    public boolean deleteFile(String path) {
        File file = new File(path);
        if (IsExist(path))
            file.delete();
        return true;
    }

    // 删除一个目录
    public boolean deleteFileDir(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!IsExist(path)) {
            return flag;
        }
        if (!file.isDirectory()) {

            file.delete();
            return true;
        }
        String[] filelist = file.list();
        File temp = null;
        for (int i = 0; i < filelist.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + filelist[i]);
            } else {
                temp = new File(path + File.separator + filelist[i]);
            }
            if (temp.isFile()) {

                temp.delete();
            }
            if (temp.isDirectory()) {
                deleteFileDir(path + "/" + filelist[i]);// 先删除文件夹里面的文件
            }
        }
        file.delete();

        flag = true;
        return flag;
    }

    // 删除文件夹
    public void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除指定文件夹下所有文件
    public boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    //获取指定目录下的所有文件名称
    public String[] getFlieName(String rootpath) {
        File root = new File(rootpath);
        File[] filesOrDirs = root.listFiles();
        if (filesOrDirs != null) {
            String[] dir = new String[filesOrDirs.length];
            int num = 0;
            for (int i = 0; i < filesOrDirs.length; i++) {
                if (filesOrDirs[i].isDirectory()) {
                    dir[i] = filesOrDirs[i].getName();
                    num++;
                }
            }
            String[] dir_r = new String[num];
            num = 0;
            for (int i = 0; i < dir.length; i++) {
                if (dir[i] != null && !dir[i].equals("")) {
                    dir_r[num] = dir[i];
                    num++;
                }
            }
            return dir_r;
        } else
            return null;
    }

    //将指定路径的文件转换io流
    public BufferedWriter getWriter(String path) throws FileNotFoundException,
            UnsupportedEncodingException {
        FileOutputStream fileout = null;
        fileout = new FileOutputStream(new File(path));
        OutputStreamWriter writer = null;
        writer = new OutputStreamWriter(fileout, "UTF-8");
        BufferedWriter w = new BufferedWriter(writer); // 缓冲区
        return w;
    }
    public InputStream getInputStream(String path) throws FileNotFoundException {
        FileInputStream filein = null;
        File file = new File(path);
        filein = new FileInputStream(file);
        BufferedInputStream in = null;
        if (filein != null)
            in = new BufferedInputStream(filein);
        return in;
    }

    //判断文件是否存在
    public boolean ifFileExit(String path) {
        File f = new File(path);
        if (!f.exists())
            return false;
        if (f.length() == 0)
            return false;
        return true;
    }

    //io流和byte[]的互相转换
    public static byte[] InputStream2Bytes(InputStream in) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[6 * 1024];
        int count = -1;
        while ((count = in.read(data, 0, 4 * 1024)) != -1)
            outStream.write(data, 0, count);
        data = null;
        return outStream.toByteArray();
    }
    public static byte[] OutputStream2Bytes(OutputStream out)
            throws IOException {

        byte[] data = new byte[6 * 1024];
        out.write(data);
        return data;
    }
    public static InputStream byte2InputStream(byte[] in) {
        ByteArrayInputStream is = new ByteArrayInputStream(in);
        return is;
    }
    public static OutputStream bytes2OutputStream(byte[] in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(in);
        return out;
    }

    //把输入流保存为指定文件
    public File writeFromInputToSD(String path, InputStream inputStream) {
        File file = null;
        OutputStream output = null;
        try {
            file = creatFileIfNotExist(path);
            output = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int temp;
            while ((temp = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, temp);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    //把String保存为文件
    public File writeFromInputToSD(String path, byte[] b) {
        File file = null;
        OutputStream output = null;
        try {
            file = creatFileIfNotExist(path);
            output = new FileOutputStream(file);
            output.write(b);
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    //把String append到文件的
    public void saveTxtFile(String filePath, String text) {
        try {
            creatFileIfNotExist(filePath);
            String txt = readTextLine(filePath);
            text = text + txt;
            FileOutputStream out = new FileOutputStream(filePath);
            OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
            writer.write(text);
            writer.close();
            out.close();
        } catch (Exception e) {
            String ext = e.getLocalizedMessage();
        }

    }

    //清空指定文件中的内容
    public void clearTxtFile(String filePath) {
        try {
            String text = "";
            FileOutputStream out = new FileOutputStream(filePath);
            OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
            writer.write(text);
            writer.close();
            out.close();
        } catch (Exception e) {
            String ext = e.getLocalizedMessage();
        }
    }

    //获取指定路径文件中的string
    public String readTextLine(String textFilePath) {
        try {
            FileInputStream input = new FileInputStream(textFilePath);
            InputStreamReader streamReader = new InputStreamReader(input,
                    "gb2312");
            LineNumberReader reader = new LineNumberReader(streamReader);
            String line = null;
            StringBuilder allLine = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                allLine.append(line);
                allLine.append("\n");
            }
            streamReader.close();
            reader.close();
            input.close();
            return allLine.toString();
        } catch (Exception e) {
            return "";
        }
    }

    //截取指定字符前的字符串
    public String getNameByFlag(String source, String flag) {
        String[] source_spli = source.split(flag);
        String s = source_spli[0].replace(flag, "");
        return s.trim();
    }

    //获取Asset文件夹下文件
    public InputStream getAssetsInputStream(Context paramContext,
                                            String paramString) throws IOException {
        return paramContext.getResources().getAssets().open(paramString);
    }

    //以缩略图的方式读取图片
    public Bitmap getBitmap(InputStream is) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        opt.inSampleSize = 4;
        return BitmapFactory.decodeStream(is, null, opt);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值