Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the tool classes commonly used in Android development

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces what tools are commonly used in Android development, the content is very detailed, interested friends can refer to, hope to be helpful to you.

As a new driver in the field of programmers, it's time to sort out some things. After two or three years of walking, the code is also written and forgotten while walking. Many questions are forgotten when I am busy. I decided to write some essays for my spare time to look back. Readers in need can also glance at them at will, although I may not be able to change them. O (∩ _ ∩) O ~

Many things in daily development have been written countless times, and I am not in the habit of rewriting every time (I wonder if any of my friends will be so honest? Then it is necessary to organize your own tool class. Here are a few of the ones I have used more so far.

Common tool class

/ * convert from dp units to px (pixels) * / public static int dip2px (Context context, float dpValue) {final float scale = context.getResources () .getDisplayMetrics () .density; return (int) (dpValue * scale + 0.5f) according to the resolution of the phone. } / * change from px (pixel) unit to dp * / public static int px2dip (Context context, float pxValue) {final float scale = context.getResources (). GetDisplayMetrics (). Density; return (int) (pxValue / scale + 0.5f) according to the resolution of the phone. } / * Md5 32-bit or 16-bit encryption * * @ param plainText * @ return 32-bit encryption * / 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. Offset; 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 () } / * regular judgment of mobile phone number * @ 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 }} / * detect whether the current network type is wifi * * @ param context * @ return * / public static int checkedNetWorkType (Context context) {if (! checkedNetWork (context)) {return 0 / no network} ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE) If (cm.getNetworkInfo (ConnectivityManager.TYPE_WIFI). IsConnectedOrConnecting ()) {return 1, inception, Universe, WiFi} else {return 2 / / non-wifi}} / * check if the network is connected * * @ param context * @ return * / public static boolean checkedNetWork (Context context) {/ / get the connection device manager ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE); if (cm = = null) return false / * get the network connection object * / NetworkInfo networkInfo = cm.getActiveNetworkInfo (); if (networkInfo = = null | |! networkInfo.isAvailable ()) {return false;} return true } / * detect whether GPS is open * * @ 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;} / * * Redirect GPS Settings * / public static void openGPSSettings (final Context context) {if (checkGPSIsOpen (context)) {/ / initLocation () / / self-written positioning method} else {/ if it is not opened, the pop-up dialog box AlertDialog.Builder builder = new AlertDialog.Builder (context, R.style.AlertDialogCustom); builder.setTitle ("warm reminder"); builder.setMessage ("the current application needs to turn on the positioning function." Please click\ "Settings\" -\ "location Services\" to turn on the location function. ") ; / / the setup dialog box is cancelable builder.setCancelable (false); builder.setPositiveButton ("Settings", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialogInterface, int I) {dialogInterface.dismiss () / / Redirect GPS settings interface Intent intent = new Intent (Settings.ACTION_LOCATION_SOURCE_SETTINGS); context.startActivity (intent);}}) Builder.setNegativeButton ("cancel", new DialogInterface.OnClickListener () {@ Override public void onClick (DialogInterface dialogInterface, int I) {dialogInterface.dismiss (); ActivityManager.getInstance () .exit ();}}); AlertDialog alertDialog = builder.create () AlertDialog.show ();} / * string is Base64 encoded * @ param str * / public static String StringToBase64 (String str) {String encodedString = Base64.encodeToString (str.getBytes (), Base64.DEFAULT); return encodedString } / * string Base64 decoding * @ param encodedString * @ return * / public static String Base64ToString (String encodedString) {String decodedString = new String (Base64.decode (encodedString,Base64.DEFAULT)); return decodedString;}

There is also a method to calculate the real distance between two points according to longitude and latitude, which usually directly uses the method contained in the integrated third-party map SDK. Here is the code.

/ * add: calculate the real distance between two points * * @ return m * / public static double getDistance (double longitude1, double latitude1, double longitude2, double latitude2) {/ / Dimension double lat1 = (Math.PI / 180) * latitude1; double lat2 = (Math.PI / 180) * latitude2 / / Longitude double lon1 = (Math.PI / 180) * longitude1; double lon2 = (Math.PI / 180) * longitude2; / / Earth radius double R = 6371 / / km between two points. If you want meters, the result is * 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;}

