Android UserUtils

Android Utils


public class UserUtils {
    /**
     * 地图中绘制多边形、圆形的边界颜色
     *
     * @since 3.3.0
     */
    public static final int STROKE_COLOR = Color.argb(180, 63, 145, 252);
    /**
     * 地图中绘制多边形、圆形的填充颜色
     *
     * @since 3.3.0
     */
    public static final int FILL_COLOR = Color.argb(163, 118, 212, 243);

    /**
     * 地图中绘制多边形、圆形的边框宽度
     *
     * @since 3.3.0
     */
    public static final float STROKE_WIDTH = 5F;
    public final static int AVATAR = 1, UPLOAD = 2;
    public static int currentMode = 2; //全局变量决定使用avatar/upload上传
    private  static long lastClickTime=0;//上次点击的时间
    private  static int spaceTime = 800;//时间间隔

    /**
     * 防止按钮连续点击
     * 每次点击button的时候,获取当前的时间,然后对比上一次的时间,两者的差值如果小于某个规定的时间,则判断为快速点击。
     */
    public synchronized static boolean isFastClick() {
        long currentTime = System.currentTimeMillis();//当前系统时间
        boolean isAllowClick;//是否允许点击
        if (currentTime - lastClickTime < spaceTime) {
            isAllowClick = true;
        } else {
            isAllowClick = false;
        }
        lastClickTime = currentTime;
        return isAllowClick;
    }

    public static int getCurrentMode() {
        return currentMode;
    }

    public static boolean isLogin() {
        if (TextUtils.isEmpty(LocalUserDataModel.accesstoken) || TextUtils.isEmpty(LocalUserDataModel.userName)) {
            return false;
        } else {
            return true;
        }
    }

