SystemTools.java 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
package com.cnlive.gundam.user.util;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.StrictMode;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.widget.EditText;
import android.widget.Toast;

import com.cnlive.gundam.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SystemTools {

    private static final String DOWNLOAD_PICTURE_PATH = "/com.cnlive.digitalcinema/picture/";

    public final static boolean isScreenLocked(Context c) {
        KeyguardManager mKeyguardManager = (KeyguardManager) c
                .getSystemService(Context.KEYGUARD_SERVICE);
        return !mKeyguardManager.inKeyguardRestrictedInputMode();
    }

    public static String saveDrawableToSdcard(Context context, int resID) {
        return saveBitmapToSdcard(context, BitmapFactory.decodeResource(context.getResources(), resID));
    }

    public static String saveBitmapToSdcard(Context context, Bitmap bm) {
        File f = new File(context.getExternalCacheDir().getAbsolutePath() + "/", "sharePicName.png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f.getAbsolutePath();
    }

    // 保存图片到sd卡
    public static void saveToSdcard(Context context, Bitmap bm, String title) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOAD_PICTURE_PATH);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            String target = file.getAbsolutePath() + "/" + title + ".png";
            File imageFile = new File(target);
            imageFile.createNewFile();
            FileOutputStream out = new FileOutputStream(imageFile);
            bm.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            //发送广播,刷新相册
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(imageFile);
            intent.setData(uri);
            if (context != null)
                context.sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过文件名来判断,是否本地有此图片
            drawable = Drawable.createFromStream(
                    new URL(imageUrl).openStream(), "image.jpg");
        } catch (IOException e) {
            Log.d("test", e.getMessage());
        }
        if (drawable == null) {
            Log.d("test", "null drawable");
        } else {
            Log.d("test", "not null drawable");
        }

        return drawable;
    }

    public static final String getShowTime(Date date) {
        String show_time = "";
        long difference = (new Date().getTime() - date.getTime()) / 1000; //分钟

        if (difference < 30) {
            show_time = "刚刚";
        } else if (difference >= 30 && difference < 60) {
            show_time = difference + "秒前";
        } else if (difference >= 60 && difference < 3600) {
            show_time = difference / 60 + "分钟前";
        } else if (difference >= 3600 && difference < 86400) {
            show_time = difference / 60 / 60 + "小时前";
        } else if (difference >= 86400 && difference < 172800) {
            show_time = "昨天";
        } else if (difference >= 172800 && difference < 230400) {
            show_time = "前天";
        } else if (difference >= 230400 && difference < 259200) {
            show_time = "3天前";
        } else if (difference >= 259200 && difference < 345600) {
            show_time = "4天前";
        } else if (difference >= 345600 && difference < 432000) {
            show_time = "5天前";
        } else if (difference >= 432000 && difference < 518000) {
            show_time = "6天前";
        } else if (difference >= 518000 && difference < 604400) {
            show_time = "7天前";
        } else if (difference >= 604400) {
            try {
                show_time = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault()).format(date);
            } catch (Exception e) {
                Log.e("Date", "error ", e);
            }
        }
        return show_time;
    }

    public static String getSystemDateTime() {
        return android.text.format.DateFormat.format("yyyy.MM.dd/kk:mm",
                new Date()).toString();
    }

    public static int getCurrentTime() {
        Time localTime = new Time("Asia/Hong_Kong");
        localTime.setToNow();
        return Integer.valueOf(localTime.format("%H%M"));
    }

    public static int getCurrentDate() {
        Time localTime = new Time("Asia/Hong_Kong");
        localTime.setToNow();
        return Integer.valueOf(localTime.format("%Y%m%d"));
    }

    /**
     * @param err_msg
     * @return
     * @description 规定EditText输入长度
     */
    public static void lengthFilter(final Context context,
                                    final EditText editText, final int max_length, final String err_msg) {

        InputFilter[] filters = new InputFilter[1];

        filters[0] = new InputFilter.LengthFilter(max_length) {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                int destLen = getCharacterNum(dest.toString()); // 获取字符个数(一个中文算2个字符)
                int sourceLen = getCharacterNum(source.toString());
                if (destLen + sourceLen > max_length) {
                    editText.setText(dest.toString());
                    Toast toast = Toast.makeText(context, err_msg,
                            Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    return "";
                }
                return source;
            }
        };
        editText.setFilters(filters);
    }

    /**
     * @param content
     * @return
     * @description 获取一段字符串的字符个数(包含中英文,一个中文算2个字符)
     */
    public static int getCharacterNum(final String content) {
        if (null == content || "".equals(content)) {
            return 0;
        } else {
            return (content.length() + getChineseNum(content));
        }
    }

    /**
     * @param s
     * @return
     * @description 返回字符串里中文字或者全角字符的个数
     */
    public static int getChineseNum(String s) {

        int num = 0;
        char[] myChar = s.toCharArray();
        for (int i = 0; i < myChar.length; i++) {
            if ((char) (byte) myChar[i] != myChar[i]) {
                num++;
            }
        }
        return num;
    }

    public static InputStream readURLInputStream(String URL) throws Exception {
        java.net.URL sourceUrl;
        URLConnection conn;
        sourceUrl = new URL(URL);
        conn = sourceUrl.openConnection();
        conn.setConnectTimeout(7000);
        return conn.getInputStream();
    }

    /**
     * 获取网络文件长度
     *
     * @param downloadUrl
     * @return
     * @throws IOException
     */
    @TargetApi(9)
    public static int getNetFileLength(String downloadUrl) {
        int fileSize = 0;
        try {
            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                        .permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 建立连接
            conn.setConnectTimeout(6 * 1000);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            conn.setRequestProperty("Referer", downloadUrl);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty(
                    "User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            conn.connect();
            if (conn.getResponseCode() == 200) {
                fileSize = conn.getContentLength();
            }
        } catch (Exception e) {
        }
        return fileSize;
    }

    public static final int LOCAL_FILE_VIDEO = 4;

    public static final int FILE_STREAM_VIDEO = 5;

    public static final int LIVE_STREAM_VIDEO = 6;

    public static Integer getMediaType(String videoPath) {
        if (videoPath.contains("/playlist")) {
            return SystemTools.LIVE_STREAM_VIDEO;
        } else if (videoPath.contains(".m3u8")) {
            return SystemTools.FILE_STREAM_VIDEO;
        } else {
            return SystemTools.LOCAL_FILE_VIDEO;
        }
    }

    public static byte[] getBytes(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = is.read(b, 0, 1024)) != -1) {
            baos.write(b, 0, len);
            baos.flush();
        }
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    /**
     * 图片的缩放方法
     *
     * @param bgimage   :源图片资源
     * @param newWidth  :缩放后宽度
     * @param newHeight :缩放后高度
     * @return
     */
    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }

    public static String DownloadFile(String path, String string_url, String file_name) {
        // 未下载完成
        int buffer_size = 1024;
        HttpURLConnection http = null;
        InputStream is = null;
        RandomAccessFile raf = null;
        try {
            File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
            if (!dir.exists()) {
                dir.mkdirs();
            } else if (!dir.isDirectory()) {
                dir.delete();
                dir.mkdirs();
            }
            String filePath = dir.getAbsolutePath() + "/" + file_name;
            File f = new File(filePath);
            if (f.exists()) {
            }

            URL url = new URL(string_url);
            http = (HttpURLConnection) url.openConnection(); //
            http.setConnectTimeout(5 * 1000);
            http.setRequestMethod("GET");//
            http.setRequestProperty(
                    "Accept",
                    "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
            http.setRequestProperty("Accept-Language", "zh-CN");
            http.setRequestProperty("Referer", url.toString());
            http.setRequestProperty("Charset", "UTF-8");
            http.setRequestProperty(
                    "User-Agent",
                    "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
            http.setRequestProperty("Connection", "Keep-Alive");

            is = http.getInputStream();
            byte[] buffer = new byte[buffer_size];
            int offset = 0;
            int tempLen = 0;

            raf = new RandomAccessFile(filePath, "rwd");//
            raf.seek(0);
            while ((offset = is.read(buffer, 0, buffer_size)) != -1) {
                raf.write(buffer, 0, offset);
                tempLen += offset;
                if (tempLen > buffer_size * 50) {
                    tempLen = 0;
                }
            }
            is.close();
            raf.close();
            return filePath;
        } catch (Exception e) {
            return "";
        } finally {
            if (http != null)
                http.disconnect();
            if (is != null)
                is = null;
            if (raf != null)
                raf = null;
        }
    }

    public static String getTimeFromInt(int time) {
        if (time < 0) {
            return "00:00";
        }

        int secondnd = time / 60;
        int minutesnd = time % 60;

        String f = secondnd >= 10 ? String.valueOf(secondnd) : "0" + String.valueOf(secondnd);
        String m = minutesnd >= 10 ? String.valueOf(minutesnd) : "0" + String.valueOf(minutesnd);

        return f + ":" + m;
    }

    public static String storeImageToFile(Context mContext, Bitmap bitmap, String headName) {
        if (bitmap == null) {
            return null;
        }
        File rootFile = null;
        File file = null;
        RandomAccessFile accessFile = null;
        String path = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/" + "com.cnlive.spring/image";
            rootFile = new File(path);
            if (!rootFile.exists()) {
                rootFile.mkdirs();
            }
            file = new File(path + "/" + headName);
            ByteArrayOutputStream steam = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, steam);
            byte[] buffer = steam.toByteArray();

            try {
                accessFile = new RandomAccessFile(file, "rw");
                accessFile.write(buffer);
            } catch (Exception e) {
                return null;
            }

            try {
                steam.close();
                accessFile.close();
            } catch (IOException e) {
                //Note: do nothing.
            }
        } else {
            ToastUtil.show(mContext, "请检查您的SD卡是否安装!");
        }
        return path;
    }

    public static Bitmap getImageFromAssetsFile(Context context, String fileName) {
        Bitmap image = null;
        AssetManager am = context.getResources().getAssets();
        try {
            InputStream is = am.open(fileName);
            image = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;

    }

    /**
     * 验证手机号码
     *
     * @param mobiles
     * @return [0-9]{5,9}
     */
    public static boolean isMobileNO(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,2-3,5-9]))\\d{8}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isPwd(String pwd) {  //只能是数字和字母
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
            Matcher m = p.matcher(pwd);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static boolean isNickName(String nickName) {  //只能是数字和字母
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^[A-Za-z0-9\\u4E00-\\u9FA5]+$");
            Matcher m = p.matcher(nickName);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    private static float density = 0;

    public static int dip2px(Context context, float dipValue) {
        if (density == 0)
            density = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * density + 0.5f);
    }

    public static String formatTime(int ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;

        int hour = ms / hh;
        int minute = (ms - hour * hh) / mi;
        int second = (ms - hour * hh - minute * mi) / ss;
        int milliSecond = ms - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if (hour > 0 && hour < 10) {
            sb.append("0" + hour + ":");
        } else if (hour >= 10) {
            sb.append(hour + ":");
        } else {
            sb.append("00:");
        }

        if (minute > 0 && minute < 10) {
            sb.append("0" + minute + ":");
        } else if (minute >= 10) {
            sb.append(minute + ":");
        } else {
            sb.append("00:");
        }

        if (second > 0 && second < 10) {
            sb.append("0" + second);
        } else if (second >= 10) {
            sb.append(second);
        } else {
            sb.append("00");
        }
        return sb.toString();
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = context.getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证邮箱 return true 为有效地址
     */
    public static boolean isEmailValid(String url) {
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}");
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
        Matcher m = p.matcher(url);
        boolean b = m.matches();
        return b;
    }

    public static boolean checkNetwork(Context context) {
        if (context == null) return false;
        if (NetworkUtil.isConnectInternet(context.getApplicationContext())) {
            return true;
        } else {
            Toast.makeText(context.getApplicationContext(), context.getString(R.string.net_connect_toast), Toast.LENGTH_SHORT).show();
            return false;
        }
    }
}