android开发工具类

来源:互联网 发布:mac无法拖动文件夹 编辑:程序博客网 时间:2024/06/06 02:51
package com.artron.mmj.seller.utils;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieSyncManager;
import android.webkit.MimeTypeMap;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.FrameLayout;


import com.artron.mmj.seller.R;
import com.artron.mmj.seller.net.StaticField;
import com.artron.mmj.seller.shareddata.LocalCacheData;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xwalk.core.XWalkCookieManager;


import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import io.rong.imkit.RongIM;




/**
 * @author 工具类
 */


public class AppUtils {


    /**
     * 生成md5key的随机字符串
     */
    public static final String MD5KEY_SIGN = "artron_20150926_panpeng_20140905";


    public static boolean needClearXWalkCookie; // 需要清理xwalkview cookie
    public static boolean needClearWebViewCookie; // 需要清理 webview cookie


    public static String getDeviceUuid(Context context) {
        String deviceId = LocalCacheData.getInstance(context).getDeviceId();


        if (TextUtils.isEmpty(deviceId)) {
            deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getDeviceId();
            if (TextUtils.isEmpty(deviceId) || "000000000000000".equals(deviceId)) {
                deviceId = UUID.randomUUID().toString();
            }
            LocalCacheData.getInstance(context).setDeviceId(deviceId);
        }
        return deviceId;


    }


    public static void clearCache(Context context) {
        LocalCacheData.getInstance(context).setUid("");
        LocalCacheData.getInstance(context).setNickname("");
        LocalCacheData.getInstance(context).setAvatar("");
        LocalCacheData.getInstance(context).setMobile("");
        LocalCacheData.getInstance(context).setRongCloudToken("");
        needClearXWalkCookie = true;
        needClearWebViewCookie = true;
        try {
            RongIM.getInstance().logout();
            RongIM.getInstance().disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void clearWebViewCookie(Context context) {
        // xwalk
        try {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                XWalkCookieManager cookieManagerWeb = new XWalkCookieManager();
                cookieManagerWeb.removeAllCookie();
                cookieManagerWeb.removeSessionCookie();
            }
        } catch (Exception e) {
            Log.w("xwalk", e);
        }


        // webview
        try {
            android.webkit.CookieManager webkitCookieManager = android.webkit.CookieManager.getInstance();
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                webkitCookieManager.removeSessionCookie();
                webkitCookieManager.removeAllCookie();
                CookieSyncManager.createInstance(context);
                CookieSyncManager.getInstance().sync();
            } else {
                webkitCookieManager.removeSessionCookies(null);
                webkitCookieManager.removeAllCookies(null);
                webkitCookieManager.flush();
            }
        } catch (Exception e) {
            Log.w("xwalk", e);
        }


    }