    //PHOTO = 1, IN_IMG = 2;
    public static void uploadImage(int iType, final String imgPath) {
        currentMode = 2; //复位为普通图片上传,这样的话每次头像上传都需要先设置上传模式为头像上传
        String str = "";
        switch (iType) {
            case AVATAR://头像
                str = UrlConstants.HOST + "/upload/portraitImage";
                break;
            case UPLOAD://认证图片
                str = UrlConstants.HOST + "/file/upload";
                break;
        }
        final String fileName = imgPath.substring(imgPath.lastIndexOf("/") + 1);
        final String finalStr = str;
        new Thread() {
            public void run() {
                try {
                    URL url = new URL(finalStr);
                    String boundary = "******";
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("image", fileName);
                    connection.setRequestProperty("username", LocalUserDataModel.userName);
                    connection.setRequestProperty("plateform", "2");
                    connection.setRequestProperty("accesstoken", LocalUserDataModel.accesstoken);
//                        connection.setRequestProperty("Content-Type",
//                                "multipart/form-data;boundary=" + boundary);
                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    //读取文件上传到服务器
                    File file = new File(imgPath);
                    FileInputStream fileInputStream = new FileInputStream(file);
                    byte[] bytes = new byte[1024];
                    int numReadByte;
                    while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
                        out.write(bytes, 0, numReadByte);
                    }
                    out.flush();
                    fileInputStream.close();
                    //读取URLConnection的响应
                    InputStream in = connection.getInputStream();
                    // 得到响应码
                    int res = connection.getResponseCode();

                    StringBuilder sb2 = new StringBuilder();
                    BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
                    String Line;
                    while ((Line = br.readLine()) != null) {
                        sb2.append(Line);
                    }
                    out.close();
                    connection.disconnect();

//                        return sb2.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

//            return null;
    }

    public static void saveBitmapToFile(Bitmap bitmap, String path) {
        BufferedOutputStream os = null;
        try {
            File file = new File(path);
            int end = path.lastIndexOf(File.separator);
            String _filePath = path.substring(0, end);
            File filePath = new File(_filePath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            file.createNewFile();
            os = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bitmap != null) {
                bitmap.recycle();
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String htmlPrepare(String content) {
        String header = "\n" +
                "\n" +
                "\n";
        String tail = "\n" +
                "\n";
        String htmlContent = header + content + tail;
        return htmlContent;
    }


    //获取App版本
    public static PackageInfo getAppVersion(Context context) {
        PackageInfo pinfo = null;
        try {
            pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        Integer versionCode = pinfo.versionCode; // 1
        String versionName = pinfo.versionName; // 1.0
        return pinfo;
    }

    //版本更新
    public static void checkUpdate(Context context, boolean showNoUpdateUI) {
//        UpdateManager manager = new UpdateManager(context);
//
//        UpdateOptions options = new UpdateOptions.Builder(context)
//                .checkUrl("http://www.matrix2d.com/bein/info.json")
//                .updateFormat(UpdateFormat.JSON)
//                .updatePeriod(new UpdatePeriod(UpdatePeriod.EACH_TIME))
//                .checkPackageName(true)
//                .showNoUpdateUI(showNoUpdateUI)
//                .build();
//        manager.check(context, options);
    }

    public static void showAlertDialog(@Nullable String title, @Nullable String message,
                                       @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                       @NonNull String positiveText,
                                       @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                       @NonNull String negativeText, @NonNull Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        builder.show();
    }

    //时间转换成unix格式
    //param:format "yyyy-MM-dd" 任何时间格式都可以
    public static long timeToUnix(String time, String format) {
        long unixTime;
        SimpleDateFormat sf = new SimpleDateFormat(format);
        Date date = new Date();
        try {
            date = sf.parse(time);
            unixTime = date.getTime();
            return unixTime;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return -1;
    }

    //unix转换成时间
    //format: "yyyyMMdd HH:mm:ss"
    public static String unixToTime(long UnixTimestamp, String format) {
        String date = new java.text.SimpleDateFormat(format).format(new java.util.Date(UnixTimestamp * 1000));
        return date;
    }

    public static long getCurrentUnixTime() {
        long UnixTimestamp = System.currentTimeMillis() / 1000L;
        return UnixTimestamp;
    }

    /**
     * 获取阶段性日期
     *
     * @param dateline
     * @return
     */
    public static String getPeriodDate(long dateline) {
        long minute = 60;// 1分钟
        long hour = 60 * minute;// 1小时
        long day = 24 * hour;// 1天
        long month = 31 * day;// 月
        long year = 12 * month;// 年

        if (dateline == 0) {
            return null;
        }
        long diff = Long.valueOf(String.valueOf(new Date().getTime()).substring(0, 10)) - dateline;
        if (diff >= 2 * day) {
            return unixToTime(dateline, "MM-dd HH:mm");
        }
        if (diff >= day && diff < 2 * day) {
            return "昨天" + unixToTime(dateline, " HH:mm");
        }
        /*long r = 0;
        if (diff > year) {
            r = (diff / year);
            return r + "年前";
        }
        if (diff > month) {
            r = (diff / month);
            return r + "个月前";
        }
        if (diff > day) {
            r = (diff / day);
            return r + "天前";
        }
        if (diff > hour) {
            r = (diff / hour);
            return r + "个小时前";
        }
        if (diff > minute) {
            r = (diff / minute);
            return r + "分钟前";
        }*/
        return "今天" + unixToTime(dateline, " HH:mm");
    }

    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    public static int dip2px(Context context, float px) {
        final float scale = getScreenDensity(context);
        return (int) (px * scale + 0.5);
    }

    //base64解码
    public static String base64Decode(String content) {
        if (TextUtils.isEmpty(content)) return "";

        final byte data[] = Base64.decode(content, Base64.DEFAULT);
        String text = null;
        try {
            text = new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return text;
    }

    //base64编码
    public static String base64encode(String content) {
        byte[] bytes = content.getBytes();
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = "";
        try {
            encodeString = new String(encode, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeString;
    }

    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    /**************************************************************************************************/
    /**
     * 阿里云图片上传
     */
    public static void getAliYunPath(final Context context, final String path, final BeinCallBackListener beinCallBackListener) {
        OSS oss;
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider("LTAIarzd41OS5sPA", "cpcPY6FDsfJ5Bq9RpzgWXlIKM3qIAq");
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时,默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时,默认15秒
        conf.setMaxConcurrentRequest(8); // 最大并发请求数,默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数,默认2次

        // oss为全局变量,OSS_ENDPOINT是一个OSS区域地址
        oss = new OSSClient(context, "oss-cn-shanghai.aliyuncs.com", credentialProvider, conf);
//        生成一个新路径
        String newpath = "android/" + LocalUserDataModel.userName + "/";
        Calendar c = Calendar.getInstance();
        String month = unixToTime(getCurrentUnixTime(), "yyyyMM");
        newpath = newpath + month + "/"
                + String.valueOf(c.get(Calendar.DAY_OF_MONTH)) + "/"
                + c.getTimeInMillis() + "_" + UserUtils.randomInt()
                + path.substring(path.indexOf("."), path.length());
        PutObjectRequest put = new PutObjectRequest("isbein", newpath, path);
        put.setProgressCallback(new OSSProgressCallback() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        final String finalNewpath = newpath;
        final OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                beinCallBackListener.onSuccess("http://oss.isbein.com/" + finalNewpath);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // Request exception
                if (clientExcepion != null) {
                    // Local exception, such as a network exception
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // Service exception
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                beinCallBackListener.onSuccess("");
            }
        });
    }

    /**
     * 随机生成8位数字字符串
     *
     * @return
     */
    public static String randomInt() {
        String randomNum = String.valueOf(Math.random());
        randomNum = randomNum.replace(".", "");
        randomNum = randomNum.substring(0, 8);
        return randomNum;
    }

    /**
     * 分享
     *
     * @param activity
     * @param url
     * @param title
     * @param recommendReason
     * @param imageUrl
     * @param shareListener
     */
    public static void travelOutShare(final Activity activity, final String url, final String title, final String recommendReason, final String imageUrl, final UMShareListener shareListener) {
        final SnsPlatform weixin = SHARE_MEDIA.WEIXIN.toSnsPlatform();
        final SnsPlatform weiCircle = SHARE_MEDIA.WEIXIN_CIRCLE.toSnsPlatform();
        final SnsPlatform sina = SHARE_MEDIA.SINA.toSnsPlatform();
        final SnsPlatform qq = SHARE_MEDIA.QQ.toSnsPlatform();
        final SnsPlatform more = SHARE_MEDIA.MORE.toSnsPlatform();
        new ShareAction(activity).withText("hello")
                .addButton("app_name", "app_name", "bein_icon", "bein_icon")
                .addButton(weixin.mShowWord, weixin.mKeyword, weixin.mIcon, weixin.mGrayIcon)
                .addButton(weiCircle.mShowWord, weiCircle.mKeyword, weiCircle.mIcon, weiCircle.mGrayIcon)
                .addButton(sina.mShowWord, sina.mKeyword, sina.mIcon, sina.mGrayIcon)
                .addButton(qq.mShowWord, qq.mKeyword, qq.mIcon, qq.mGrayIcon)
                .addButton(more.mShowWord, more.mKeyword, more.mIcon, more.mGrayIcon)
                .addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Toast.makeText(activity, "复制文本按钮", Toast.LENGTH_LONG).show();
                        } else if (snsPlatform.mShowWord.equals("app_name")) {
                            /*Intent toShare = new Intent(activity, ShareReasonActivity.class);
                            toShare.putExtra("title", title);
                            toShare.putExtra("shareId", shareId);
                            toShare.putExtra("image", imageUrl);
                            toShare.putExtra("bname", bname);
                            activity.startActivity(toShare);*/
                        } else {
                            if (snsPlatform.mShowWord.equals(weixin.mShowWord)) {
                                share_media = SHARE_MEDIA.WEIXIN;
                            } else if (snsPlatform.mShowWord.equals(weiCircle.mShowWord)) {
                                share_media = SHARE_MEDIA.WEIXIN_CIRCLE;
                            } else if (snsPlatform.mShowWord.equals(sina.mShowWord)) {
                                share_media = SHARE_MEDIA.SINA;
                            } else if (snsPlatform.mShowWord.equals(qq.mShowWord)) {
                                share_media = SHARE_MEDIA.QQ;
                            } else if (snsPlatform.mShowWord.equals(more.mShowWord)) {
                                share_media = SHARE_MEDIA.MORE;
                            }
                            final SHARE_MEDIA finalShare_media = share_media;
                            if (!url.equals("")) {
                                UMWeb web = new UMWeb(url);
                                web.setTitle(title);
                                web.setDescription(recommendReason);
                                web.setThumb(new UMImage(activity, imageUrl));
                                new ShareAction(activity).withMedia(web)
                                        .setPlatform(finalShare_media)
                                        .setCallback(shareListener)
                                        .share();
                            } else {//五个分享地址,参数1=商家分享.2=线路分享3=霸王餐分享4party分享5.推荐三级

                            }

                        }
                    }
                })
                .setCallback(shareListener)
                .open();
    }

    public static int[] calcPopupXY(View rootView, View anchor) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        rootView.measure(w, h);
        int popupWidth = rootView.getMeasuredWidth();
        int popupHeight = rootView.getMeasuredHeight();
        Rect anchorRect = getViewAbsoluteLocation(anchor);
        int x = anchorRect.left + (anchorRect.right - anchorRect.left) / 2 - popupWidth / 2;
        int y = anchorRect.top - popupHeight;
        return new int[]{x, y};
    }

    public static Rect getViewAbsoluteLocation(View view) {
        if (view == null) {
            return new Rect();
        }
        // 获取View相对于屏幕的坐标
        int[] location = new int[2];
        view.getLocationOnScreen(location);//这是获取相对于屏幕的绝对坐标,而view.getLocationInWindow(location); 是获取window上的相对坐标,本例中只有一个window,二者等价
        // 获取View的宽高
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
        // 获取View的Rect
        Rect rect = new Rect();
        rect.left = location[0];
        rect.top = location[1];
        rect.right = rect.left + width;
        rect.bottom = rect.top + height;
        return rect;
    }

    /**
     * 语音转换
     *
     * @param json
     * @return
     */
    public static String parseIatResult(String json) {
        StringBuffer ret = new StringBuffer();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                // 转写结果词,默认使用第一个结果
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                JSONObject obj = items.getJSONObject(0);
                ret.append(obj.getString("w"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret.toString();
    }

    /**
     * 联系客服
     */
    public static void goCustomerService(final Context context) {
        LayoutInflater mInflater = LayoutInflater.from(context);
        ViewGroup rootView = (ViewGroup) mInflater.inflate(R.layout.dialog_customer_service, null);
        rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        final Dialog dialog = new Dialog(context);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题,否则会影响高度计算,一定要在setContentView之前调用,终于明白有一个设置theme的构造函数的目的了
        dialog.setContentView(rootView);
        dialog.getWindow().setGravity(Gravity.CENTER);
        dialog.show();
        TextView makeCall = (TextView) rootView.findViewById(R.id.make_call);
        TextView dismissCall = (TextView) rootView.findViewById(R.id.dismiss_call);

        makeCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "400 1234 567"));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });
        dismissCall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    /**
     * 图片压缩
     *
     * @param imagePath
     * @return
     */
    public static String goCompressBitmap(String imagePath) {
        String result = null;
        ByteArrayOutputStream baos = null;
        //压缩图片
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 只获取图片的大小信息,而不是将整张图片载入在内存中,避免内存溢出  
        BitmapFactory.decodeFile(imagePath, options);
        int height = options.outHeight;
        int width = options.outWidth;
        float standardW = 480f;
        float standardH = 800f;
        int inSampleSize = 1; // 默认像素压缩比例,压缩为原图的1/2  
        int minLen = Math.min(height, width); // 原图的最小边长  
        if (minLen > 200) { // 如果原始图像的最小边长大于100dp(此处单位我认为是dp,而非px)  
            float ratio = (float) minLen / 100.0f; // 计算像素压缩比例  
            inSampleSize = (int) ratio;
        }
        if (width > height && width > standardW) {
            inSampleSize = (int) (width / standardW);
        } else if (width < height && height > standardH) {
            inSampleSize = (int) (height / standardH);
        }
        if (inSampleSize <= 0)
            inSampleSize = 1;
        options.inJustDecodeBounds = false; // 计算好压缩比例后,这次可以去加载原图了  
        options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例  
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options); // 解码文件  
        //转成base64字符串
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, 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;
    }

    /**
     * 获取屏幕实际大小
     *
     * @param context
     * @return
     */
    public static Point getRealScreenSize(Context context) {

        Point size = new Point();
        try {
            WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                windowManager.getDefaultDisplay().getRealSize(size);
            } else {
                try {
                    Method mGetRawW = Display.class.getMethod("getRawWidth");
                    Method mGetRawH = Display.class.getMethod("getRawHeight");
                    size.set((Integer) mGetRawW.invoke(windowManager.getDefaultDisplay()), (Integer) mGetRawH.invoke(windowManager.getDefaultDisplay()));
                } catch (Exception e) {
                    size.set(windowManager.getDefaultDisplay().getWidth(), windowManager.getDefaultDisplay().getHeight());
                }
            }
        } catch (Exception e) {
        }
        return size;
    }

    /**
     * 获取 url里key为name的值
     *
     * @param url
     * @param name
     * @return
     */
    public static String queryParam(String url, String name) {
        Pattern pattern = Pattern.compile("(^|[?&])" + name + "=([^&]*)(&|$)");
        Matcher matcher = pattern.matcher(url);
        StringBuffer buffer = new StringBuffer();
        String con = "";

        while (matcher.find()) {
            con = matcher.group();
            buffer.append(con + " ");
        }

        String ret = buffer.toString().trim();

        if (ret.contains("&") && ret.lastIndexOf("&") == ret.length() - 1) {
            ret = ret.substring(ret.indexOf("=") + 1, ret.length() - 1);
        } else {
            if (TextUtils.isEmpty(ret)) {
                return "";
            } else {
                ret = ret.substring(ret.indexOf("=") + 1, ret.length());
            }
        }
        return ret;
    }

}

你可能感兴趣的:(Android UserUtils)