Commonly used tool classes in Android development

Commonly used tool classes in Android development

As a new programmer, it's time to sort out some things. After two or three years, I've forgotten the code as I wrote it, and lost it as I went along. I forgot many problems while I was busy. I decided to write some essays for myself to look back on in my spare time. Readers in need can also take a look at them at will. If there are any mistakes or problems, you can raise them. Although I may not necessarily correct them, O(∩_∩)O haha~

[[228901]]

In daily development, many things have been written countless times. I don't have the habit of rewriting them every time (I wonder if there are any friends who are so straightforward??), so it is necessary to organize your own tool classes. Here are a few that I have used more so far.

Common tools

  1. /**
  2. * Convert from dp to px (pixels) based on the phone's resolution
  3. */
  4. public   static   int dip2px(Context context, float dpValue) {
  5. final float scale = context.getResources().getDisplayMetrics().density;
  6. return ( int ) (dpValue * scale + 0.5f);
  7. }
  8.  
  9. /**
  10. * Convert from px (pixels) to dp based on the phone's resolution
  11. */
  12. public   static   int px2dip(Context context, float pxValue) {
  13. final float scale = context.getResources().getDisplayMetrics().density;
  14. return ( int ) (pxValue / scale + 0.5f);
  15. }
  16.  
  17. /**
  18. * Md5 32-bit or 16-bit encryption
  19. *
  20. * @param plainText
  21. * @return 32-bit encryption
  22. */
  23. public   static String Md5(String plainText) {
  24. StringBuffer buf = null ;
  25. try {
  26. MessageDigest md = MessageDigest.getInstance( "MD5" );
  27. md.update (plainText.getBytes());
  28. byte b[] = md.digest();
  29. int i;
  30. buf = new StringBuffer( "" );
  31. for ( int offset = 0; offset < b.length; offset++) {
  32. i = b[offset];
  33. if (i < 0) i += 256;
  34. if (i < 16)
  35. buf.append( "0" );
  36. buf.append( Integer .toHexString(i));
  37. }
  38.  
  39. } catch (NoSuchAlgorithmException e) {
  40. e.printStackTrace();
  41. }
  42. return buf.toString();
  43. }
  44.  
  45. /**
  46. * Mobile phone number regular expression
  47. * @param str
  48. * @return  
  49. * @throws PatternSyntaxException
  50. */
  51. public   static boolean isPhoneNumber(String str) throws PatternSyntaxException {
  52. if (str != null ) {
  53. String pattern = "(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}" ;
  54.  
  55. Pattern r = Pattern.compile(pattern);
  56. Matcher m = r.matcher(str);
  57. return m.matches();
  58. } else {
  59. return   false ;
  60. }
  61. }
  62.  
  63. /**
  64. * Check whether the current network type is wifi
  65. *
  66. * @param context
  67. * @return  
  68. */
  69. public   static   int checkedNetWorkType(Context context) {
  70. if (!checkedNetWork(context)) {
  71. return 0;//No network
  72. }
  73. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  74. if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) {
  75. return 1;//wifi
  76. } else {
  77. return 2;//non-wifi
  78. }
  79. }
  80.  
  81. /**
  82. * Check if you are connected to the network
  83. *
  84. * @param context
  85. * @return  
  86. */
  87. public   static boolean checkedNetWork(Context context) {
  88. // Get the connected device manager
  89. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  90. if (cm == null ) return   false ;
  91. /**
  92. * Get the network connection object
  93. */
  94. NetworkInfo networkInfo = cm.getActiveNetworkInfo();
  95.  
  96. if (networkInfo == null || !networkInfo.isAvailable()) {
  97. return   false ;
  98. }
  99. return   true ;
  100. }
  101.  
  102. /**
  103. * Check if GPS is turned on
  104. *
  105. * @return  
  106. */
  107. public   static boolean checkGPSIsOpen(Context context) {
  108. boolean isOpen;
  109. LocationManager locationManager = (LocationManager) context
  110. .getSystemService(Context.LOCATION_SERVICE);
  111. if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
  112. isOpen = true ;
  113. } else {
  114. isOpen = false ;
  115. }
  116.  
  117. return isOpen;
  118. }
  119.  
  120. /**
  121. * Jump to GPS settings
  122. */
  123. public   static void openGPSSettings(final Context context) {
  124. if (checkGPSIsOpen(context)) {
  125. // initLocation(); //Location method written by yourself
  126. } else {
  127. // //If it is not open, a dialog box will pop up
  128. AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);
  129.  
  130. builder.setTitle( "Warm Tips" );
  131. builder.setMessage( "The current application needs to enable the positioning function. Please click \"Settings\"-\"Positioning Service\" to enable the positioning function." );
  132. //Set the dialog box to be cancelable
  133. builder.setCancelable( false );
  134.  
  135. builder.setPositiveButton( "setting" , new DialogInterface.OnClickListener() {
  136. @Override
  137. public void onClick(DialogInterface dialogInterface, int i) {
  138. dialogInterface.dismiss();
  139. // Jump to GPS settings interface
  140. Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  141. context.startActivity(intent);
  142. }
  143. });
  144. builder.setNegativeButton( "Cancel" , new DialogInterface.OnClickListener() {
  145. @Override
  146. public void onClick(DialogInterface dialogInterface, int i) {
  147. dialogInterface.dismiss();
  148. ActivityManager.getInstance().exit();
  149. }
  150. });
  151. AlertDialog alertDialog = builder.create ();
  152. alertDialog.show();
  153. }
  154. }
  155.  
  156. /**
  157. * Base64 encoding of the string
  158. * @param str
  159. */
  160. public   static String StringToBase64(String str){
  161. String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT );
  162. return encodedString;
  163. }
  164.  
  165. /**
  166. * Base64 decoding of the string
  167. * @param encodedString
  168. * @return  
  169. */
  170. public   static String Base64ToString(String encodedString){
  171. String decodedString =new String(Base64.decode(encodedString,Base64. DEFAULT ));
  172. return decodedString;
  173. }