    public static byte[] readFile(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) != -1) {
            out.write(buf, 0, len);
        }
        out.close();
        in.close();
        return out.toByteArray();
    }


    /**
     * 获取mac地址
     *
     * @param context
     * @return
     */
    public static String getMacAdrress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        try {
            String address = info.getMacAddress();
            return address != null ? address : "";
        } catch (Exception e) {
        }
        return "";
    }


    /**
     * 获取android版本号
     *
     * @return
     */
    public static String getAndroidVersion() {
        // return android.os.Build.VERSION.SDK_INT;
        return android.os.Build.VERSION.RELEASE;
    }


    /**
     * 获取应用版本号
     *
     * @return
     */
    public static String getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0);
            // 当前应用的版本名称
            String versionName = info.versionName;
            return versionName;
            // // 当前版本的版本号
            // int versionCode = info.versionCode;


            // 当前版本的包名
            // String packageNames = info.packageName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 获取设备型号
     *
     * @return
     */
    public static String getDeviceModel() {
        return android.os.Build.MODEL;
    }


    /**
     * 获取设备宽度
     *
     * @return
     */
    public static int getDeviceWidth(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(mDisplayMetrics);
        int w = mDisplayMetrics.widthPixels;
        return w;
    }


    /**
     * 获取设备高度
     *
     * @return
     */
    public static int getDeviceHeight(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(mDisplayMetrics);
        int h = mDisplayMetrics.heightPixels;
        return h;
    }


    /**
     * 获取屏幕密度
     *
     * @param context
     * @return
     */
    public static float getDeviceDensity(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(mDisplayMetrics);
        float density = mDisplayMetrics.density;  // 密度
        return density;
    }


    /**
     * 获取md5key
     *
     * @return
     */
    public static String getMD5Key(String deviceType, String deviceId, String osVersion, String deviceModel,
                                   String appVersion, String screenWidth, String screenHeight, String deviceScale, String marketKey, String macAddress) {


        String srcStr = deviceType + '|'
                + deviceId + '|' + osVersion + '|' + deviceModel + '|' +
                appVersion + '|' + screenWidth + '|' + screenHeight + '|' +
                deviceScale + '|' + marketKey + '|' + macAddress + '|' + MD5KEY_SIGN;
        Log.i("test", "srcStr:" + srcStr);
        return EncryptUtil.md5EncodeString(srcStr);
    }




    /**
     * 获取md5key
     *
     * @return
     */
    public static String getMD5Key2(String androidVersion, String deviceModel) {
        return EncryptUtil.md5EncodeString(androidVersion + deviceModel + MD5KEY_SIGN);
    }


    /**
     * 判断是否有网络
     *
     * @param context
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }


        return false;
    }




    /**
     * 获取应用市场的key
     *
     * @return
     */
    public static String getAppMarketKey(Context context) {
        ApplicationInfo appInfo;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    PackageManager.GET_META_DATA);
            return appInfo.metaData.getString("APP_MARKET_KEY");
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";


    }


    /**
     * 压缩图片
     *
     * @return
     * @author Msz 2014/5/20
     * 通过图片比例自动压缩图片
     */
    public static Bitmap scaleImg(Bitmap bm, int newSize) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth;
        float scaleHeight;
        // 计算缩放比例
        if (width > height) {
            scaleWidth = ((float) newSize * width / height) / width; // ((float)
            // width;
            scaleHeight = ((float) newSize) / height;// ((float) newWidth *
            // height / width) /
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            matrix.postRotate(0);


            return imageCrop(Bitmap
                    .createScaledBitmap(bm, newSize * width / height, newSize, false));
            // height;
        } else if (width < height) {
            scaleWidth = ((float) newSize) / width;
            scaleHeight = ((float) newSize * height / width) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            matrix.postRotate(0);


            return imageCrop(Bitmap
                    .createScaledBitmap(bm, newSize, newSize * height / width, false));
        } else {
            scaleWidth = ((float) newSize) / width;
            scaleHeight = ((float) newSize * height / width) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            matrix.postRotate(0);
            return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        }


    }


    /**
     * 按正方形裁切图片
     */
    public static Bitmap imageCrop(Bitmap bitmap) {
        int w = bitmap.getWidth(); // 得到图片的宽,高
        int h = bitmap.getHeight();


        int wh = w > h ? h : w;// 裁切后所取的正方形区域边长


        int retX = w > h ? (w - h) / 2 : 0;// 基于原图,取正方形左上角x坐标
        int retY = w > h ? 0 : (h - w) / 2;


        // 下面这句是关键
        return Bitmap.createBitmap(bitmap, retX, retY, wh, wh, null, false);
    }


    /**
     * drawable转成bitmap图片
     */
    public static Bitmap drawable2Bitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                    : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }


    /**
     * bitmap图片转成二进制数组
     */
    public static byte[] getBitmapByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }


    /**
     * 二进制数组转成bitmap图片
     */
    public static Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }


    /**
     * 判断 多个字段的值否为空
     *
     * @return true为null或空; false不null或空
     * @author Msz 2014/5/20
     */
    public static boolean isNull(String... ss) {
        for (int i = 0; i < ss.length; i++) {
            if (null == ss[i] || ss[i].equals("") || ss[i].equalsIgnoreCase("null")) {
                return true;
            }
        }


        return false;
    }


    /**
     * 判断 一个字段的值否为空
     *
     * @param s
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean isNull(String s) {
        if (null == s || s.equals("") || s.equalsIgnoreCase("null")) {
            return true;
        }


        return false;
    }


    /**
     * 判断两个字段是否一样
     *
     * @author Msz 2014/5/20
     */
    public static boolean judgeStringEquals(String s0, String s1) {
        return s0 != null && null != s1 && s0.equals(s1);
    }


    /**
     * 判断email格式是否正确
     *
     * @param email
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }


    /**
     * 验证手机号码长度
     *
     * @param phone
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean phoneLength(String phone) {
        if (phone.length() == 11 && phone.startsWith("1")) {
            return true;
        }


        return false;
    }


    /**
     * 验证手机号码
     *
     * @param phone
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean isPhone(String phone) {
        if (isNull(phone))
            return false;
        String pattern = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";


        return phone.matches(pattern);
    }


    /**
     * 验证密码由6-23位数字、字母、下划线和中文组成
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean isPassword(String pwd) {
        if (isNull(pwd))
            return false;
        String pattern = "^[a-zA-Z0-9_\u4e00-\u9fa5]{6,23}$";


        return pwd.matches(pattern);
    }


    /**
     * 判断账号是否在4-15位之间
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean nameLength(String name) {
        if (name.length() < 4 || name.length() > 15) {
            return false;
        }
        return true;
    }


    /**
     * 判断密码是否在6-23位之间
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean pwdLength(String pwd) {
        if (pwd.length() < 6 || pwd.length() > 23) {
            return false;
        }
        return true;
    }


    /**
     * 将px类型的尺寸转换成dp类型的尺寸
     *
     * @param context
     * @return
     * @author Msz 2014/5/20
     */
    public static int PXtoDP(Context context, int pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    /**
     * 将dp类型的尺寸转换成px类型的尺寸
     *
     * @param context
     * @return
     * @author Msz 2014/5/20
     */
    public static int DPtoPX(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    /**
     * sp 转换 px
     *
     * @param resources
     * @param sp
     * @return
     */
    public static float sp2px(Resources resources, float sp) {
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }


    /**
     * 将px值转换为sp值,保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }


    /**
     * 判断sd卡是否存在
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static boolean judgeSDCard() {
        String status = Environment.getExternalStorageState();
        return status.equals(Environment.MEDIA_MOUNTED);
    }


    /**
     * 获得hashmap中value的值,以List 返回
     *
     * @param hashMap
     * @return
     * @author Msz 2014/5/20
     */
    public static List<String> getListByHashMap(HashMap<String, String> hashMap) {
        List<String> list = new ArrayList<String>();
        Iterator iter = hashMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            list.add((String) val);
        }


        return list;
    }


    /**
     * 获取版本号 给用户看的
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static double getVersionName(Activity activity) {
        String versionName = "0";
        if (getPackageInfo(activity) != null) {
            versionName = getPackageInfo(activity).versionName;
        }


        return Double.parseDouble(versionName);
    }


    /**
     * 获取版本号 系统识别用的
     *
     * @return
     * @author Msz 2014/5/20
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        if (getPackageInfo(context) != null) {
            versionCode = getPackageInfo(context).versionCode;
        }


        return versionCode;
    }


    //获取类报名
    private static PackageInfo getPackageInfo(Context context) {
        String packageName = context.getPackageName();
        try {
            return context.getPackageManager().getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }


        return null;
    }


    //获取当前栈顶的类名
    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);


        if (runningTaskInfos != null)
            return (runningTaskInfos.get(0).topActivity).getClassName();
        else
            return null;
    }


    //判断应用是否在运行
    public static boolean appIsRunning(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        try {
            PackageInfo packageinfo = context.getPackageManager().getPackageInfo(context.getPackageName(),
                    0);
            // 当前版本的包名
            String packageName = packageinfo.packageName;
            for (RunningTaskInfo info : list) {
                if (info.topActivity.getPackageName().equals(packageName) || info.baseActivity.getPackageName().equals(packageName)) {
                    isAppRunning = true;
                    break;
                }
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return isAppRunning;
    }


    /**
     * 制作圆角头像
     *
     * @param bitmap 需要制作圆角的图片
     * @param pixels 圆角半径
     * @param color  背景色
     * @return
     * @author Msz 2014/5/20
     */


    public static Bitmap toRoundCorner(Bitmap bitmap, float pixels, int color) {
        Bitmap output = Bitmap
                .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);


        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;


        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);


        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }


    /**
     * 制作圆角头像
     *
     * @param bitmap
     * @param pixels
     * @return
     */


    public static Bitmap toRoundCorner(Bitmap bitmap, float pixels) {
        // System.out.println("图片是否变成圆角模式了+++++++++++++");
        Bitmap output = Bitmap
                .createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);


        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;


        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);


        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        // System.out.println("pixels+++++++" + pixels);


        return output;
    }


    /**
     * 保存bitmap成文件形式
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static void saveBitmapFile(Bitmap bm, String path,String fileName) throws
            IOException {
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(dirFile,fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }


    /**
     * 保存bitmap到SD卡中
     *
     * @param bm
     * @throws IOException
     */
    public static void saveBitmapToSDCard(Context context, Bitmap bm) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(StorageUtils.getOwnCacheDirectory(context.getApplicationContext(), StaticField.SDCARD_PATH_CAN_CLEAR + "/adv.jpg")); // 欢迎页面广告图片目录
            if (fos != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存登录背景bitmap到SD卡中
     *
     * @param bm
     * @throws IOException
     */
    public static void saveBackgroundBitmapToSDCard(Context context, Bitmap bm) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(StorageUtils.getOwnCacheDirectory(context.getApplicationContext(), StaticField.AVATAR_PATH + "/avatar_back.jpg")); // 头像目录
            if (fos != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取SD卡图片
     *
     * @param pathString
     * @return
     * @author Msz 2014/5/20
     */
    public static Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return bitmap;
    }


    /**
     * 获取屏幕信息
     *
     * @author Msz 2014/5/20
     */
    public static void getScreenWidth(Activity ctx) {
        DisplayMetrics dm = new DisplayMetrics();
        ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
    }




    /**
     * 是否包含特殊字符
     *
     * @param text
     * @return
     */
    public static boolean isContainSpeacial(String text) {
        if (text != null) {
            String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(text);
            return m.find();
        } else {
            return true;
        }
    }


    /**
     * 是否只包含汉子、字母、数字和下划线,且不以下划线开头
     *
     * @param text
     * @return
     */
    public static boolean isJustDigitalAndLetterAndCN(String text) {
        if (text != null) {
            String regEx = "^[\u4e00-\u9fa5_a-zA-Z0-9]+$";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(text);
            return !m.matches();
        } else {
            return false;
        }
    }


    /**
     * 是否为纯数字
     *
     * @param text
     * @return
     */
    public static boolean isJustDigital(String text) {
        String pattern = "[+-] [0-9]*";
        Pattern pat = Pattern.compile(pattern);
        Matcher mat = pat.matcher(text);
        return mat.matches();
    }


    /**
     * 判断中文个数
     *
     * @param text
     * @return
     */
    public static int getChineseCount(String text) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < text.length(); i++) {


            int a = text.charAt(i);


            if (a > 0x4e00 && a < 0x9fff) {
                count++;
            }
        }
        return count;
    }


    /**
     * 转换文件大小
     */
    public static String getFileSize(File f) {
        long fileS = f.length();
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }


    /**
     * 将时间戳转为代表"距现在多久之前"的字符串数组
     * <p/>
     * 时间戳
     *
     * @return
     */
    public static String[] getStandardDateArray(long timestamp) {
        try {
            String[] timeStrArray = new String[2];
            long t = timestamp;
            long time = System.currentTimeMillis() - (t * 1000);
            long mill = (long) Math.floor(time / 1000);// 秒前


            long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前


            long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时


            long day = (long) Math.floor(time / 24 / 60 / 60 / 1000.0f);// 天前
            // XLog.e("当前系统时间" + System.currentTimeMillis() + "获取到的时间" + t *
            // 1000
            // + "时间差" + time + "天数" + day);
            long month = (long) Math.floor(day / 30);
            // XLog.e("月" + month);
            long year = (long) Math.floor(day / 365);


            if (year - 1 >= 0) {
                // sb.append(year + "年");
                // sb.append( "1年");
                timeStrArray[0] = "1";
                timeStrArray[1] = "年前";
            } else if (month - 1 >= 0) {
                if (month == 12) {
                    // sb.append("1年");
                    timeStrArray[0] = "1";
                    timeStrArray[1] = "年前";
                } else {
                    // sb.append(month + "个月");
                    timeStrArray[0] = String.valueOf(month);
                    timeStrArray[1] = "个月前";
                }
            } else if (day - 1 >= 0) {
                if (day >= 30) {
                    // sb.append("1个月");
                    timeStrArray[0] = "1";
                    timeStrArray[1] = "个月前";
                } else if (day / 7 >= 1) {
                    // sb.append(day/7 + "周");
                    timeStrArray[0] = String.valueOf(day / 7);
                    timeStrArray[1] = "周前";
                } else {
                    // sb.append(day + "天");
                    timeStrArray[0] = String.valueOf(day);
                    timeStrArray[1] = "天前";
                }
            } else if (hour - 1 >= 0) {
                if (hour == 24) {
                    // sb.append("1天");
                    timeStrArray[0] = "1";
                    timeStrArray[1] = "天前";
                } else {
                    // sb.append(hour + "小时");
                    timeStrArray[0] = String.valueOf(hour);
                    timeStrArray[1] = "小时前";
                }
            } else if (minute - 1 >= 0) {
                if (minute == 60) {
                    // sb.append("1小时");
                    timeStrArray[0] = "1";
                    timeStrArray[1] = "小时前";
                } else {
                    // sb.append(minute + "分钟");
                    timeStrArray[0] = String.valueOf(minute);
                    timeStrArray[1] = "分钟前";
                }
            } else if (mill - 10 >= 0) {
                if (mill == 60) {
                    // sb.append("1分钟");
                    timeStrArray[0] = "1";
                    timeStrArray[1] = "分钟前";
                } else {
                    // sb.append(mill + "秒");
                    timeStrArray[0] = String.valueOf(mill);
                    timeStrArray[1] = "秒前";
                }
            } else {
                // sb.append("刚刚");
                timeStrArray[0] = "刚刚";
                timeStrArray[1] = "刚刚";
            }
            // if (!sb.toString().equals("刚刚")) {
            // sb.append("前");
            // }
            return timeStrArray;
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     *
     * @param timeStr 时间戳
     * @return
     */
    public static String getStandardDate(String timeStr) {
        try {
            long t = Long.parseLong(timeStr);
            return getStandardDateFromLong(t);
        } catch (Exception e) {
            return timeStr;
        }
    }


    /**
     * 将时间戳转为日期模式
     * <p/>
     * 时间戳
     *
     * @return
     */
    public static String getDate(String time) {
        try {
            SimpleDateFormat sdr = new SimpleDateFormat("yyyy-MM-dd");
            int i = Integer.parseInt(time);
            String times = sdr.format(new Date(i * 1000L));
            return times;
        } catch (Exception e) {
            return time;
        }
    }


    /**
     * 将时间戳转为日期模式
     * <p/>
     * 时间戳
     *
     * @return
     */
    public static String getMonthDate(String time) {
        try {
            SimpleDateFormat sdr = new SimpleDateFormat("MM.dd HH:mm");
            int i = Integer.parseInt(time);
            String times = sdr.format(new Date(i * 1000L));
            return times;
        } catch (Exception e) {
            return time;
        }
    }


    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     *
     * @param timeStr 时间戳
     * @return
     */
    public static String getStandardDateFromLong(long timeStr) {
        try {
            StringBuffer sb = new StringBuffer();


            long t = timeStr;
            long time = System.currentTimeMillis() - (t * 1000);
            long mill = (long) Math.floor(time / 1000);// 秒前


            long minute = (long) Math.floor(time / 60 / 1000.0f);// 分钟前


            long hour = (long) Math.floor(time / 60 / 60 / 1000.0f);// 小时


            long day = (long) Math.floor(time / 24 / 60 / 60 / 1000.0f);// 天前
            // XLog.e("当前系统时间" + System.currentTimeMillis() + "获取到的时间" + t *
            // 1000
            // + "时间差" + time + "天数" + day);
            long month = (long) Math.floor(day / 30);
            // XLog.e("月" + month);
            long year = (long) Math.floor(day / 365);


            if (year - 1 >= 0) {
                // sb.append(year + "年");
                sb.append("1年");
            } else if (month - 1 >= 0) {
                if (month == 12) {
                    sb.append("1年");
                } else {
                    sb.append(month + "个月");
                }
            } else if (day - 1 >= 0) {
                if (day >= 30) {
                    sb.append("1个月");
                } else if (day / 7 >= 1) {
                    sb.append(day / 7 + "周");
                } else {
                    sb.append(day + "天");
                }
            } else if (hour - 1 >= 0) {
                if (hour == 24) {
                    sb.append("1天");
                } else {
                    sb.append(hour + "小时");
                }
            } else if (minute - 1 >= 0) {
                if (minute == 60) {
                    sb.append("1小时");
                } else {
                    sb.append(minute + "分钟");
                }
            } else if (mill - 10 >= 0) {
                if (mill == 60) {
                    sb.append("1分钟");
                } else {
                    sb.append(mill + "秒");
                }
            } else {
                sb.append("刚刚");
            }
            if (!sb.toString().equals("刚刚")) {
                sb.append("前");
            }
            return sb.toString();
        } catch (Exception e) {
            return "";
        }
    }


    // 将字符串转为时间戳


    public static String getTime(String user_time) {
        String re_time = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d;
        try {


            d = sdf.parse(user_time);
            long l = d.getTime();
            String str = String.valueOf(l);
            re_time = str.substring(0, 10);


        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return re_time;
    }


    /**
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        if (input != null) {
            char[] c = input.toCharArray();
            for (int i = 0; i < c.length; i++) {
                if (c[i] == 12288) {
                    c[i] = (char) 32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char) (c[i] - 65248);
            }
            return new String(c);
        }
        return null;
    }


    /**
     * 读取图片属性:旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    /*
     * 旋转图片
     *
     * @param angle
     *
     * @param bitmap
     *
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    /**
     * 缩放图片
     *
     * @param imagePath
     * @return 一个缩放好的bitmap
     */
    public static Bitmap getZoomBitmap(String imagePath) {
        // 解决图片内存溢出问题
        Options options = new Options();
        options.inJustDecodeBounds = true;// 这样就只返回图片参数
        // 获取这个图片的宽和高
        Bitmap bm = BitmapFactory.decodeFile(imagePath, options); // 此时返回bm为空
        options.inJustDecodeBounds = false;// 上面操作完后,要设回来,不然下面同样获取不到实际图片
        // 计算缩放比
        int be = (int) (options.outHeight / (float) 500);
        // 上面算完后一下如果比300大,那就be就大于1,那么就压缩be,如果比300小,那图片肯定很小了,直接按原图比例显示就行
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;// be=2.表示压缩为原来的1/2,以此类推
        // 重新读入图片,注意在这之前要把options.inJustDecodeBounds 设为 false!
        bm = BitmapFactory.decodeFile(imagePath, options);


        return bm;
    }


    // 根据路径获得图片并压缩,返回bitmap用于显示
    public static Bitmap getSmallBitmap(Context context, String filePath) {
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);


        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, AppUtils.getDeviceWidth(context) / 5,
                AppUtils.getDeviceWidth(context) / 5);


        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;


        return BitmapFactory.decodeFile(filePath, options);
    }


    // 根据路径获得图片并压缩,返回bitmap用于显示
    public static Bitmap getJPEGBitmap(Context context, String filePath) {
        final Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, AppUtils.getDeviceWidth(context),
                AppUtils.getDeviceWidth(context));
        options.inPreferredConfig = Config.RGB_565;
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;


        return BitmapFactory.decodeFile(filePath, options);
    }


    // 计算图片的缩放值
    public static int calculateInSampleSize(Options options, int reqWidth,
                                            int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;


        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }


    @SuppressLint("NewApi")
    public static void saveBitmap(Bitmap bitmap, File file, Context context) throws IOException {
        int rate = 100;
        if (file.length() > 1024 * 4) {
            rate = 65;
        } else if (file.length() > 1024 * 3) {
            rate = 75;
        } else if (file.length() > 1024 * 2) {
            rate = 85;
        } else if (file.length() > 1024) {
            rate = 95;
        }
        BufferedOutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, rate, os);
        } finally {
            insertToAlbum(file.getAbsolutePath(), context);
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }


    }


    @SuppressLint("NewApi")
    public static void saveBitmap2(Context context, String fileName, String filePath,
                                   Bitmap bitmap, File file) throws IOException {
        int rate = 100;
        BufferedOutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, rate, os);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
        insertToAlbum(filePath, context);


    }


    // 根据图片的URL路径来获取网络图片并保存到SD卡中
    public static void saveBitmap(final Activity ac, final String path) throws IOException {
        // TODO Auto-generated method stubz
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(30 * 1000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        InputStream inputStream = conn.getInputStream();
                        Options opts = new Options();
                        // 根据计算出的比例进行缩放
                        int scale = getScare(ac, path);
                        opts.inSampleSize = scale;


                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opts);
                        saveBitmapToSDCard(ac, bitmap);// 保存图片到SD卡中
                    }
                } catch (Exception e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }


            ;
        }.start();
    }


    // 根据图片的URL路径来获取网络图片
    public static void getBitmap(final Activity ac, final Handler myHandler, final String path,
                                 final int msgtype) throws IOException {
        // TODO Auto-generated method stubz
        final Message msg = new Message();
        final Bundle bundle = new Bundle();
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(30 * 1000);
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        InputStream inputStream = conn.getInputStream();
                        Options opts = new Options();
                        // 根据计算出的比例进行缩放
                        int scale = getScare(ac, path);
                        opts.inSampleSize = scale;


                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, opts);


                        // Bitmap bitmap =
                        // BitmapFactory.decodeStream(inputStream);
                        msg.what = msgtype;
                        bundle.putParcelable("bitmap", bitmap);
                    } else {


                    }
                } catch (Exception e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                msg.setData(bundle);
                myHandler.sendMessage(msg);
            }


            ;
        }.start();
    }


    /**
     * 计算图片的缩放比例
     *
     * @return
     */
    public static int getScare(Activity ac, String path) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(path);
            HttpResponse response = client.execute(httpGet);
            int code = response.getStatusLine().getStatusCode();


            if (200 == code) {
                InputStream is = response.getEntity().getContent();
                Options opts = new Options();
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(is, null, opts);


                int imageWidth = opts.outWidth;
                int imageHeight = opts.outHeight;


                Display display = ac.getWindowManager().getDefaultDisplay();
                int screenWidth = display.getWidth();
                int screenHeight = display.getHeight();


                int widthscale = imageWidth / screenWidth;
                int heightscale = imageHeight / screenHeight;
                int scale = widthscale > heightscale ? widthscale : heightscale;


                return scale;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;// 网络连接失败时默认返回1
    }


    //插入文件到相册
    public static void fileScan(String file, Context contex) {
        Uri data = Uri.parse("file://" + file);
        contex.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, data));
    }


    // /**刷新相册
    // * @param path
    // * @param context
    // */
    // public static void folderScan(String path, Context context){
    // File file = new File(path);
    // if(file==null||!file.exists()){
    // return;
    // }
    // if(file.isDirectory()){
    // File[] array = file.listFiles();
    // if(array!=null){
    // for(int i=0;i<array.length;i++){
    // File f = array[i];
    //
    // if(f.isFile()){//FILE TYPE
    // // String name = f.getName();
    // //
    // // if(name.contains(".mp3")){
    // fileScan(f.getAbsolutePath(),context);
    // // }
    // }
    // else {//FOLDER TYPE
    // folderScan(f.getAbsolutePath(),context);
    // }
    // }
    // }
    // }else{
    // fileScan(file.getAbsolutePath(),context);
    // }
    // }
    public static void insertToAlbum(String filePath, Context context) {
        if (filePath == null || filePath.length() == 0) {
            return;
        }
        final String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
        // 系统时间
        final long dateTaken = System.currentTimeMillis();
        ContentValues values = new ContentValues(5);
        values.put(MediaStore.Images.Media.TITLE, fileName);
        values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        values.put(MediaStore.Images.Media.DATA, filePath);
        context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    }


    public static void deleteToAlbum(String filePath, Context context) {
        if (filePath == null || filePath.length() == 0) {
            return;
        }
        try {
            final String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
            // 系统时间
            final long dateTaken = System.currentTimeMillis();
            ContentValues values = new ContentValues(5);
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            values.put(MediaStore.Images.Media.DATA, filePath);
            context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    MediaStore.Images.Media.DATA + "=?", new String[]{filePath});
        } catch (Exception e) {


        }
    }


    public static boolean isPswFormat(String psw) {
        if (!TextUtils.isEmpty(psw) && psw.length() >= 6) {
            return psw.matches("[A-Za-z0-9_]+");
        }
        return false;
    }


    public static String getTimeFromTimeStamp(long time) {
        Long timestamp = time * 1000;
        String date = new SimpleDateFormat("MM.dd").format(new Date(timestamp));
        return date;
    }


    public static void setHintSize(EditText edit, String hint) {
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hint);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(15, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        edit.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


    /**
     * 判断应用是否已安装
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isInstalled(Context context, String packageName) {
        boolean hasInstalled = false;
        PackageManager pm = context.getPackageManager();
        List<PackageInfo> list = pm.getInstalledPackages(PackageManager.PERMISSION_GRANTED);
        for (PackageInfo p : list) {
            if (packageName != null && packageName.equals(p.packageName)) {
                hasInstalled = true;
                break;
            }
        }
        return hasInstalled;
    }


    /**
     * 根据坐标打开第三方地图,跳转到制定位置
     *
     * @param context
     * @param latitude
     * @param longitude
     */
    public static void showMap(Context context, String latitude, String longitude) {
        try {
            Uri geoLocation = Uri.parse("geo:" + latitude + "," + longitude);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(geoLocation);
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据号码跳转到拨号页面
     *
     * @param context
     * @param phoneNumber
     */
    public static void dialPhoneNumber(Context context, String phoneNumber) {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("tel:" + phoneNumber));
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据Email跳转到发送邮件
     *
     * @param context
     */
    public static void sendEmail(Context context, String email) {
        try {
            Intent data = new Intent(Intent.ACTION_SENDTO);
            data.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            data.setData(Uri.parse(email));
            data.putExtra(Intent.EXTRA_SUBJECT, "");
            data.putExtra(Intent.EXTRA_TEXT, "");
            if (data.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 比较两个日期大小
     *
     * @param context
     */
    public static Long compare(Context context, String time1, String time2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse(time1);
        Date d2 = sdf.parse(time2);
        Log.e("time", d2.getTime() - d1.getTime() + "");
        return d2.getTime() - d1.getTime();
    }


    /**
     * 判断程序是否已经启动
     *
     * @param context
     */
    public static boolean isPre(Context context) {
        ActivityManager _ActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        RunningTaskInfo runningTaskInfo = _ActivityManager.getRunningTasks(1).get(0);// 这个地方需要在清单中配置权限
        return runningTaskInfo.baseActivity.getPackageName().equals(context.getPackageName()) ? true
                : false;
    }


    /**
     * 通过包名启动activity
     *
     * @param context
     * @param packageName
     */
    public static void runAppWithPackageName(Activity context, String packageName) {
        PackageInfo pi;
        try {
            pi = context.getPackageManager().getPackageInfo(packageName, 0);
            Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
            resolveIntent.setPackage(pi.packageName);
            PackageManager pManager = context.getPackageManager();
            List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);


            ResolveInfo ri = apps.iterator().next();
            if (ri != null) {
                packageName = ri.activityInfo.packageName;
                String className = ri.activityInfo.name;
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName cn = new ComponentName(packageName, className);
                intent.setComponent(cn);
                context.startActivity(intent);
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }


    }


    public static void runAppWithPackageNameLocal(Activity context, String packageName) {
        try {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName(context.getPackageName(), packageName);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cn);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 转换uri
     *
     * @param uriString
     * @return
     */
    public static Uri uriParse(String uriString) {
        uriString = uriString != null ? uriString : "";
        if (uriString.startsWith("file://")) {
            uriString = uriString.replace("#", "%23");
        }
        return Uri.parse(uriString);
    }


    /* 一个获得当前进程的名字的方法 */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


    /**
     * 发送短信-调用发件箱
     *
     * @param context
     * @param mobile
     * @param smsContent
     */
    public static void sendSMS(Context context, String mobile, String smsContent) {
        Uri uri = Uri.parse("smsto:" + mobile);
        Intent it = new Intent(Intent.ACTION_SENDTO, uri);
        it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        it.putExtra("sms_body", smsContent);
        context.startActivity(it);
    }


    /**
     * Computes the widest view in an adapter, best used when you need to wrap_content on a ListView, please be careful
     * and don't use it on an adapter that is extremely numerous in items or it will take a long time.
     *
     * @param context Some context
     * @param adapter The adapter to process
     * @return The pixel width of the widest View
     */
    public static int getWidestView(Context context, Adapter adapter) {
        int maxWidth = 0;
        View view = null;
        FrameLayout fakeParent = new FrameLayout(context);
        for (int i = 0, count = adapter.getCount(); i < count; i++) {
            view = adapter.getView(i, view, fakeParent);
            view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int width = view.getMeasuredWidth();
            if (width > maxWidth) {
                maxWidth = width;
            }
        }
        return maxWidth;
    }




    public static String readAssetsResourceVersion(Context context) {


        try {
            Properties properties = new Properties();
            properties.load(context.getAssets().open("www/readme/dream.txt"));
            String resourceVersion = properties.getProperty("version", "0");
            return resourceVersion;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }


    public static String readLocalResourceVersion(Context context) {
        try {
            File dirFile = StorageUtils.getInternalFilesDirectory(context, StaticField.LOCAL_ASSETS_DIR);
            File propertiesFile = new File(dirFile, "www/readme/dream.txt");
            if (!propertiesFile.exists()) {
                return null;
            }
            Properties properties = new Properties();
            FileInputStream fis = new FileInputStream(propertiesFile);
            properties.load(fis);
            String resourceVersion = properties.getProperty("version", "0");
            fis.close();
            return resourceVersion;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;


    }


    public static int compareResVersion(String assetsVersionStr, String localVersionStr) {
// int assetsVersion = 0;
// if(assetsVersionStr != null){
// String versionInt = assetsVersionStr.replace(".","");
// if(versionInt.matches("\\d+")){
// assetsVersion = Integer.valueOf(versionInt);
// }
// }
// int localVersion = 0;
// if(localVersionStr != null){
// String versionInt = localVersionStr.replace(".","");
// if(versionInt.matches("\\d+")){
// localVersion = Integer.valueOf(versionInt);
// }
// }
        if (null == assetsVersionStr) {
            return 0;
        }
        if (null == localVersionStr) {
            return 1;
        }


        int compareResult = assetsVersionStr.compareTo(localVersionStr);
        if (compareResult > 0) {
            return 1;
        } else if (compareResult < 0) {
            return -1;
        } else {
            return 0;
        }
    }




    /**
     * 获取网络返回类型 -1 错误 或 无网络
     * 0 mobile 1 wifi
     *
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        try {
            Log.i("test", "context:" + context);
            ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectMgr.getActiveNetworkInfo();
            if (info != null) {
                return info.getType();
            } else {
                return -1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }




    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }




    public static String saveScreenBitMap(Activity activity, View v) {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.CHINA);
        File dirFile = StorageUtils.getOwnCacheDirectory(activity, StaticField.SDCARD_PATH_CAN_CLEAR);
        String fileName = "temp_screenshot_" + sdf.format(new Date()) + ".jpg";


        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int w = size.x;
        int h = size.y;
        Bitmap bitmap = null;
        try {
            bitmap = Bitmap.createBitmap(w, h, Config.RGB_565);
            View decorView = activity.getWindow().getDecorView();
            decorView.setDrawingCacheEnabled(true);
            bitmap = decorView.getDrawingCache();
        } catch (Exception e) {
            e.printStackTrace();
        }


        if (bitmap != null) {
            Log.i("test", "bitmap got!");
            try {
                File outFile = new File(dirFile, fileName);
                FileOutputStream out = new FileOutputStream(outFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 75, out);
                Log.i("test", "file" + outFile.getAbsolutePath() + "output done.");
                bitmap.recycle();
                return outFile.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.i("test", "bitmap is NULL!");
        }
        return null;


    }


public static String getMimeType(String filePath) {
final String defaultMime = "application/octet-stream";
String mime = defaultMime;
if (filePath != null) {
try{
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(filePath);
mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
if(TextUtils.isEmpty(mime)){
mime = defaultMime;
}
} catch (Exception e) {
return mime;
}
}
return mime;
}


    public static void sendNotification(Context context,PendingIntent messagePendingIntent,String title,
                                 String content){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setCategory(Notification.CATEGORY_MESSAGE);
        builder.setContentIntent(messagePendingIntent);
        builder.setAutoCancel(true);
        builder.setContentTitle(title);
        builder.setContentText(content);
        builder.setDefaults(Notification.DEFAULT_SOUND);
        NotificationManager messageNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        messageNotificationManager.notify(1, builder.build());// 永远只收一条消息
    }


}
0 0
原创粉丝点击