Common file class

There is a lot of code for file classes, so here we only give users who read and write files.

/ * determine whether the SD card is available * @ return SD card is available return true * / public static boolean hasSdcard () {String status = Environment.getExternalStorageState (); return Environment.MEDIA_MOUNTED.equals (status);} / * read the contents of the file *

* default utf-8 encoding * @ param filePath file path * @ return string * @ throws IOException * / public static String readFile (String filePath) throws IOException {return readFile (filePath, "utf-8") } / * read the contents of the file * @ param filePath file directory * @ param charsetName character encoding * @ return String 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 () } / * read the text file into the List string collection (default utf-8 encoding) * @ param filePath file directory * @ return file does not exist to return null Otherwise, the string collection * @ throws IOException * / public static List readFileToList (String filePath) throws IOException {return readFileToList (filePath, "utf-8") is returned. } / * read text file to List string collection * @ param filePath file directory * @ param charsetName character encoding * @ return file does not exist to return null Otherwise, return string collection * / public static List 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 fileContent = new ArrayList (); 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 () } / * write data to the file * @ param filePath file directory * @ param content content to be written * @ param append if it is true, the data is written at the end of the file instead of at the beginning of the file * @ return successfully writes and returns true Write failure returns 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 ();} / * write data to the file

* rewrite data at the beginning of the file by default * @ param filePath file directory * @ param stream byte input stream * @ return returns true if the write succeeds, otherwise it returns false * @ throws IOException * / public static boolean writeFile (String filePath, InputStream stream) throws IOException {return writeFile (filePath, stream, false) } / * write data to the file * @ param filePath file directory * @ param stream byte input stream * @ param append if true, write the data to the end of the file * when false, clear the original data and write from scratch * @ return returns true if the write succeeds, otherwise it returns false * @ throws IOException * / public static boolean writeFile (String filePath, InputStream stream, boolean append) throws IOException {if (TextUtils.isEmpty (filePath)) throw new NullPointerException ("filePath isEmpty") If (stream = = null) throw new NullPointerException ("InputStream is null"); return writeFile (new File (filePath), stream, append) } / * write data to the file * rewrite data at the beginning of the file by default * @ param file specified file * @ param stream byte input stream * @ return returned true after successful write Otherwise, return false * @ throws IOException * / public static boolean writeFile (File file, InputStream stream) throws IOException {return writeFile (file, stream, false) } / * write data to the file * @ param file specifies that the file * @ param stream byte input stream * @ param append is true, rewrite the data at the beginning of the file * when false, clear the original data and write from scratch * @ return returns true if the write succeeds, otherwise it returns 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 () }

Date tool class

/ * convert long time to yyyy-MM-dd HH:mm:ss string

* @ param timeInMillis long value * @ return yyyy-MM-dd HH:mm:ss * / public static String getDateTimeFromMillis (long timeInMillis) {return getDateTimeFormat (new Date (timeInMillis));} / * convert date to yyyy-MM-dd HH:mm:ss string *

* @ param date Date object * @ return yyyy-MM-dd HH:mm:ss * / public static String getDateTimeFormat (Date date) {return dateSimpleFormat (date, defaultDateTimeFormat.get ()) } / * * convert int of year, month and day into string of yyyy-MM-dd * @ param year year * @ param month month 1-12 * @ param day day * Note: month represents the month of Calendar Less than the actual 1 * input is not judged * / public static String getDateFormat (int year, int month, int day) {return getDateFormat (getDate (year, month, day)) } / * time when HH:mm:ss was obtained * @ param date * @ return * / public static String getTimeFormat (Date date) {return dateSimpleFormat (date, defaultTimeFormat.get ()) } / * * formatted date display format * @ param sdate original date format "yyyy-MM-dd" * @ param format formatted date format * @ return formatted date display * / 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) Format date display format * @ param date Date object * @ param format formatted date format * @ return formatted date display * / public static String dateFormat (Date date, String format) {SimpleDateFormat formatter = new SimpleDateFormat (format); return dateSimpleFormat (date, formatter) } / * convert date to the string * @ param date Date * @ param format SimpleDateFormat *

