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 - /**
- * Convert from dp to px (pixels) based on the phone's resolution
- */
- public static int dip2px(Context context, float dpValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return ( int ) (dpValue * scale + 0.5f);
- }
-
- /**
- * Convert from px (pixels) to dp based on the phone's resolution
- */
- public static int px2dip(Context context, float pxValue) {
- final float scale = context.getResources().getDisplayMetrics().density;
- return ( int ) (pxValue / scale + 0.5f);
- }
-
- /**
- * 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.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();
- }
-
- /**
- * Mobile phone number regular expression
- * @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 ;
- }
- }
-
- /**
- * Check 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;//wifi
- } else {
- return 2;//non-wifi
- }
- }
-
- /**
- * Check if you are connected to the network
- *
- * @param context
- * @return
- */
- public static boolean checkedNetWork(Context context) {
- // Get the connected 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 ;
- }
-
- /**
- * Check if GPS is turned on
- *
- * @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;
- }
-
- /**
- * Jump to GPS settings
- */
- public static void openGPSSettings(final Context context) {
- if (checkGPSIsOpen(context)) {
- // initLocation(); //Location method written by yourself
- } else {
- // //If it is not open, a dialog box will pop up
- AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogCustom);
-
- builder.setTitle( "Warm Tips" );
- builder.setMessage( "The current application needs to enable the positioning function. Please click \"Settings\"-\"Positioning Service\" to enable the positioning function." );
- //Set the dialog box to be cancelable
- builder.setCancelable( false );
-
- builder.setPositiveButton( "setting" , new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialogInterface, int i) {
- dialogInterface.dismiss();
- // Jump to 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();
- }
- }
-
- /**
- * Base64 encoding of the string
- * @param str
- */
- public static String StringToBase64(String str){
- String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT );
- return encodedString;
- }
-
- /**
- * Base64 decoding of the string
- * @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 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 - /**
- * Supplement: Calculate the true distance between two points
- *
- * @return meter
- */
- public static double getDistance( double longitude1, double latitude1, double longitude2, double latitude2) {
- // Dimensions
- 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;
-
- // The distance between two points is km. If you want meters, just multiply the result by 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 types There are many codes for file classes, and only the code for reading and writing files is given here. - /**
- * Determine whether the SD card is available
- * @return SD card available returns true
- */
- public static boolean hasSdcard() {
- String status = Environment.getExternalStorageState();
- return Environment.MEDIA_MOUNTED.equals(status);
- }
-
- /**
- * Read the contents of the file
- * <br>
- * 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 text files into List string collection (default utf-8 encoding)
- * @param filePath file directory
- * @return Returns null if the file does not exist , otherwise returns a string collection
- * @throws IOException
- */
- public static List<String> readFileToList(String filePath)
- throws IOException {
- return readFileToList(filePath, "utf-8" );
- }
-
- /**
- * Read text files into List string collection
- * @param filePath file directory
- * @param charsetName character encoding
- * @return Returns null if the file does not exist , otherwise returns a string collection
- */
- 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();
- }
- }
- }
- }
-
- /**
- * Write data to the file
- * @param filePath file directory
- * @param content The content to be written
- * @param append If true , data will be written to the end of the file instead of the beginning of the file
- * @return Returns true if writing is successful, false if writing fails
- * @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<br>
- * By default, rewrite data at the beginning of the file
- * @param filePath file directory
- * @param stream byte input stream
- * @return Returns true if writing is successful , otherwise 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 data to the end of the file;
- * When false , clear the original data and write from the beginning
- * @return Returns true if writing is successful , otherwise returns 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);
- }
-
- /**
- * Write data to the file
- * By default, rewrite data at the beginning of the file
- * @param file specifies the file
- * @param stream byte input stream
- * @return Returns true if writing is successful , otherwise returns 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 the file
- * @param stream byte input stream
- * @param append When true , rewrite the data at the beginning of the file;
- * When false , clear the original data and write from the beginning
- * @return Returns true if writing is successful , otherwise 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 Tools - /**
- * Convert long time into yyyy-MM-dd HH:mm:ss string<br>
- * @param timeInMillis time 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
- * <br>
- * @param date Date Object
- * @ return yyyy-MM-dd HH:mm:ss
- */
- public static String getDateTimeFormat( Date date ) {
- return dateSimpleFormat( date , defaultDateTimeFormat.get());
- }
-
- /**
- * Convert the year, month, and day int to a string of yyyy-MM-dd
- * @param year
- * @param month month 1-12
- * @param day
- * Note: Month refers to the calendar month, which is 1 less than the actual month
- * No judgment is made on the input items
- */
- public static String getDateFormat( int year , int month , int day ) {
- return getDateFormat(getDate( year , month , day ));
- }
-
- /**
- * Get the time in HH:mm:ss
- * @param date
- * @return
- */
- public static String getTimeFormat( Date date ) {
- return dateSimpleFormat( date , defaultTimeFormat.get());
- }
-
- /**
- * Format 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 string
- * @param date Date
- * @param format SimpleDateFormat
- * <br>
- * Note: When SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format is used.
- * @ 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 a string in the format of "yyyy-MM-dd HH:mm:ss" to a Date
- * @param strDate time string
- * @return Date
- */
- public static Date getDateByDateTimeFormat(String strDate) {
- return getDateByFormat(strDate, defaultDateTimeFormat.get());
- }
-
- /**
- * Convert a string in the format of "yyyy-MM-dd" to a Date
- * @param strDate
- * @return Date
- */
- public static Date getDateByDateFormat(String strDate) {
- return getDateByFormat(strDate, defaultDateFormat.get());
- }
-
- /**
- * Convert a time string in the specified format into a 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 a String string into a Date according to a certain format <br>
- * Note: When SimpleDateFormat is empty, the default yyyy-MM-dd HH:mm:ss format is used.
- * @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 the int of year, month and day into date
- * @param year
- * @param month month 1-12
- * @param day
- * Note: Month refers to the calendar month, which is 1 less than the actual month
- */
- 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 two dates
- *
- * @param strat start date, format yyyy-MM-dd
- * @param end end date, format yyyy-MM-dd
- * @return the number of days 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 a few days ago or a few days later
- * @param diff difference: 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 adding a certain number of days to the given date.
- *
- * @param // date given date object
- * @param amount The number of days to add. If it is the number of days ahead, a negative number can be used.
- * @return Date object after adding 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 adding a certain number of days to the given date.
- *
- * @param date the given date object
- * @param amount The number of days to add. If it is the number of days ahead, a negative number can be used.
- * @return Date object after adding 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();
- }
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. |