PageRenderTime 80ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/src/com/wqdsoft/im/global/FeatureFunction.java

https://gitlab.com/Er_Hei/PlayCar
Java | 1360 lines | 1011 code | 192 blank | 157 comment | 208 complexity | cf32378cad282842c6fe21c75a39b5d9 MD5 | raw file
  1. package com.wqdsoft.im.global;
  2. import java.io.BufferedOutputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.lang.reflect.Field;
  11. import java.net.HttpURLConnection;
  12. import java.net.MalformedURLException;
  13. import java.net.URL;
  14. import java.security.MessageDigest;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.text.Collator;
  17. import java.text.DecimalFormat;
  18. import java.text.ParseException;
  19. import java.text.SimpleDateFormat;
  20. import java.util.Calendar;
  21. import java.util.Date;
  22. import java.util.GregorianCalendar;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Locale;
  26. import java.util.Map;
  27. import java.util.regex.Matcher;
  28. import java.util.regex.Pattern;
  29. import android.app.ActivityManager;
  30. import android.app.ActivityManager.RunningAppProcessInfo;
  31. import android.content.Context;
  32. import android.content.pm.PackageInfo;
  33. import android.content.pm.PackageManager;
  34. import android.database.Cursor;
  35. import android.graphics.Bitmap;
  36. import android.graphics.BitmapFactory;
  37. import android.graphics.BitmapFactory.Options;
  38. import android.net.Uri;
  39. import android.os.Environment;
  40. import android.provider.MediaStore.MediaColumns;
  41. import android.text.TextUtils;
  42. import android.util.Base64;
  43. import android.util.Log;
  44. import com.alibaba.fastjson.JSON;
  45. import com.google.zxing.BarcodeFormat;
  46. import com.google.zxing.MultiFormatWriter;
  47. import com.google.zxing.WriterException;
  48. import com.google.zxing.common.BitMatrix;
  49. import com.playcar.R;
  50. import com.wqdsoft.im.exception.SPException;
  51. import com.wqdsoft.im.map.BMapApiApp;
  52. import com.wqdsoft.im.net.IMInfo;
  53. import com.wqdsoft.im.service.PhpServiceThread;
  54. public class FeatureFunction {
  55. private static final String TAG = "FeatureFunction";
  56. private static final int ONE_MINUTE = 60; // Seconds
  57. private static final int ONE_HOUR = 60 * ONE_MINUTE;
  58. private static final int ONE_DAY = 24 * ONE_HOUR;
  59. public static final String PUB_TEMP_DIRECTORY = "/IM/";
  60. public static byte[] getImage(URL path, File file) throws SPException{
  61. HttpURLConnection conn = null;
  62. InputStream is = null;
  63. byte[] imgData = null;
  64. try {
  65. URL url = path;
  66. conn = (HttpURLConnection) url.openConnection();
  67. is = conn.getInputStream();
  68. // Get the length
  69. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  70. byte[] temp = new byte[512];
  71. int readLen = 0;
  72. int destPos = 0;
  73. while ((readLen = is.read(temp)) > 0) {
  74. bos.write(temp, 0, readLen);
  75. destPos += readLen;
  76. }
  77. if (destPos != 0) {
  78. imgData = new byte[destPos];
  79. System.arraycopy(bos.toByteArray(), 0, imgData, 0, destPos);
  80. // Save to cache
  81. if (file != null){
  82. writeBitmapToCache(imgData, file);
  83. }
  84. }
  85. if(is != null){
  86. is.close();
  87. }
  88. if(conn != null){
  89. conn.disconnect();
  90. }
  91. } catch (MalformedURLException e) {
  92. e.printStackTrace();
  93. } catch (IOException e) {
  94. e.printStackTrace();
  95. }catch (OutOfMemoryError e){
  96. //throw new SPException(R.string.exception_out_of_memory);
  97. }
  98. return imgData;
  99. }
  100. private static void writeBitmapToCache(byte[] imgData, File file) {
  101. FileOutputStream fos = null;
  102. BufferedOutputStream outPutBuffer = null;
  103. if (file != null) {
  104. try {
  105. if (!file.exists()) {
  106. file.createNewFile();
  107. }
  108. fos = new FileOutputStream(file);
  109. outPutBuffer = new BufferedOutputStream(fos);
  110. outPutBuffer.write(imgData);
  111. outPutBuffer.flush();
  112. fos.flush();
  113. } catch (IOException e) {
  114. e.printStackTrace();
  115. } finally {
  116. try {
  117. if (fos != null) {
  118. fos.close();
  119. }
  120. if (outPutBuffer != null) {
  121. outPutBuffer.close();
  122. }
  123. } catch (IOException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. }
  128. }
  129. public static Bitmap downLoadImage(final String mImageUrl){
  130. Bitmap bitmap = null;
  131. if(mImageUrl != null){
  132. //Log.e("position", "position = " + position);
  133. File file = null;
  134. String fileName = new MD5().getMD5ofStr(mImageUrl);// url.replaceAll("/",
  135. if (FeatureFunction.checkSDCard()) {
  136. if (FeatureFunction.newFolder(Environment.getExternalStorageDirectory()
  137. + ImageLoader.SDCARD_PICTURE_CACHE_PATH)) {
  138. file = new File(
  139. Environment.getExternalStorageDirectory()
  140. + ImageLoader.SDCARD_PICTURE_CACHE_PATH, fileName);
  141. if(file != null && file.exists()){
  142. try {
  143. FileInputStream fin = new FileInputStream(file.getPath());
  144. int length = fin.available();
  145. byte[] buffer = new byte[length];
  146. fin.read(buffer);
  147. fin.close();
  148. bitmap = BitmapFactory.decodeByteArray(buffer, 0,
  149. buffer.length);
  150. } catch (FileNotFoundException e) {
  151. e.printStackTrace();
  152. } catch (IOException e) {
  153. e.printStackTrace();
  154. }
  155. }else{
  156. if (IMCommon.getNetWorkState()){
  157. bitmap = loadImageFromUrl(mImageUrl,file);
  158. }
  159. }
  160. }
  161. }
  162. }
  163. return bitmap;
  164. }
  165. private static Bitmap loadImageFromUrl(String urlString, File file) {
  166. Bitmap bitmap = null;
  167. HttpURLConnection conn = null;
  168. InputStream is = null;
  169. try {
  170. URL url = new URL(urlString);
  171. conn = (HttpURLConnection) url.openConnection();
  172. is = conn.getInputStream();
  173. // Get the length
  174. int length = (int) conn.getContentLength();
  175. if (length != -1) {
  176. ByteArrayOutputStream outstream = new ByteArrayOutputStream();
  177. //byte[] imgData = new byte[length];
  178. byte[] temp = new byte[512];
  179. int readLen = 0;
  180. int destPos = 0;
  181. while ((readLen = is.read(temp)) > 0) {
  182. outstream.write(temp, 0, readLen);
  183. destPos += readLen;
  184. }
  185. byte[] imgData = new byte[destPos];
  186. System.arraycopy(outstream.toByteArray(), 0, imgData, 0, destPos);
  187. bitmap = BitmapFactory.decodeByteArray(imgData, 0,
  188. imgData.length);
  189. // Save to cache
  190. if (file != null){
  191. writeBitmapToCache(imgData, file);
  192. }
  193. }
  194. if (is != null) {
  195. is.close();
  196. }
  197. if (conn != null) {
  198. conn.disconnect();
  199. }
  200. } catch (MalformedURLException e) {
  201. e.printStackTrace();
  202. } catch (IOException e) {
  203. e.printStackTrace();
  204. } catch (OutOfMemoryError e) {
  205. e.printStackTrace();
  206. }
  207. return bitmap;
  208. }
  209. /**
  210. * Try to decode a image file with file path
  211. *
  212. * @param filePath
  213. * image file path
  214. * @param quanlity
  215. * the compress rate
  216. * @param autoCompress
  217. * if need to compress more if OOM occurs
  218. * @return the decoded bitmap or null if failed
  219. */
  220. public static Bitmap tryToDecodeImageFile(String filePath, int quanlity,
  221. boolean autoCompress) {
  222. Bitmap bitmap = null;
  223. try {
  224. if (quanlity == 1) {
  225. bitmap = BitmapFactory.decodeFile(filePath);
  226. } else {
  227. BitmapFactory.Options options = new Options();
  228. options.inSampleSize = quanlity;
  229. bitmap = BitmapFactory.decodeFile(filePath, options);
  230. }
  231. } catch (OutOfMemoryError oe) {
  232. if (autoCompress) {
  233. int rate = (quanlity >= 4) ? 2 : 4;
  234. Log.d(TAG, "Decode the file automatically with quanlity :"
  235. + quanlity * rate);
  236. bitmap = tryToDecodeImageFile(filePath, quanlity * rate, false);
  237. } else {
  238. Log.e(TAG, "Decode the file failed!, out of memory!");
  239. oe.printStackTrace();
  240. }
  241. } catch (Exception e) {
  242. e.printStackTrace();
  243. }
  244. return bitmap;
  245. }
  246. /**
  247. * Check SD card
  248. *
  249. * @return true if SD card is mounted
  250. */
  251. public static boolean checkSDCard() {
  252. if (Environment.getExternalStorageState().equals(
  253. Environment.MEDIA_MOUNTED))
  254. return true;
  255. else
  256. return false;
  257. }
  258. /**
  259. * @author LuoB.
  260. * @param oldTime 较小的时间
  261. * @param newTime 较大的时间 (如果为空 默认当前时间 ,表示和当前时间相比)
  262. * @return -1 :同一天. 0:昨天 . 1 :至少是前天.
  263. * @throws ParseException 转换异常
  264. */
  265. public static int isYeaterday(Date oldTime,Date newTime) throws ParseException{
  266. if(newTime==null){
  267. newTime=new Date();
  268. }
  269. //将下面的 理解成 yyyy-MM-dd 00:00:00 更好理解点
  270. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  271. String todayStr = format.format(newTime);
  272. Date today = format.parse(todayStr);
  273. //昨天 86400000=24*60*60*1000 一天
  274. if((today.getTime()-oldTime.getTime())>0 && (today.getTime()-oldTime.getTime())<=86400000) {
  275. return 0;
  276. }
  277. else if((today.getTime()-oldTime.getTime())<=0){ //至少是今天
  278. return -1;
  279. }
  280. else{ //至少是前天
  281. return 1;
  282. }
  283. }
  284. public static String calculaterReleasedTime(Context context, Date date,long time,long lastMsgTime) {
  285. Date currentDate = new Date();
  286. long duration = (currentDate.getTime() - date.getTime()) / 1000; // Seconds
  287. if(lastMsgTime!=0){
  288. //long checkDuration = (new Date(time).getTime() - new Date(lastMsgTime).getTime()) / 1000; // Seconds
  289. long duration1 = (time - lastMsgTime) / 1000;
  290. if(duration1 <=3*ONE_MINUTE){
  291. return "";
  292. }
  293. }
  294. try {
  295. if(isYeaterday(date, currentDate) ==0){
  296. SimpleDateFormat format =null;
  297. if(lastMsgTime == 0){
  298. format =new SimpleDateFormat("MM月dd日"); //new SimpleDateFormat("HH:mm:ss");
  299. }else{
  300. format =new SimpleDateFormat("HH:mm"); //new SimpleDateFormat("HH:mm:ss");
  301. }
  302. return format.format(date);
  303. }
  304. } catch (ParseException e) {
  305. e.printStackTrace();
  306. }
  307. // Not normal
  308. if (currentDate.before(date)) {
  309. if (Math.abs(duration) < ONE_MINUTE * 5) {//不足一分钟
  310. return context.getString(R.string.just_now);
  311. } else {
  312. return getDateString(context, date,
  313. currentDate.getYear() != date.getYear(),lastMsgTime!=0?true:false);
  314. }
  315. }
  316. if (duration >= ONE_DAY) {
  317. return getDateString(context, date,
  318. currentDate.getYear() != date.getYear(),lastMsgTime!=0?true:false);
  319. /*return getTime(time);*/
  320. }else if (duration >= ONE_HOUR) {
  321. /*return duration / ONE_HOUR + context.getString(R.string.hour)
  322. + context.getString(R.string.before);*/
  323. SimpleDateFormat format =new SimpleDateFormat("HH:mm");
  324. return format.format(date);
  325. //return getTime(time,false);
  326. } else if (duration >= ONE_MINUTE) {
  327. return duration / ONE_MINUTE + context.getString(R.string.minutes_time)
  328. + context.getString(R.string.before);
  329. } else {
  330. return duration + context.getString(R.string.second)
  331. + context.getString(R.string.before);
  332. }
  333. }
  334. public static String calculateFileSize(long size) {
  335. if (size < 1024l) {
  336. return size + "B";
  337. } else if (size < (1024l * 1024l)) {
  338. return Math.round((size * 100 >> 10)) / 100.00 + "KB";
  339. } else if (size < (1024l * 1024l * 1024l)) {
  340. return (Math.round((size * 100 >> 20)) / 100.00) + "MB";
  341. } else {
  342. return Math.round((size * 100 >> 30)) / 100.00 + "GB";
  343. }
  344. }
  345. public static String getDateString(Context context, Date date,
  346. boolean withYearString,boolean isShowMM) {
  347. String timeString = "";
  348. SimpleDateFormat format = null;
  349. if (withYearString) {
  350. if(isShowMM){
  351. format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
  352. }else{
  353. format = new SimpleDateFormat("yyyy.MM.dd");
  354. }
  355. }else{
  356. if(isShowMM){
  357. format = new SimpleDateFormat("MM月dd日 HH:mm");
  358. }else{
  359. format = new SimpleDateFormat("MM月dd日 ");
  360. }
  361. }
  362. return format.format(date);
  363. }
  364. public static String getDateStringFormate(Context context, Date date,
  365. boolean withYearString,boolean isShowMins) {
  366. String time = "";
  367. if (withYearString) {
  368. if(isShowMins){
  369. time = (date.getYear() + 1900) + "."
  370. + (date.getMonth() + 1)+"."
  371. + date.getDate()+ " "
  372. + date.getHours()+":"
  373. + date.getMinutes();
  374. }else{
  375. time = (date.getYear() + 1900) + "."
  376. + (date.getMonth() + 1)+"."
  377. + date.getDate();
  378. }
  379. }else{
  380. if(isShowMins){
  381. time = (date.getMonth() + 1) + context.getString(R.string.month)
  382. + date.getDate() + context.getString(R.string.day)
  383. + date.getHours() +":"
  384. + date.getMinutes();
  385. }else{
  386. time = (date.getMonth() + 1) + context.getString(R.string.month)
  387. + date.getDate() + context.getString(R.string.day);
  388. }
  389. }
  390. return time;
  391. }
  392. public static int chineseCompare(String chineseString1,
  393. String chineseString2) {
  394. return Collator.getInstance(Locale.CHINESE).compare(chineseString1,
  395. chineseString2);
  396. }
  397. public static boolean createWholePermissionFolder(String path) {
  398. Log.d(TAG, "+ createWholePermissionFolder()");
  399. Process p;
  400. int status = -1;
  401. boolean isSuccess = false;
  402. try {
  403. File destDir = new File(path);
  404. if (!destDir.exists()) {
  405. destDir.mkdirs();
  406. }
  407. p = Runtime.getRuntime().exec("chmod 777 " + destDir);
  408. status = p.waitFor();
  409. if (status == 0) {
  410. Log.d(TAG, "Modify folder permission success!");
  411. isSuccess = true;
  412. } else {
  413. Log.e(TAG, "Modify folder permission fail!");
  414. }
  415. } catch (Exception e) {
  416. Log.e(TAG, "Modify folder permission exception!: " + e.toString());
  417. }
  418. Log.d(TAG, "- createWholePermissionFolder()");
  419. return isSuccess;
  420. }
  421. public static String saveTempBitmap(Bitmap bitmap, String fileName) {
  422. if (bitmap == null || fileName == null || fileName.length() == 0) {
  423. Log.e(TAG, "saveTempBitmap(), illegal param, bitmap = " + bitmap
  424. + "filename = " + fileName);
  425. return "";
  426. }
  427. createWholePermissionFolder(Environment.getExternalStorageDirectory() + PUB_TEMP_DIRECTORY);
  428. File bitmapFile = new File(Environment.getExternalStorageDirectory() + PUB_TEMP_DIRECTORY, fileName);
  429. FileOutputStream bitmapWriter;
  430. String retPath = "";
  431. try {
  432. bitmapWriter = new FileOutputStream(bitmapFile);
  433. if (bitmap.compress(Bitmap.CompressFormat.JPEG, 75, bitmapWriter)) {
  434. Log.d("TAG", "Save picture successfully! file name = "
  435. + PUB_TEMP_DIRECTORY + fileName);
  436. bitmapWriter.flush();
  437. bitmapWriter.close();
  438. retPath = Environment.getExternalStorageDirectory() + PUB_TEMP_DIRECTORY + fileName;
  439. }
  440. } catch (FileNotFoundException e) {
  441. e.printStackTrace();
  442. } catch (IOException e) {
  443. e.printStackTrace();
  444. } catch (Exception e) {
  445. e.printStackTrace();
  446. }
  447. return retPath;
  448. }
  449. /**
  450. * Judge if the characters in the string are all number
  451. *
  452. * @param str
  453. * @return
  454. * @author mikewu
  455. */
  456. public static boolean isNumeric(String str) {
  457. Pattern pattern = Pattern.compile("[0-9]*");
  458. return pattern.matcher(str).matches();
  459. }
  460. public static int dip2px(Context context, int dipValue) {
  461. final float scale = context.getResources().getDisplayMetrics().density;
  462. return (int) (dipValue * scale + 0.5f);
  463. }
  464. public static int px2dip(Context context, float pxValue) {
  465. final float scale = context.getResources().getDisplayMetrics().density;
  466. return (int) (pxValue / scale + 0.5f);
  467. }
  468. /**
  469. * 比较versionName 是否比之前的大
  470. * @param local
  471. * @param romote
  472. * @return
  473. */
  474. public boolean compareVersion(String local, String romote){
  475. boolean isNewVersion = false;
  476. try {
  477. String loaclVersion[] = local.substring(1).split("\\.");
  478. String romoteVersion[] = romote.split("\\.");
  479. int length = loaclVersion.length < romoteVersion.length ? loaclVersion.length : romoteVersion.length;
  480. for (int i = 0; i < length; i++) {
  481. if (Integer.parseInt(loaclVersion[i]) < Integer.parseInt(romoteVersion[i])) {
  482. isNewVersion = true;
  483. break;
  484. }
  485. else if (Integer.parseInt(loaclVersion[i]) > Integer.parseInt(romoteVersion[i])) {
  486. break;
  487. }
  488. }
  489. } catch (Exception e) {
  490. e.printStackTrace();
  491. }
  492. return isNewVersion;
  493. }
  494. public static int getAppVersion(Context context) {
  495. int versionCode = 0;
  496. try {
  497. PackageManager pm = context.getPackageManager();
  498. PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
  499. versionCode = pi.versionCode;
  500. } catch (Exception e) {
  501. Log.e(TAG, "Exception", e);
  502. }
  503. return versionCode;
  504. }
  505. public static String getAppVersionName(Context context) {
  506. String versionName = "";
  507. try {
  508. PackageManager pm = context.getPackageManager();
  509. PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
  510. versionName = pi.versionName;
  511. if (versionName == null || versionName.length() <= 0) {
  512. return "";
  513. }
  514. } catch (Exception e) {
  515. Log.e(TAG, "Exception", e);
  516. }
  517. return versionName;
  518. }
  519. public static String replaceHtml(String html) {
  520. String regEx = "<.+?>";
  521. Pattern p = Pattern.compile(regEx);
  522. Matcher m = p.matcher(html);
  523. String s = m.replaceAll("");
  524. return s;
  525. }
  526. public static void freeBitmap(HashMap<String, Bitmap> cache) {
  527. if (cache.isEmpty()) {
  528. return;
  529. }
  530. for (Bitmap bitmap : cache.values()) {
  531. if (bitmap != null && !bitmap.isRecycled()) {
  532. bitmap.recycle();
  533. bitmap = null;
  534. }
  535. }
  536. cache.clear();
  537. System.gc();
  538. }
  539. public static String getRefreshTime(){
  540. String strDate = "";
  541. SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm:ss");
  542. Date curDate = new Date(System.currentTimeMillis());//获取当前时间
  543. strDate = formatter.format(curDate);
  544. return strDate;
  545. }
  546. public static String getChatTime(long time){
  547. String strDate = "";
  548. SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
  549. Date curDate = new Date(time);//获取当前时间
  550. strDate = formatter.format(curDate);
  551. String toDayTime = formartTime(System.currentTimeMillis()/1000, "yyyy");
  552. if(toDayTime!=null && strDate!=null && strDate.equals(toDayTime)){
  553. strDate = formartTime(time/1000, "MM-dd HH:mm");
  554. }else{
  555. strDate = formartTime(time/1000, "yyyy-MM-dd HH:mm");
  556. }
  557. return strDate;
  558. }
  559. public static String getFormatTime(String time){
  560. SimpleDateFormat formatter = new SimpleDateFormat("yyyy/M/d HH:mm:ss");
  561. Date d;
  562. String formattime = "";
  563. try {
  564. d = formatter.parse(time);
  565. SimpleDateFormat formatter2 = new SimpleDateFormat("MM-dd HH:mm:ss");
  566. formattime = formatter2.format(d);
  567. } catch (ParseException e) {
  568. e.printStackTrace();
  569. }
  570. return formattime;
  571. }
  572. public static boolean newFolder(String folderPath) {
  573. try {
  574. String filePath = folderPath;
  575. File myFilePath = new File(filePath);
  576. if (!myFilePath.exists()) {
  577. myFilePath.mkdirs();
  578. }
  579. return true;
  580. } catch (Exception e) {
  581. e.printStackTrace();
  582. return false;
  583. }
  584. }
  585. public static String generator(String key) {
  586. String cacheKey;
  587. try {
  588. final MessageDigest mDigest = MessageDigest.getInstance("MD5");
  589. mDigest.update(key.getBytes());
  590. cacheKey = bytesToHexString(mDigest.digest());
  591. } catch (NoSuchAlgorithmException e) {
  592. cacheKey = String.valueOf(key.hashCode());
  593. }
  594. return cacheKey;
  595. }
  596. private static String bytesToHexString(byte[] bytes) {
  597. // http://stackoverflow.com/questions/332079
  598. StringBuilder sb = new StringBuilder();
  599. for (int i = 0; i < bytes.length; i++) {
  600. String hex = Integer.toHexString(0xFF & bytes[i]);
  601. if (hex.length() == 1) {
  602. sb.append('0');
  603. }
  604. sb.append(hex);
  605. }
  606. return sb.toString();
  607. }
  608. public static boolean reNameFile(File file, String newName){
  609. return file.renameTo(new File(file.getParentFile(), newName));
  610. }
  611. public static boolean isPic(String filename) {
  612. String strPattern = "^.((jpg)|(png)|(jpeg))$";
  613. Pattern p = Pattern.compile(strPattern, Pattern.CASE_INSENSITIVE);
  614. Matcher m = p.matcher(filename);
  615. Log.d("m.matches()", String.valueOf(m.matches()));
  616. return m.matches();
  617. }
  618. /**
  619. * 获取图片名称
  620. * @param isSingle 0-不需要保存 1-保存单张 2-保存所有的url
  621. * @return
  622. */
  623. public static String getPhotoFileName(int isSingle) {
  624. Date date = new Date(System.currentTimeMillis());
  625. SimpleDateFormat dateFormat = new SimpleDateFormat(
  626. "'IMG'_yyyyMMdd_HHmmss");
  627. String urlName = dateFormat.format(date) + ".jpg";
  628. if(isSingle == 1){
  629. IMCommon.saveCamerUrl(BMapApiApp.getInstance(), urlName);
  630. }else if(isSingle == 2){
  631. String[] tempUrlString = IMCommon.getCamerArrayUrl(BMapApiApp.getInstance());
  632. String[] urlString;
  633. if(tempUrlString!=null && tempUrlString.length>0){
  634. //String[]
  635. urlString = new String[tempUrlString.length+1];
  636. System.arraycopy(tempUrlString, 0, urlString, 0, tempUrlString.length);
  637. urlString[urlString.length-1] = urlName;
  638. }else{
  639. urlString = new String[]{urlName};
  640. }
  641. if(urlString != null && urlString.length>0){
  642. IMCommon.saveCamerArrayUrl(BMapApiApp.getInstance(), urlString);
  643. }
  644. }
  645. return urlName;
  646. }
  647. public static Date getTimeDate(long time){
  648. //String strDate = "";
  649. //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  650. Date curDate = new Date(time);//获取当前时间
  651. return curDate;
  652. }
  653. /**
  654. * 保留一位小数点
  655. * @param f
  656. * @return
  657. * 作者:fighter <br />
  658. * 创建时间:2013-6-13<br />
  659. * 修改时间:<br />
  660. */
  661. public static String floatMac1(float f){
  662. DecimalFormat decimalFormat = new DecimalFormat("####.#");
  663. try {
  664. return decimalFormat.format(f);
  665. } catch (Exception e) {
  666. return f + "";
  667. }
  668. }
  669. public static String floatMac(String floatStr){
  670. DecimalFormat decimalFormat = new DecimalFormat("####.#");
  671. try {
  672. float f = Float.parseFloat(floatStr);
  673. return decimalFormat.format(f);
  674. } catch (Exception e) {
  675. return floatStr;
  676. }
  677. }
  678. /**
  679. * 获取几天以前的秒数
  680. * @param day
  681. * @return
  682. * 作者:fighter <br />
  683. * 创建时间:2013-6-7<br />
  684. * 修改时间:<br />
  685. */
  686. public static String dayBefore(float day){
  687. // Calendar calendar = Calendar.getInstance();
  688. // calendar.add(Calendar.DAY_OF_WEEK, 0 - day);
  689. // return (calendar.getTimeInMillis() / 1000) + "";
  690. long time = (long) (60 * 60 * 24 * day);
  691. return time + "";
  692. }
  693. public static Calendar getCalendar(String brithDate) {
  694. Calendar calendar = Calendar.getInstance();
  695. if (TextUtils.isEmpty(brithDate)) {
  696. return calendar;
  697. }
  698. String birth = brithDate;
  699. try {
  700. Date date = new Date(birth); // 出生日期d1
  701. calendar.setTime(date);
  702. } catch (IllegalArgumentException e) {
  703. e.printStackTrace();
  704. }
  705. return calendar;
  706. }
  707. public static String getTime(String currTime){
  708. long time = 0;
  709. try {
  710. time = Long.parseLong(currTime);
  711. } catch (Exception e) {
  712. time = System.currentTimeMillis();
  713. }
  714. return getTime(time);
  715. }
  716. public static String getTime(long currTime){
  717. Calendar calendar = Calendar.getInstance(Locale.CHINA);
  718. calendar.setTimeInMillis(currTime);
  719. String str = timeDifference(calendar);
  720. Date date = calendar.getTime();
  721. SimpleDateFormat format = null;
  722. if(str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.minutes))
  723. || str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.hour))){
  724. format =new SimpleDateFormat("HH:mm"); //new SimpleDateFormat("HH:mm:ss");
  725. }else if(str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.day))
  726. || str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.long_ago))){
  727. format = new SimpleDateFormat("yyyy.MM.dd");
  728. }
  729. return format.format(date);
  730. }
  731. public static boolean getOnline(String online){
  732. if(TextUtils.isEmpty(online)){
  733. return false;
  734. }
  735. try {
  736. long mtime = Long.parseLong(online) * 1000;
  737. Calendar calendar = Calendar.getInstance(Locale.CHINA);
  738. long currTime = calendar.getTimeInMillis() - mtime;
  739. if(currTime > PhpServiceThread.TIME){
  740. return false;
  741. }else{
  742. return true;
  743. }
  744. } catch (Exception e) {
  745. return false;
  746. }
  747. }
  748. /**
  749. * 出生日期转换为年龄
  750. * @param brithDate
  751. * @return
  752. * 作者:fighter <br />
  753. * 创建时间:2013-3-26<br />
  754. * 修改时间:<br />
  755. */
  756. public static int dateToAge(String brithDate){
  757. if(TextUtils.isEmpty(brithDate)){
  758. return 0;
  759. }
  760. int age = 0;
  761. try {
  762. Calendar cal = Calendar.getInstance();
  763. String birth = brithDate;
  764. String now = (cal.get(Calendar.YEAR) + "/"
  765. + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DATE));
  766. Date d1 = new Date(birth); // 出生日期d1
  767. Date d2 = new Date(now); // 当前日期d2
  768. long i = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24);
  769. int g = (int) i;
  770. age = g / 365;
  771. } catch (IllegalArgumentException e) {
  772. }
  773. return age;
  774. }
  775. public static Map<String, String> objectToMap(Object strVo) {
  776. return (Map<String, String>) JSON.parse(JSON.toJSONString(strVo));
  777. }
  778. public static String timeDifference(long time){
  779. Calendar calendar = Calendar.getInstance();
  780. calendar.setTimeInMillis(time);
  781. return timeDifference(calendar);
  782. }
  783. public static String timeOnlie(String online){
  784. try {
  785. long mtime = Long.parseLong(online) * 1000;
  786. Calendar calendar = Calendar.getInstance(Locale.CHINA);
  787. calendar.setTimeInMillis(mtime);
  788. String str = timeOnlie(calendar);
  789. Date date = calendar.getTime();
  790. SimpleDateFormat format = null;
  791. if(str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.minutes))
  792. || str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.hour))){
  793. format = new SimpleDateFormat("HH:mm:ss");
  794. }else if(str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.day))
  795. || str.endsWith(BMapApiApp.getInstance().getResources().getString(R.string.long_ago))){
  796. format = new SimpleDateFormat("MM-dd HH:mm:ss");
  797. }
  798. return format.format(date);
  799. } catch (Exception e) {
  800. return "";
  801. }
  802. }
  803. public static String timeOnlie(Calendar calendar){
  804. long cTime = calendar.getTimeInMillis();
  805. calendar.setTimeInMillis(cTime + PhpServiceThread.TIME);
  806. String info = "";
  807. Calendar currCalendar = Calendar.getInstance();
  808. long second = (currCalendar.getTimeInMillis() - calendar.getTimeInMillis()) / 1000;
  809. int index = 0;
  810. if(second < (60 * 60)){
  811. index = 60;
  812. } else if(second < (24 * 60 * 60)){
  813. index = 60 * 60;
  814. }else if(second < (30 * (24 * 60 * 60))){
  815. index = (24 * 60 * 60);
  816. }
  817. info = secondOnlie(second, index, 1);
  818. return info;
  819. }
  820. private static String secondOnlie(long second, int index, int num){
  821. String info = "";
  822. if(index == 60){
  823. info = BMapApiApp.getInstance().getResources().getString(R.string.minutes);
  824. } else if(index == (60 * 60)){
  825. info = BMapApiApp.getInstance().getResources().getString(R.string.hour);;
  826. } else if(index == (24 * 60 * 60)){
  827. info = BMapApiApp.getInstance().getResources().getString(R.string.day);
  828. } else {
  829. return BMapApiApp.getInstance().getResources().getString(R.string.long_ago);
  830. }
  831. if(second < index * num){
  832. return num + info;
  833. }else{
  834. return secondOnlie(second, index, ++num);
  835. }
  836. }
  837. public static String timeDifference(String currTime){
  838. Calendar calendar = Calendar.getInstance();
  839. try {
  840. long curr = Long.parseLong(currTime);
  841. calendar.setTimeInMillis(curr);
  842. } catch (Exception e) {
  843. }
  844. return timeDifference(calendar);
  845. }
  846. /**
  847. * 判断时间与当前时间的差距, 给予字符提示.
  848. * @param calendar
  849. * @return
  850. * 作者:fighter <br />
  851. * 创建时间:2013-4-9<br />
  852. * 修改时间:<br />
  853. */
  854. public static String timeDifference(Calendar calendar){
  855. String info = "";
  856. Calendar currCalendar = Calendar.getInstance();
  857. long second = (currCalendar.getTimeInMillis() - calendar.getTimeInMillis()) / 1000;
  858. int index = 0;
  859. if(second < (60 * 60)){
  860. index = 60;
  861. } else if(second < (24 * 60 * 60)){
  862. index = 60 * 60;
  863. }else if(second < (30 * (24 * 60 * 60))){
  864. index = (24 * 60 * 60);
  865. }
  866. info = second(second, index, 1);
  867. return info;
  868. }
  869. private static String second(long second, int index, int num){
  870. String info = "";
  871. if(index == 60){
  872. info = BMapApiApp.getInstance().getResources().getString(R.string.minutes);
  873. } else if(index == (60 * 60)){
  874. info = BMapApiApp.getInstance().getResources().getString(R.string.hour);
  875. } else if(index == (24 * 60 * 60)){
  876. info = BMapApiApp.getInstance().getResources().getString(R.string.day);
  877. } else {
  878. return BMapApiApp.getInstance().getResources().getString(R.string.long_ago);
  879. }
  880. if(second < index * num){
  881. return num + info;
  882. }else{
  883. return second(second, index, ++num);
  884. }
  885. }
  886. /**
  887. * 程序是否在前台运行
  888. *
  889. * @return
  890. */
  891. public static boolean isAppOnForeground(Context context) {
  892. // Returns a list of application processes that are running on the
  893. // device
  894. ActivityManager activityManager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
  895. String packageName = context.getApplicationContext().getPackageName();
  896. List<RunningAppProcessInfo> appProcesses = activityManager
  897. .getRunningAppProcesses();
  898. if (appProcesses == null)
  899. return false;
  900. for (RunningAppProcessInfo appProcess : appProcesses) {
  901. // The name of the process that this object is associated with.
  902. if (appProcess.processName.equals(packageName)
  903. && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
  904. return true;
  905. }
  906. }
  907. return false;
  908. }
  909. public static String getFilePathByContentResolver(Context context, Uri uri) {
  910. if (null == uri) {
  911. return null;
  912. }
  913. Cursor c = context.getContentResolver().query(uri, null, null, null, null);
  914. String filePath = null;
  915. if (null == c) {
  916. throw new IllegalArgumentException(
  917. "Query on " + uri + " returns null result.");
  918. }
  919. try {
  920. if ((c.getCount() != 1) || !c.moveToFirst()) {
  921. } else {
  922. filePath = c.getString(c.getColumnIndexOrThrow(MediaColumns.DATA));
  923. }
  924. } finally {
  925. c.close();
  926. }
  927. return filePath;
  928. }
  929. public static long getTimeStamp(String brithDate) {
  930. long time = 0;
  931. try {
  932. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  933. Date date = formatter.parse(brithDate);
  934. time = date.getTime();
  935. } catch (IllegalArgumentException e) {
  936. e.printStackTrace();
  937. } catch (ParseException e) {
  938. e.printStackTrace();
  939. }
  940. return time;
  941. }
  942. public static boolean isEmail(String strEmail){
  943. String strPattern = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,4}$";
  944. Pattern p = Pattern.compile(strPattern);
  945. Matcher m = p.matcher(strEmail);
  946. Log.d("m.matches()", String.valueOf(m.matches()));
  947. return m.matches();
  948. }
  949. public static String showdate(int year, int month, int day) {
  950. Calendar calendar = Calendar.getInstance();
  951. int cYear = calendar.get(Calendar.YEAR);
  952. int cMonth = calendar.get(Calendar.MONTH);
  953. int cDay = calendar.get(Calendar.DAY_OF_MONTH);
  954. if(year> cYear){
  955. return "";
  956. }
  957. if(year == cYear && month > cMonth){
  958. return "";
  959. }
  960. if(year == cYear && month == cMonth && day > cDay){
  961. return "";
  962. }
  963. int trueMonth = (month + 1);
  964. String sMonth = trueMonth > 9 ? (trueMonth+"") : ("0" + trueMonth);
  965. String sDay = day > 9 ? (day + "") : ("0" + day);
  966. String date = year + "-" + sMonth + "-" + sDay;
  967. return date;
  968. }
  969. //格式化时间戳
  970. /**
  971. * "yyyy-MM-dd HH:mm:ss"
  972. * @param time
  973. * @param formateType
  974. * @return
  975. */
  976. public static String formartTime(long time,String formateType){
  977. SimpleDateFormat sdf = new SimpleDateFormat(formateType);
  978. String formatTime = sdf.format(new Date(time*1000));
  979. return formatTime;
  980. }
  981. public static int getSourceIdByName(String imageName){
  982. int sourceID = 0;
  983. try {
  984. Field field = Class.forName("com.wqdsoft.im.R$drawable").getField(imageName);
  985. sourceID = field.getInt(field);
  986. } catch (Exception e) {
  987. }
  988. return sourceID;
  989. }
  990. /**
  991. * 生成二维码
  992. * @param str 组id
  993. * @param handler
  994. * @param what 消息值
  995. * @param width 二维码宽
  996. * @param height 二维码高
  997. * @return
  998. */
  999. public static Bitmap create2DCode(String str,int oldWidth,int oldHeight) {
  1000. Bitmap bitmap=null;
  1001. try {
  1002. String groupEncode = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);
  1003. String codeStr = IMInfo.CODE_URL+"/"+groupEncode;
  1004. //IMInfo.SERVER_PREFIX+"/g/"+Base64.encodeToString(mRoomId.getBytes(), Base64.DEFAULT)
  1005. //生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
  1006. BitMatrix matrix = new MultiFormatWriter().encode(codeStr,BarcodeFormat.QR_CODE, oldWidth, oldHeight);
  1007. int width = matrix.getWidth();
  1008. int height = matrix.getHeight();
  1009. //二维矩阵转为一维像素数组,也就是一直横着排了
  1010. int[] pixels = new int[width * height];
  1011. for (int y = 0; y < height; y++) {
  1012. for (int x = 0; x < width; x++) {
  1013. if(matrix.get(x, y)){
  1014. pixels[y * width + x] = 0xff000000;
  1015. }
  1016. }
  1017. }
  1018. bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  1019. //通过像素数组生成bitmap,具体参考api
  1020. bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
  1021. return bitmap;
  1022. } catch (WriterException e) {
  1023. e.printStackTrace();
  1024. return null;
  1025. }catch (Exception e) {
  1026. e.printStackTrace();
  1027. return null;
  1028. }
  1029. }
  1030. /**
  1031. * 获取 昨天、今天、明天的日期
  1032. * @param fromat "yyyy-MM-dd"
  1033. */
  1034. @SuppressWarnings("static-access")
  1035. public static String dateTime(String fromat){
  1036. Date date=new Date();//取时间
  1037. Calendar calendar = new GregorianCalendar();
  1038. calendar.setTime(date);
  1039. calendar.add(calendar.DATE,-1);//把日期往后增加一天.整数往后推,负数往前移动
  1040. date=calendar.getTime(); //这个时间就是日期往后推一天的结果
  1041. SimpleDateFormat formatter = new SimpleDateFormat(fromat);
  1042. String dateString = formatter.format(date);
  1043. Log.e("dateTime",dateString);
  1044. return dateString;
  1045. }
  1046. /***
  1047. * 判断是否超过24小时
  1048. * @param date1 开始时间
  1049. * @param date2 结束时间
  1050. * @return
  1051. * @throws Exception
  1052. */
  1053. public static boolean jisuan(String date1, String date2) throws Exception {
  1054. java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1055. java.util.Date start = sdf.parse(date1);
  1056. java.util.Date end = sdf.parse(date2);
  1057. long cha = end.getTime() - start.getTime();
  1058. double result = cha * 1.0 / (1000 * 60 * 60);
  1059. if(result<=24){
  1060. //System.out.println("可用");
  1061. return true;
  1062. }else{
  1063. //System.out.println("已过期");
  1064. return false;
  1065. }
  1066. }
  1067. /**
  1068. * 获取程序外部的缓存目录
  1069. * @param context
  1070. * @return
  1071. */
  1072. public static File getExternalCacheDir(Context context) {
  1073. final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
  1074. return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
  1075. }
  1076. public static String getSecondTime(long online){
  1077. try {
  1078. String timeStr = "";
  1079. Calendar calendar = Calendar.getInstance(Locale.CHINA);
  1080. calendar.setTimeInMillis(online);
  1081. String str = timeOnlie(calendar);
  1082. if(str.endsWith(BMapApiApp.getInstance().getString(R.string.second)) || str.endsWith(BMapApiApp.getInstance().getString(R.string.minutes))
  1083. || str.endsWith(BMapApiApp.getInstance().getString(R.string.hour))){
  1084. timeStr = str + BMapApiApp.getInstance().getString(R.string.before);
  1085. }else if(str.endsWith(BMapApiApp.getInstance().getString(R.string.day)) || str.endsWith(BMapApiApp.getInstance().getString(R.string.long_ago))){
  1086. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  1087. Date date = calendar.getTime();
  1088. timeStr = format.format(date);
  1089. }
  1090. return timeStr;
  1091. } catch (Exception e) {
  1092. return "";
  1093. }
  1094. }
  1095. public static String showTimedate(int year, int month, int day, int hour, int minute) {
  1096. Calendar calendar = Calendar.getInstance();
  1097. int cYear = calendar.get(Calendar.YEAR);
  1098. int cMonth = calendar.get(Calendar.MONTH);
  1099. int cDay = calendar.get(Calendar.DAY_OF_MONTH);
  1100. int cHour = calendar.get(Calendar.HOUR_OF_DAY);
  1101. int cMinute = calendar.get(Calendar.MINUTE);
  1102. if (year < cYear) {
  1103. return "";
  1104. }
  1105. if (year == cYear && month < cMonth) {
  1106. return "";
  1107. }
  1108. if (year == cYear && month == cMonth && day < cDay) {
  1109. return "";
  1110. }
  1111. if (year == cYear && month == cMonth && day == cDay && hour < cHour) {
  1112. return "";
  1113. }
  1114. if (year == cYear && month == cMonth && day == cDay && hour == cHour
  1115. && minute < cMinute) {
  1116. return "";
  1117. }
  1118. int trueMonth = (month + 1);
  1119. String sMonth = trueMonth > 9 ? (trueMonth + "") : ("0" + trueMonth);
  1120. String sDay = day > 9 ? (day + "") : ("0" + day);
  1121. String sHour = hour > 9 ? (hour + "") : ("0" + hour);
  1122. String sMinute = minute > 9 ? (minute + "") : ("0" + minute);
  1123. String date = year + "-" + sMonth + "-" + sDay + " " + sHour + ":" + sMinute;
  1124. return date;
  1125. }
  1126. /**
  1127. *
  1128. * @param context
  1129. * @param string assests 中的文件
  1130. * @return
  1131. */
  1132. public static String getAssestsFile(String string) {
  1133. try {
  1134. //Return an AssetManager instance for your application's package
  1135. InputStream is = BMapApiApp.getInstance().getResources().getAssets().open(string);
  1136. int size = is.available();
  1137. // Read the entire asset into a local byte buffer.
  1138. byte[] buffer = new byte[size];
  1139. is.read(buffer);
  1140. is.close();
  1141. // Convert the buffer into a string.
  1142. String text = new String(buffer, "UTF-8");
  1143. return text;
  1144. } catch (IOException e) {
  1145. // Should never happen!
  1146. throw new RuntimeException(e);
  1147. }
  1148. }
  1149. /**
  1150. * 生成缩略图的尺寸
  1151. * @param width 原始图片宽度
  1152. * @param height 原始图片高度
  1153. * @return
  1154. */
  1155. public static int[] getScalcSize(int width,int height){
  1156. int maxL = 220;
  1157. float bigger = height>width?height:width;
  1158. float coefficient = (float) 1.0;
  1159. int maxPix = maxL;
  1160. if(bigger > maxPix){
  1161. coefficient = maxPix/bigger;
  1162. }
  1163. int[] i = new int[2];
  1164. i[0] = (int) (width * coefficient);
  1165. i[1] = (int) (height * coefficient);
  1166. return i;
  1167. }
  1168. }