* Note: when SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format is * @ 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)) } / * convert the string in "yyyy-MM-dd HH:mm:ss" format to Date * @ param strDate time string * @ return Date * / public static Date getDateByDateTimeFormat (String strDate) {return getDateByFormat (strDate, defaultDateTimeFormat.get ()) } / * convert the string in "yyyy-MM-dd" format to Date * @ param strDate * @ return Date * / public static Date getDateByDateFormat (String strDate) {return getDateByFormat (strDate, defaultDateFormat.get ()) } / * convert the specified format time string to Date object * @ param strDate time string * @ param format format string * @ return Date * / public static Date getDateByFormat (String strDate, String format) {return getDateByFormat (strDate, new SimpleDateFormat (format));} / * convert the String string to Date according to a certain format

* Note: when SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format * @ param strDate time string * @ param format SimpleDateFormat object * @ exception ParseException date format conversion error * / 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 } / * * convert int on the day of the year to date * @ param year year * @ param month month 1-12 * @ param day day * Note: month represents the month of Calendar, which is 1 * / public static Date getDate (int year, int month, int day) {Calendar mCalendar = Calendar.getInstance (); mCalendar.set (year, month-1, day) Return mCalendar.getTime () } / * find the number of days between the two dates * * @ param strat start date, format yyyy-MM-dd * @ param end end date Format yyyy-MM-dd * @ return number of days difference between two dates * / public static long getIntervalDays (String strat, String end) {return ((java.sql.Date.valueOf (end)) .getTime ()-(java.sql.Date.valueOf (strat)) .getTime () / (3600 * 24 * 1000) } / * * get the current year * @ return year (int) * / public static int getCurrentYear () {Calendar mCalendar = Calendar.getInstance (); return mCalendar.get (Calendar.YEAR) } / * * get the current month * @ return month (int) 1-12 * / public static int getCurrentMonth () {Calendar mCalendar = Calendar.getInstance (); return mCalendar.get (Calendar.MONTH) + 1 } / * * get the date of the month * @ return day (int) * / public static int getDayOfMonth () {Calendar mCalendar = Calendar.getInstance (); return mCalendar.get (Calendar.DAY_OF_MONTH) } / * get today's date (format: yyyy-MM-dd) * @ return yyyy-MM-dd * / public static String getToday () {Calendar mCalendar = Calendar.getInstance (); return getDateFormat (mCalendar.getTime ()) } / * * get yesterday's date (format: yyyy-MM-dd) * @ return yyyy-MM-dd * / public static String getYesterday () {Calendar mCalendar = Calendar.getInstance (); mCalendar.add (Calendar.DATE,-1); return getDateFormat (mCalendar.getTime ()) } / * * get the date of the day before yesterday (format: yyyy-MM-dd) * @ return yyyy-MM-dd * / public static String getBeforeYesterday () {Calendar mCalendar = Calendar.getInstance (); mCalendar.add (Calendar.DATE,-2); return getDateFormat (mCalendar.getTime ()) } / * * get the date * @ param diff difference before or after a few days: positive push backward, negative push forward * @ return * / public static String getOtherDay (int diff) {Calendar mCalendar = Calendar.getInstance (); mCalendar.add (Calendar.DATE, diff); return getDateFormat (mCalendar.getTime ()) } / * get the date object after a given date plus a certain number of days. * * @ param / / date the number of days to be added for the given date object * @ param amount. If it is a forward number, you can use a negative number. * @ return Date plus the Date object after a certain number of days. * / public static String getCalcDateFormat (String sDate, int amount) {Date date = getCalcDate (getDateByDateFormat (sDate), amount); return getDateFormat (date);} / * * get the date object after a given date plus a certain number of days. * * @ param date the number of days to be added for the given date object * @ param amount. If it is a forward number, use a negative number. * @ return Date plus the Date object after a certain number of days. * / public static Date getCalcDate (Date date, int amount) {Calendar cal = Calendar.getInstance (); cal.setTime (date); cal.add (Calendar.DATE, amount); return cal.getTime ();} this is all about the tool classes commonly used in Android development. I hope the above can be helpful and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report