There is also a method for calculating the real distance between two points based on longitude and latitude. Generally, the method included in the integrated third-party map SDK is used directly. Here is the code

  1. /**
  2. * Supplement: Calculate the true distance between two points
  3. *
  4. * @return meter
  5. */
  6. public   static   double getDistance( double longitude1, double latitude1, double longitude2, double latitude2) {
  7. // Dimensions
  8. double lat1 = (Math.PI / 180) * latitude1;
  9. double lat2 = (Math.PI / 180) * latitude2;
  10.  
  11. // Longitude
  12. double lon1 = (Math.PI / 180) * longitude1;
  13. double lon2 = (Math.PI / 180) * longitude2;
  14.  
  15. //Earth radius
  16. double R = 6371;
  17.  
  18. // The distance between two points is km. If you want meters, just multiply the result by 1000
  19. double d = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;
  20.  
  21. return d * 1000;
  22. }

Common file types

There are many codes for file classes, and only the code for reading and writing files is given here.

  1. /**
  2. * Determine whether the SD card is available
  3. * @return SD card available returns true  
  4. */
  5. public   static boolean hasSdcard() {
  6. String status = Environment.getExternalStorageState();
  7. return Environment.MEDIA_MOUNTED.equals(status);
  8. }
  9.  
  10. /**
  11. * Read the contents of the file
  12. * <br>
  13. * Default utf-8 encoding
  14. * @param filePath file path
  15. * @return string
  16. * @throws IOException
  17. */
  18. public   static String readFile(String filePath) throws IOException {
  19. return readFile(filePath, "utf-8" );
  20. }
  21.  
  22. /**
  23. * Read the contents of the file
  24. * @param filePath file directory
  25. * @param charsetName character encoding
  26. * @return String string
  27. */
  28. public   static String readFile(String filePath, String charsetName)
  29. throws IOException {
  30. if (TextUtils.isEmpty(filePath))
  31. return   null ;
  32. if (TextUtils.isEmpty(charsetName))
  33. charsetName = "utf-8" ;
  34. File file = new File(filePath);
  35. StringBuilder fileContent = new StringBuilder( "" );
  36. if (file == null || !file.isFile())
  37. return   null ;
  38. BufferedReader reader = null ;
  39. try {
  40. InputStreamReader is = new InputStreamReader(new FileInputStream(
  41. file), charsetName);
  42. reader = new BufferedReader( is );
  43. String line = null ;
  44. while ((line = reader.readLine()) != null ) {
  45. if (!fileContent.toString().equals( "" )) {
  46. fileContent.append( "\r\n" );
  47. }
  48. fileContent.append(line);
  49. }
  50. return fileContent.toString();
  51. finally
  52. if (reader != null ) {
  53. try {
  54. reader.close () ;
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }
  61.  
  62. /**
  63. * Read text files into List string collection (default utf-8 encoding)
  64. * @param filePath file directory
  65. * @return Returns null if the file does not exist , otherwise returns a string collection
  66. * @throws IOException
  67. */
  68. public   static List<String> readFileToList(String filePath)
  69. throws IOException {
  70. return readFileToList(filePath, "utf-8" );
  71. }
  72.  
  73. /**
  74. * Read text files into List string collection
  75. * @param filePath file directory
  76. * @param charsetName character encoding
  77. * @return Returns null if the file does not exist , otherwise returns a string collection
  78. */
  79. public   static List<String> readFileToList(String filePath,
  80. String charsetName) throws IOException {
  81. if (TextUtils.isEmpty(filePath))
  82. return   null ;
  83. if (TextUtils.isEmpty(charsetName))
  84. charsetName = "utf-8" ;
  85. File file = new File(filePath);
  86. List<String> fileContent = new ArrayList<String>();
  87. if (file == null || !file.isFile()) {
  88. return   null ;
  89. }
  90. BufferedReader reader = null ;
  91. try {
  92. InputStreamReader is = new InputStreamReader(new FileInputStream(
  93. file), charsetName);
  94. reader = new BufferedReader( is );
  95. String line = null ;
  96. while ((line = reader.readLine()) != null ) {
  97. fileContent.add (line);
  98. }
  99. return fileContent;
  100. finally
  101. if (reader != null ) {
  102. try {
  103. reader.close () ;
  104. } catch (IOException e) {
  105. e.printStackTrace();
  106. }
  107. }
  108. }
  109. }
  110.  
  111. /**
  112. * Write data to the file
  113. * @param filePath file directory
  114. * @param content The content to be written
  115. * @param append If true , data will be written to the end of the file instead of the beginning of the file
  116. * @return Returns true if writing is successful, false if writing fails  
  117. * @throws IOException
  118. */
  119. public   static boolean writeFile(String filePath, String content,
  120. boolean append) throws IOException {
  121. if (TextUtils.isEmpty(filePath))
  122. return   false ;
  123. if (TextUtils.isEmpty(content))
  124. return   false ;
  125. FileWriter fileWriter = null ;
  126. try {
  127. createFile(filePath);
  128. fileWriter = new FileWriter(filePath, append);
  129. fileWriter.write(content);
  130. fileWriter.flush();
  131. return   true ;
  132. finally
  133. if (fileWriter != null ) {
  134. try {
  135. fileWriter. close ();
  136. } catch (IOException e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. }
  141. }
  142.  
  143.  
  144. /**
  145. * Write data to the file<br>
  146. * By default, rewrite data at the beginning of the file
  147. * @param filePath file directory
  148. * @param stream byte input stream
  149. * @return Returns true if writing is successful , otherwise returns false  
  150. * @throws IOException
  151. */
  152. public   static boolean writeFile(String filePath, InputStream stream)
  153. throws IOException {
  154. return writeFile(filePath, stream, false );
  155. }
  156.  
  157. /**
  158. * Write data to the file
  159. * @param filePath file directory
  160. * @param stream byte input stream
  161. * @param append If true , write data to the end of the file;
  162. * When false , clear the original data and write from the beginning
  163. * @return Returns true if writing is successful , otherwise returns false  
  164. * @throws IOException
  165. */
  166. public   static boolean writeFile(String filePath, InputStream stream,
  167. boolean append) throws IOException {
  168. if (TextUtils.isEmpty(filePath))
  169. throw new NullPointerException( "filePath is Empty" );
  170. if (stream == null )
  171. throw new NullPointerException( "InputStream is null" );
  172. return writeFile(new File(filePath), stream,
  173. append);
  174. }
  175.  
  176. /**
  177. * Write data to the file
  178. * By default, rewrite data at the beginning of the file
  179. * @param file specifies the file
  180. * @param stream byte input stream
  181. * @return Returns true if writing is successful , otherwise returns false  
  182. * @throws IOException
  183. */
  184. public   static boolean writeFile(File file, InputStream stream)
  185. throws IOException {
  186. return writeFile(file, stream, false );
  187. }
  188.  
  189. /**
  190. * Write data to the file
  191. * @param file specifies the file
  192. * @param stream byte input stream
  193. * @param append When true , rewrite the data at the beginning of the file;
  194. * When false , clear the original data and write from the beginning
  195. * @return Returns true if writing is successful , otherwise returns false  
  196. * @throws IOException
  197. */
  198. public   static boolean writeFile(File file, InputStream stream,
  199. boolean append) throws IOException {
  200. if (file == null )
  201. throw new NullPointerException( "file = null" );
  202. OutputStream out = null ;
  203. try {
  204. createFile(file.getAbsolutePath());
  205. out = new FileOutputStream(file, append);
  206. byte data[] = new byte[1024];
  207. int length = -1;
  208. while ((length = stream. read (data)) != -1) {
  209. out .write(data, 0, length);
  210. }
  211. out .flush();
  212. return   true ;
  213. finally
  214. if ( out != null ) {
  215. try {
  216. out . close ();
  217. stream.close ();
  218. } catch (IOException e) {
  219. e.printStackTrace();
  220. }
  221. }
  222. }
  223. }

Date Tools

  1. /**
  2. * Convert long time into yyyy-MM-dd HH:mm:ss string<br>
  3. * @param timeInMillis time long value
  4. * @ return yyyy-MM-dd HH:mm:ss
  5. */
  6. public   static String getDateTimeFromMillis(long timeInMillis) {
  7. return getDateTimeFormat(new Date (timeInMillis));
  8. }
  9.  
  10. /**
  11. * Convert date to yyyy-MM-dd HH:mm:ss string
  12. * <br>
  13. * @param date   Date Object
  14. * @ return yyyy-MM-dd HH:mm:ss
  15. */
  16. public   static String getDateTimeFormat( Date   date ) {
  17. return dateSimpleFormat( date , defaultDateTimeFormat.get());
  18. }
  19.  
  20. /**
  21. * Convert the year, month, and day int to a string of yyyy-MM-dd
  22. * @param year
  23. * @param month month 1-12
  24. * @param day
  25. * Note: Month refers to the calendar month, which is 1 less than the actual month
  26. * No judgment is made on the input items
  27. */
  28. public   static String getDateFormat( int   year , int   month , int   day ) {
  29. return getDateFormat(getDate( year , month , day ));
  30. }
  31.  
  32. /**
  33. * Get the time in HH:mm:ss
  34. * @param date  
  35. * @return  
  36. */
  37. public   static String getTimeFormat( Date   date ) {
  38. return dateSimpleFormat( date , defaultTimeFormat.get());
  39. }
  40.  
  41. /**
  42. * Format date display format
  43. * @param sdate original date format "yyyy-MM-dd"  
  44. * @param format formatted date format
  45. * @return formatted date display
  46. */
  47. public   static String dateFormat(String sdate, String format) {
  48. SimpleDateFormat formatter = new SimpleDateFormat(format);
  49. java.sql.Date   date = java.sql. Date .valueOf(sdate);
  50. return dateSimpleFormat( date , formatter);
  51. }
  52.  
  53. /**
  54. * Format date display format
  55. * @param date   Date Object
  56. * @param format formatted date format
  57. * @return formatted date display
  58. */
  59. public   static String dateFormat( Date   date , String format) {
  60. SimpleDateFormat formatter = new SimpleDateFormat(format);
  61. return dateSimpleFormat( date , formatter);
  62. }
  63. /**
  64. * Convert date to string
  65. * @param date   Date  
  66. * @param format SimpleDateFormat
  67. * <br>
  68. * Note: When SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format is used.
  69. * @ return yyyy-MM-dd HH:mm:ss
  70. */
  71. public   static String dateSimpleFormat( Date   date , SimpleDateFormat format) {
  72. if (format == null )
  73. format = defaultDateTimeFormat.get();
  74. return ( date == null ? "" : format.format( date ));
  75. }
  76.  
  77. /**
  78. * Convert a string in the format of "yyyy-MM-dd HH:mm:ss" to a Date  
  79. * @param strDate time string
  80. * @return   Date  
  81. */
  82. public   static   Date getDateByDateTimeFormat(String strDate) {
  83. return getDateByFormat(strDate, defaultDateTimeFormat.get());
  84. }
  85.  
  86. /**
  87. * Convert a string in the format of "yyyy-MM-dd" to a Date  
  88. * @param strDate
  89. * @return   Date  
  90. */
  91. public   static   Date getDateByDateFormat(String strDate) {
  92. return getDateByFormat(strDate, defaultDateFormat.get());
  93. }
  94.  
  95. /**
  96. * Convert a time string in the specified format into a Date object
  97. * @param strDate time string
  98. * @param format format string
  99. * @return   Date  
  100. */
  101. public   static   Date getDateByFormat(String strDate, String format) {
  102. return getDateByFormat(strDate, new SimpleDateFormat(format));
  103. }
  104.  
  105. /**
  106. * Convert a String string into a Date according to a certain format <br>
  107. * Note: When SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format is used.
  108. * @param strDate time string
  109. * @param format SimpleDateFormat object
  110. * @exception ParseException Date format conversion error
  111. */
  112. private static   Date getDateByFormat(String strDate, SimpleDateFormat format) {
  113. if (format == null )
  114. format = defaultDateTimeFormat.get();
  115. try {
  116. return format.parse(strDate);
  117. } catch (ParseException e) {
  118. e.printStackTrace();
  119. }
  120. return   null ;
  121. }
  122.  
  123. /**
  124. * Convert the int of year, month and day into date  
  125. * @param year
  126. * @param month month 1-12
  127. * @param day
  128. * Note: Month refers to the calendar month, which is 1 less than the actual month
  129. */
  130. public   static   Date getDate( int   year , int   month , int   day ) {
  131. Calendar mCalendar = Calendar.getInstance();
  132. mCalendar.set ( year , month - 1, day );
  133. return mCalendar.getTime();
  134. }
  135.  
  136. /**
  137. * Find the number of days between two dates
  138. *
  139. * @param strat start date, format yyyy-MM-dd
  140. * @param end end date, format yyyy-MM-dd
  141. * @return the number of days between two dates
  142. */
  143. public   static long getIntervalDays(String strat, String end ) {
  144. return ((java.sql. Date .valueOf( end )).getTime() - (java.sql. Date  
  145. .valueOf(strat)).getTime()) / (3600 * 24 * 1000);
  146. }
  147.  
  148. /**
  149. * Get the current year
  150. * @return   year ( int )
  151. */
  152. public   static   int getCurrentYear() {
  153. Calendar mCalendar = Calendar.getInstance();
  154. return mCalendar.get ( Calendar.YEAR );
  155. }
  156.  
  157. /**
  158. * Get the current month
  159. * @return   month ( int ) 1-12
  160. */
  161. public   static   int getCurrentMonth() {
  162. Calendar mCalendar = Calendar.getInstance();
  163. return mCalendar.get (Calendar.MONTH ) + 1;
  164. }
  165.  
  166. /**
  167. * Get the date of the month
  168. * @return   day ( int )
  169. */
  170. public   static   int getDayOfMonth() {
  171. Calendar mCalendar = Calendar.getInstance();
  172. return mCalendar.get(Calendar.DAY_OF_MONTH);
  173. }
  174.  
  175. /**
  176. * Get today's date (format: yyyy-MM-dd)
  177. * @return yyyy-MM-dd
  178. */
  179. public   static String getToday() {
  180. Calendar mCalendar = Calendar.getInstance();
  181. return getDateFormat(mCalendar.getTime());
  182. }
  183.  
  184. /**
  185. * Get yesterday's date (format: yyyy-MM-dd)
  186. * @return yyyy-MM-dd
  187. */
  188. public   static String getYesterday() {
  189. Calendar mCalendar = Calendar.getInstance();
  190. mCalendar. add (Calendar. DATE , -1);
  191. return getDateFormat(mCalendar.getTime());
  192. }
  193.  
  194. /**
  195. * Get the date of the day before yesterday (format: yyyy-MM-dd)
  196. * @return yyyy-MM-dd
  197. */
  198. public   static String getBeforeYesterday() {
  199. Calendar mCalendar = Calendar.getInstance();
  200. mCalendar. add (Calendar. DATE , -2);
  201. return getDateFormat(mCalendar.getTime());
  202. }
  203.  
  204. /**
  205. * Get the date a few days ago or a few days later
  206. * @param diff difference: positive push backward, negative push forward
  207. * @return  
  208. */
  209. public   static String getOtherDay( int diff) {
  210. Calendar mCalendar = Calendar.getInstance();
  211. mCalendar. add (Calendar. DATE , diff);
  212. return getDateFormat(mCalendar.getTime());
  213. }
  214.  
  215. /**
  216. * Get the date object after adding a certain number of days to the given date.
  217. *
  218. * @param // date given date object
  219. * @param amount The number of days to add. If it is the number of days ahead, a negative number can be used.
  220. * @return   Date object after adding a certain number of days .
  221. */
  222. public   static String getCalcDateFormat(String sDate, int amount) {
  223. Date   date = getCalcDate(getDateByDateFormat(sDate), amount);
  224. return getDateFormat( date );
  225. }
  226.  
  227. /**
  228. * Get the date object after adding a certain number of days to the given date.
  229. *
  230. * @param date the given date object
  231. * @param amount The number of days to add. If it is the number of days ahead, a negative number can be used.
  232. * @return   Date object after adding a certain number of days .
  233. */
  234. public   static   Date getCalcDate( Date   date , int amount) {
  235. Calendar cal = Calendar.getInstance();
  236. cal.setTime( date );
  237. cal. add (Calendar. DATE , amount);
  238. return cal.getTime();
  239. }

It's basically all code, not because I'm lazy (if I'm lazy, you can bite me), it's mainly to facilitate novice drivers to copy it. Okay, this essay ends here.

<<:  Android phone fluency ranking: Xiaomi fifth, OnePlus first, where is Huawei?

>>:  First step in iOS reverse engineering: Modifying WeChat without jailbreaking (Appearance)

Recommend

Analysis of marketing promotion hot spots in September!

September is the start of the school year, and th...

Toutiao advertising oCPM bidding advantages and advertising resources!

Today, I will tell you what are the advantages of...

17-day fast weight loss training camp Tang Youxin yoga Pilates massage

17-day fast weight loss training camp Tang Youxin...

How to increase traffic, popularity and playback volume of Tik Tok works?

Those who have made or played Douyin know that Do...