這篇文章給大家介紹Android開(kāi)發(fā)中常用到的工具類(lèi)有哪些,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括阿城網(wǎng)站建設(shè)、阿城網(wǎng)站制作、阿城網(wǎng)頁(yè)制作以及阿城網(wǎng)絡(luò)營(yíng)銷(xiāo)策劃等。多年來(lái),我們專(zhuān)注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,阿城網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶(hù)以成都為中心已經(jīng)輻射到阿城省份的部分城市,未來(lái)相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶(hù)的支持與信任!
作為一個(gè)程序員界的新晉司機(jī),也是時(shí)候整理一些東西了,兩三年的路走來(lái),代碼也是邊寫(xiě)邊忘、邊走邊丟,很多問(wèn)題忙著忙著就忘了,決定寫(xiě)點(diǎn)隨筆供自己閑余時(shí)間回望,有需要的讀者也可以隨意瞄幾眼,哪里有錯(cuò)有問(wèn)題可以提出來(lái),雖然我不見(jiàn)得會(huì)改,O(∩_∩)O哈哈~
日常開(kāi)發(fā)中很多東西都是寫(xiě)過(guò)無(wú)數(shù)遍的,我本人沒(méi)有每次都去重新寫(xiě)的習(xí)慣(不知道有沒(méi)有小伙伴會(huì)如此耿直??)那么整理好自己的工具類(lèi)還是有必要的。這里就記錄幾個(gè)目前為止我使用較多的。
常用工具類(lèi)
/** * 根據(jù)手機(jī)的分辨率從 dp 的單位 轉(zhuǎn)成為 px(像素) */ public static int dip2px(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** * 根據(jù)手機(jī)的分辨率從 px(像素) 的單位 轉(zhuǎn)成為 dp */ public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** * Md5 32位 or 16位 加密 * * @param plainText * @return 32位加密 */ public static String Md5(String plainText) { StringBuffer buf = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return buf.toString(); } /** * 手機(jī)號(hào)正則判斷 * @param str * @return * @throws PatternSyntaxException */ public static boolean isPhoneNumber(String str) throws PatternSyntaxException { if (str != null) { String pattern = "(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(str); return m.matches(); } else { return false; } } /** * 檢測(cè)當(dāng)前網(wǎng)絡(luò)的類(lèi)型 是否是wifi * * @param context * @return */ public static int checkedNetWorkType(Context context) { if (!checkedNetWork(context)) { return 0;//無(wú)網(wǎng)絡(luò) } ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) { return 1;//wifi } else { return 2;//非wifi } } /** * 檢查是否連接網(wǎng)絡(luò) * * @param context * @return */ public static boolean checkedNetWork(Context context) { // 獲得連接設(shè)備管理器 ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; /** * 獲取網(wǎng)絡(luò)連接對(duì)象 */ NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isAvailable()) { return false; } return true; } /** * 檢測(cè)GPS是否打開(kāi) * * @return */ public static boolean checkGPSIsOpen(Context context) { boolean isOpen; LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ isOpen=true; }else{ isOpen = false; } return isOpen; } /** * 跳轉(zhuǎn)GPS設(shè)置 */ public static void openGPSSettings(final Context context) { if (checkGPSIsOpen(context)) { // initLocation(); //自己寫(xiě)的定位方法 } else { // //沒(méi)有打開(kāi)則彈出對(duì)話(huà)框 AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom); builder.setTitle("溫馨提示"); builder.setMessage("當(dāng)前應(yīng)用需要打開(kāi)定位功能。請(qǐng)點(diǎn)擊\"設(shè)置\"-\"定位服務(wù)\"打開(kāi)定位功能。"); //設(shè)置對(duì)話(huà)框是可取消的 builder.setCancelable(false); builder.setPositiveButton("設(shè)置", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); //跳轉(zhuǎn)GPS設(shè)置界面 Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); context.startActivity(intent); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); ActivityManager.getInstance().exit(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } } /** * 字符串進(jìn)行Base64編碼 * @param str */ public static String StringToBase64(String str){ String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT); return encodedString; } /** * 字符串進(jìn)行Base64解碼 * @param encodedString * @return */ public static String Base64ToString(String encodedString){ String decodedString =new String(Base64.decode(encodedString,Base64.DEFAULT)); return decodedString; }
這里還有一個(gè)根據(jù)經(jīng)緯度計(jì)算兩點(diǎn)間真實(shí)距離的,一般都直接使用所集成第三方地圖SDK中包含的方法,這里還是給出代碼
/** * 補(bǔ)充:計(jì)算兩點(diǎn)之間真實(shí)距離 * * @return 米 */ public static double getDistance(double longitude1, double latitude1, double longitude2, double latitude2) { // 維度 double lat1 = (Math.PI / 180) * latitude1; double lat2 = (Math.PI / 180) * latitude2; // 經(jīng)度 double lon1 = (Math.PI / 180) * longitude1; double lon2 = (Math.PI / 180) * longitude2; // 地球半徑 double R = 6371; // 兩點(diǎn)間距離 km,如果想要米的話(huà),結(jié)果*1000就可以了 double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R; return d * 1000; }
常用文件類(lèi)
文件類(lèi)的代碼較多,這里就只給出讀寫(xiě)文件的
/** * 判斷SD卡是否可用 * @return SD卡可用返回true */ public static boolean hasSdcard() { String status = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(status); } /** * 讀取文件的內(nèi)容 * <br> * 默認(rèn)utf-8編碼 * @param filePath 文件路徑 * @return 字符串 * @throws IOException */ public static String readFile(String filePath) throws IOException { return readFile(filePath, "utf-8"); } /** * 讀取文件的內(nèi)容 * @param filePath 文件目錄 * @param charsetName 字符編碼 * @return String字符串 */ public static String readFile(String filePath, String charsetName) throws IOException { if (TextUtils.isEmpty(filePath)) return null; if (TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = new File(filePath); StringBuilder fileContent = new StringBuilder(""); if (file == null || !file.isFile()) return null; BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream( file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { if (!fileContent.toString().equals("")) { fileContent.append("\r\n"); } fileContent.append(line); } return fileContent.toString(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 讀取文本文件到List字符串集合中(默認(rèn)utf-8編碼) * @param filePath 文件目錄 * @return 文件不存在返回null,否則返回字符串集合 * @throws IOException */ public static List<String> readFileToList(String filePath) throws IOException { return readFileToList(filePath, "utf-8"); } /** * 讀取文本文件到List字符串集合中 * @param filePath 文件目錄 * @param charsetName 字符編碼 * @return 文件不存在返回null,否則返回字符串集合 */ public static List<String> readFileToList(String filePath, String charsetName) throws IOException { if (TextUtils.isEmpty(filePath)) return null; if (TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = new File(filePath); List<String> fileContent = new ArrayList<String>(); if (file == null || !file.isFile()) { return null; } BufferedReader reader = null; try { InputStreamReader is = new InputStreamReader(new FileInputStream( file), charsetName); reader = new BufferedReader(is); String line = null; while ((line = reader.readLine()) != null) { fileContent.add(line); } return fileContent; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 向文件中寫(xiě)入數(shù)據(jù) * @param filePath 文件目錄 * @param content 要寫(xiě)入的內(nèi)容 * @param append 如果為 true,則將數(shù)據(jù)寫(xiě)入文件末尾處,而不是寫(xiě)入文件開(kāi)始處 * @return 寫(xiě)入成功返回true, 寫(xiě)入失敗返回false * @throws IOException */ public static boolean writeFile(String filePath, String content, boolean append) throws IOException { if (TextUtils.isEmpty(filePath)) return false; if (TextUtils.isEmpty(content)) return false; FileWriter fileWriter = null; try { createFile(filePath); fileWriter = new FileWriter(filePath, append); fileWriter.write(content); fileWriter.flush(); return true; } finally { if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 向文件中寫(xiě)入數(shù)據(jù)<br> * 默認(rèn)在文件開(kāi)始處重新寫(xiě)入數(shù)據(jù) * @param filePath 文件目錄 * @param stream 字節(jié)輸入流 * @return 寫(xiě)入成功返回true,否則返回false * @throws IOException */ public static boolean writeFile(String filePath, InputStream stream) throws IOException { return writeFile(filePath, stream, false); } /** * 向文件中寫(xiě)入數(shù)據(jù) * @param filePath 文件目錄 * @param stream 字節(jié)輸入流 * @param append 如果為 true,則將數(shù)據(jù)寫(xiě)入文件末尾處; * 為false時(shí),清空原來(lái)的數(shù)據(jù),從頭開(kāi)始寫(xiě) * @return 寫(xiě)入成功返回true,否則返回false * @throws IOException */ public static boolean writeFile(String filePath, InputStream stream, boolean append) throws IOException { if (TextUtils.isEmpty(filePath)) throw new NullPointerException("filePath is Empty"); if (stream == null) throw new NullPointerException("InputStream is null"); return writeFile(new File(filePath), stream, append); } /** * 向文件中寫(xiě)入數(shù)據(jù) * 默認(rèn)在文件開(kāi)始處重新寫(xiě)入數(shù)據(jù) * @param file 指定文件 * @param stream 字節(jié)輸入流 * @return 寫(xiě)入成功返回true,否則返回false * @throws IOException */ public static boolean writeFile(File file, InputStream stream) throws IOException { return writeFile(file, stream, false); } /** * 向文件中寫(xiě)入數(shù)據(jù) * @param file 指定文件 * @param stream 字節(jié)輸入流 * @param append 為true時(shí),在文件開(kāi)始處重新寫(xiě)入數(shù)據(jù); * 為false時(shí),清空原來(lái)的數(shù)據(jù),從頭開(kāi)始寫(xiě) * @return 寫(xiě)入成功返回true,否則返回false * @throws IOException */ public static boolean writeFile(File file, InputStream stream, boolean append) throws IOException { if (file == null) throw new NullPointerException("file = null"); OutputStream out = null; try { createFile(file.getAbsolutePath()); out = new FileOutputStream(file, append); byte data[] = new byte[1024]; int length = -1; while ((length = stream.read(data)) != -1) { out.write(data, 0, length); } out.flush(); return true; } finally { if (out != null) { try { out.close(); stream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
日期工具類(lèi)
/** * 將long時(shí)間轉(zhuǎn)成yyyy-MM-dd HH:mm:ss字符串<br> * @param timeInMillis 時(shí)間long值 * @return yyyy-MM-dd HH:mm:ss */ public static String getDateTimeFromMillis(long timeInMillis) { return getDateTimeFormat(new Date(timeInMillis)); } /** * 將date轉(zhuǎn)成yyyy-MM-dd HH:mm:ss字符串 * <br> * @param date Date對(duì)象 * @return yyyy-MM-dd HH:mm:ss */ public static String getDateTimeFormat(Date date) { return dateSimpleFormat(date, defaultDateTimeFormat.get()); } /** * 將年月日的int轉(zhuǎn)成yyyy-MM-dd的字符串 * @param year 年 * @param month 月 1-12 * @param day 日 * 注:月表示Calendar的月,比實(shí)際小1 * 對(duì)輸入項(xiàng)未做判斷 */ public static String getDateFormat(int year, int month, int day) { return getDateFormat(getDate(year, month, day)); } /** * 獲得HH:mm:ss的時(shí)間 * @param date * @return */ public static String getTimeFormat(Date date) { return dateSimpleFormat(date, defaultTimeFormat.get()); } /** * 格式化日期顯示格式 * @param sdate 原始日期格式 "yyyy-MM-dd" * @param format 格式化后日期格式 * @return 格式化后的日期顯示 */ public static String dateFormat(String sdate, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); java.sql.Date date = java.sql.Date.valueOf(sdate); return dateSimpleFormat(date, formatter); } /** * 格式化日期顯示格式 * @param date Date對(duì)象 * @param format 格式化后日期格式 * @return 格式化后的日期顯示 */ public static String dateFormat(Date date, String format) { SimpleDateFormat formatter = new SimpleDateFormat(format); return dateSimpleFormat(date, formatter); } /** * 將date轉(zhuǎn)成字符串 * @param date Date * @param format SimpleDateFormat * <br> * 注: SimpleDateFormat為空時(shí),采用默認(rèn)的yyyy-MM-dd HH:mm:ss格式 * @return yyyy-MM-dd HH:mm:ss */ public static String dateSimpleFormat(Date date, SimpleDateFormat format) { if (format == null) format = defaultDateTimeFormat.get(); return (date == null ? "" : format.format(date)); } /** * 將"yyyy-MM-dd HH:mm:ss" 格式的字符串轉(zhuǎn)成Date * @param strDate 時(shí)間字符串 * @return Date */ public static Date getDateByDateTimeFormat(String strDate) { return getDateByFormat(strDate, defaultDateTimeFormat.get()); } /** * 將"yyyy-MM-dd" 格式的字符串轉(zhuǎn)成Date * @param strDate * @return Date */ public static Date getDateByDateFormat(String strDate) { return getDateByFormat(strDate, defaultDateFormat.get()); } /** * 將指定格式的時(shí)間字符串轉(zhuǎn)成Date對(duì)象 * @param strDate 時(shí)間字符串 * @param format 格式化字符串 * @return Date */ public static Date getDateByFormat(String strDate, String format) { return getDateByFormat(strDate, new SimpleDateFormat(format)); } /** * 將String字符串按照一定格式轉(zhuǎn)成Date<br> * 注: SimpleDateFormat為空時(shí),采用默認(rèn)的yyyy-MM-dd HH:mm:ss格式 * @param strDate 時(shí)間字符串 * @param format SimpleDateFormat對(duì)象 * @exception ParseException 日期格式轉(zhuǎn)換出錯(cuò) */ private static Date getDateByFormat(String strDate, SimpleDateFormat format) { if (format == null) format = defaultDateTimeFormat.get(); try { return format.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 將年月日的int轉(zhuǎn)成date * @param year 年 * @param month 月 1-12 * @param day 日 * 注:月表示Calendar的月,比實(shí)際小1 */ public static Date getDate(int year, int month, int day) { Calendar mCalendar = Calendar.getInstance(); mCalendar.set(year, month - 1, day); return mCalendar.getTime(); } /** * 求兩個(gè)日期相差天數(shù) * * @param strat 起始日期,格式y(tǒng)yyy-MM-dd * @param end 終止日期,格式y(tǒng)yyy-MM-dd * @return 兩個(gè)日期相差天數(shù) */ public static long getIntervalDays(String strat, String end) { return ((java.sql.Date.valueOf(end)).getTime() - (java.sql.Date .valueOf(strat)).getTime()) / (3600 * 24 * 1000); } /** * 獲得當(dāng)前年份 * @return year(int) */ public static int getCurrentYear() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.YEAR); } /** * 獲得當(dāng)前月份 * @return month(int) 1-12 */ public static int getCurrentMonth() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.MONTH) + 1; } /** * 獲得當(dāng)月幾號(hào) * @return day(int) */ public static int getDayOfMonth() { Calendar mCalendar = Calendar.getInstance(); return mCalendar.get(Calendar.DAY_OF_MONTH); } /** * 獲得今天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getToday() { Calendar mCalendar = Calendar.getInstance(); return getDateFormat(mCalendar.getTime()); } /** * 獲得昨天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getYesterday() { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, -1); return getDateFormat(mCalendar.getTime()); } /** * 獲得前天的日期(格式:yyyy-MM-dd) * @return yyyy-MM-dd */ public static String getBeforeYesterday() { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, -2); return getDateFormat(mCalendar.getTime()); } /** * 獲得幾天之前或者幾天之后的日期 * @param diff 差值:正的往后推,負(fù)的往前推 * @return */ public static String getOtherDay(int diff) { Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, diff); return getDateFormat(mCalendar.getTime()); } /** * 取得給定日期加上一定天數(shù)后的日期對(duì)象. * * @param //date 給定的日期對(duì)象 * @param amount 需要添加的天數(shù),如果是向前的天數(shù),使用負(fù)數(shù)就可以. * @return Date 加上一定天數(shù)以后的Date對(duì)象. */ public static String getCalcDateFormat(String sDate, int amount) { Date date = getCalcDate(getDateByDateFormat(sDate), amount); return getDateFormat(date); } /** * 取得給定日期加上一定天數(shù)后的日期對(duì)象. * * @param date 給定的日期對(duì)象 * @param amount 需要添加的天數(shù),如果是向前的天數(shù),使用負(fù)數(shù)就可以. * @return Date 加上一定天數(shù)以后的Date對(duì)象. */ public static Date getCalcDate(Date date, int amount) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, amount); return cal.getTime(); }
關(guān)于Android開(kāi)發(fā)中常用到的工具類(lèi)有哪些就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
網(wǎng)頁(yè)名稱(chēng):Android開(kāi)發(fā)中常用到的工具類(lèi)有哪些
本文URL:http://chinadenli.net/article14/giihge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、網(wǎng)站內(nèi)鏈、網(wǎng)站設(shè)計(jì)、網(wǎng)站收錄、網(wǎng)頁(yè)設(shè)計(jì)公司、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)