Open the projects you have, there will be a large number of auxiliary classes. Today I will sort out 10 tool classes that will be used in each project for rapid development~~ Thank you here to send me the brothers/sisters of the tool classes in the project in the group~
1. Log tool category
package ; import ; /** * Log unified management category * * * */ public class L { private L() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isDebug = true;// Whether to print a bug, you can initialize it in the application's onCreate function private static final String TAG = "way"; // The following four are the default tag functions public static void i(String msg) { if (isDebug) (TAG, msg); } public static void d(String msg) { if (isDebug) (TAG, msg); } public static void e(String msg) { if (isDebug) (TAG, msg); } public static void v(String msg) { if (isDebug) (TAG, msg); } // Below is the function to pass in a custom tag public static void i(String tag, String msg) { if (isDebug) (tag, msg); } public static void d(String tag, String msg) { if (isDebug) (tag, msg); } public static void e(String tag, String msg) { if (isDebug) (tag, msg); } public static void v(String tag, String msg) { if (isDebug) (tag, msg); } }
The classes you see online should have the name of the original author on the annotation, which is a very simple class; there are also many online offerings to record logs on SDCard, but I have never recorded them, so I introduced the simplest one, you can evaluate whether it needs to be expanded~~
2. Toast unified management category
package ; import ; import ; /** * Toast unified management category * */ public class T { private T() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isShow = true; /** * Show Toast in a short time * * @param context * @param message */ public static void showShort(Context context, CharSequence message) { if (isShow) (context, message, Toast.LENGTH_SHORT).show(); } /** * Show Toast in a short time * * @param context * @param message */ public static void showShort(Context context, int message) { if (isShow) (context, message, Toast.LENGTH_SHORT).show(); } /** * Long-term display of Toast * * @param context * @param message */ public static void showLong(Context context, CharSequence message) { if (isShow) (context, message, Toast.LENGTH_LONG).show(); } /** * Long-term display of Toast * * @param context * @param message */ public static void showLong(Context context, int message) { if (isShow) (context, message, Toast.LENGTH_LONG).show(); } /** * Custom display of Toast time * * @param context * @param message * @param duration */ public static void show(Context context, CharSequence message, int duration) { if (isShow) (context, message, duration).show(); } /** * Custom display of Toast time * * @param context * @param message * @param duration */ public static void show(Context context, int message, int duration) { if (isShow) (context, message, duration).show(); } }
It is also a very simple package, which saves you as much as possible~~
3. SharedPreferences encapsulation class SPUtils
package ; import ; import ; import ; import ; import ; public class SPUtils { /** * File name saved in your phone */ public static final String FILE_NAME = "share_data"; /** * Method to save data. We need to get the specific type of the data to save data, and then call different save methods according to the type. * * @param context * @param key * @param object */ public static void put(Context context, String key, Object object) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); editor = (); if (object instanceof String) { (key, (String) object); } else if (object instanceof Integer) { (key, (Integer) object); } else if (object instanceof Boolean) { (key, (Boolean) object); } else if (object instanceof Float) { (key, (Float) object); } else if (object instanceof Long) { (key, (Long) object); } else { (key, ()); } (editor); } /** * Get the method to save the data. We use the specific type of the saved data based on the default value, and then call the relative method to get the value. * * @param context * @param key * @param defaultObject * @return */ public static Object get(Context context, String key, Object defaultObject) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); if (defaultObject instanceof String) { return (key, (String) defaultObject); } else if (defaultObject instanceof Integer) { return (key, (Integer) defaultObject); } else if (defaultObject instanceof Boolean) { return (key, (Boolean) defaultObject); } else if (defaultObject instanceof Float) { return (key, (Float) defaultObject); } else if (defaultObject instanceof Long) { return (key, (Long) defaultObject); } return null; } /** * Remove the value that has already corresponded to a key value * @param context * @param key */ public static void remove(Context context, String key) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); editor = (); (key); (editor); } /** * Clear all data * @param context */ public static void clear(Context context) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); editor = (); (); (editor); } /** * Check whether a key already exists * @param context * @param key * @return */ public static boolean contains(Context context, String key) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); return (key); } /** * Return all key-value pairs * * @param context * @return */ public static Map<String, ?> getAll(Context context) { SharedPreferences sp = (FILE_NAME, Context.MODE_PRIVATE); return (); } /** * Create a compatible class for a workaround * * @author zhy * */ private static class SharedPreferencesCompat { private static final Method sApplyMethod = findApplyMethod(); /** * Methods of reflection search apply * * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method findApplyMethod() { try { Class clz = ; return ("apply"); } catch (NoSuchMethodException e) { } return null; } /** * If found, use apply to execute, otherwise use commit * * @param editor */ public static void apply( editor) { try { if (sApplyMethod != null) { (editor); return; } } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } (); } } }
We have made suggestions for the use of SharedPreference, and published put, get, remove, clear and other methods. Note that all commit operations in it have been replaced. The purpose is to use apply as much as possible instead of commit. First of all, let’s talk about why, because the commit method is synchronous, and our commit operations are often in UI threads. After all, it is an IO operation, asynchronous as possible; so we use apply to replace it, apply asynchronously for writing; but apply is equivalent to commit, which is a new API. In order to be better compatibility, we have adapted it; SharedPreferencesCompat can also provide a certain reference for creating compatible classes for everyone~~
4. Unit conversion class DensityUtils
package ; import ; import ; /** * Auxiliary class for common unit conversion * * * */ public class DensityUtils { private DensityUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * dp to px * * @param context * @param val * @return */ public static int dp2px(Context context, float dpVal) { return (int) (TypedValue.COMPLEX_UNIT_DIP, dpVal, ().getDisplayMetrics()); } /** * sp to px * * @param context * @param val * @return */ public static int sp2px(Context context, float spVal) { return (int) (TypedValue.COMPLEX_UNIT_SP, spVal, ().getDisplayMetrics()); } /** * px to dp * * @param context * @param pxVal * @return */ public static float px2dp(Context context, float pxVal) { final float scale = ().getDisplayMetrics().density; return (pxVal / scale); } /** * px to sp * * @param fontScale * @param pxVal * @return */ public static float px2sp(Context context, float pxVal) { return (pxVal / ().getDisplayMetrics().scaledDensity); } }
5. SD card-related auxiliary categories SDCardUtils
package ; import ; import ; import ; /** * SD card-related auxiliary categories * * * */ public class SDCardUtils { private SDCardUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * Determine whether SDCard is available * * @return */ public static boolean isSDCardEnable() { return ().equals( Environment.MEDIA_MOUNTED); } /** * Get the SD card path * * @return */ public static String getSDCardPath() { return ().getAbsolutePath() + ; } /** * Get the remaining capacity of the SD card Unit byte * * @return */ public static long getSDCardAllSize() { if (isSDCardEnable()) { StatFs stat = new StatFs(getSDCardPath()); // Get the number of free data blocks long availableBlocks = (long) () - 4; // Get the size of a single data block (byte) long freeBlocks = (); return freeBlocks * availableBlocks; } return 0; } /** * Get the remaining available capacity bytes in the space where the specified path is located, unit byte * * @param filePath * @return Capacity byte SDCard available space, internal storage available space */ public static long getFreeBytes(String filePath) { // If it is the path under the SD card, obtain the available capacity of the SD card if ((getSDCardPath())) { filePath = getSDCardPath(); } else {// If it is an internal storage path, obtain the available capacity of memory storage filePath = ().getAbsolutePath(); } StatFs stat = new StatFs(filePath); long availableBlocks = (long) () - 4; return () * availableBlocks; } /** * Get the system storage path * * @return */ public static String getRootDirectoryPath() { return ().getAbsolutePath(); } }
6. Screen-related auxiliary classes ScreenUtils
package ; import ; import ; import ; import ; import ; import ; import ; /** * Get screen-related auxiliary classes * * * */ public class ScreenUtils { private ScreenUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * Get screen height * * @param context * @return */ public static int getScreenWidth(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); ().getMetrics(outMetrics); return ; } /** * Get screen width * * @param context * @return */ public static int getScreenHeight(Context context) { WindowManager wm = (WindowManager) context .getSystemService(Context.WINDOW_SERVICE); DisplayMetrics outMetrics = new DisplayMetrics(); ().getMetrics(outMetrics); return ; } /** * Get the height of the status bar * * @param context * @return */ public static int getStatusHeight(Context context) { int statusHeight = -1; try { Class<?> clazz = ("$dimen"); Object object = (); int height = (("status_bar_height") .get(object).toString()); statusHeight = ().getDimensionPixelSize(height); } catch (Exception e) { (); } return statusHeight; } /** * Get the current screenshot, including the status bar * * @param activity * @return */ public static Bitmap snapShotWithStatusBar(Activity activity) { View view = ().getDecorView(); (true); (); Bitmap bmp = (); int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = (bmp, 0, 0, width, height); (); return bp; } /** * Get the current screenshot without the status bar * * @param activity * @return */ public static Bitmap snapShotWithoutStatusBar(Activity activity) { View view = ().getDecorView(); (true); (); Bitmap bmp = (); Rect frame = new Rect(); ().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = ; int width = getScreenWidth(activity); int height = getScreenHeight(activity); Bitmap bp = null; bp = (bmp, 0, statusBarHeight, width, height - statusBarHeight); (); return bp; } }
7. App-related auxiliary categories
package ; import ; import ; import ; import ; /** * App-related auxiliary categories * * * */ public class AppUtils { private AppUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * Get the application name */ public static String getAppName(Context context) { try { PackageManager packageManager = (); PackageInfo packageInfo = ( (), 0); int labelRes = ; return ().getString(labelRes); } catch (NameNotFoundException e) { (); } return null; } /** * [Get application version name information] * * @param context * @return The current application version name */ public static String getVersionName(Context context) { try { PackageManager packageManager = (); PackageInfo packageInfo = ( (), 0); return ; } catch (NameNotFoundException e) { (); } return null; } }
8. KeyBoardUtils related auxiliary classes for soft keyboards
package ; import ; import ; import ; /** * Turn the soft keyboard on or off * * @author zhy * */ public class KeyBoardUtils { /** * Check in soft keyboard * * @param mEditText * Input box * @param mContext * Context */ public static void openKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); (mEditText, InputMethodManager.RESULT_SHOWN); (InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); } /** * Close the soft keyboard * * @param mEditText * Input box * @param mContext * Context */ public static void closeKeybord(EditText mEditText, Context mContext) { InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); ((), 0); } }
9. Network-related auxiliary classes NetUtils
package ; import ; import ; import ; import ; import ; import ; /** * Network-related tools * * * */ public class NetUtils { private NetUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } /** * Determine whether the network is connected * * @param context * @return */ public static boolean isConnected(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (null != connectivity) { NetworkInfo info = (); if (null != info && ()) { if (() == ) { return true; } } } return false; } /** * Determine whether it is a wifi connection */ public static boolean isWifi(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (cm == null) return false; return ().getType() == ConnectivityManager.TYPE_WIFI; } /** * Open the network settings interface */ public static void openSetting(Activity activity) { Intent intent = new Intent("/"); ComponentName cm = new ComponentName("", ""); (cm); (""); (intent, 0); } }
10. Http-related auxiliary classes HttpUtils
package ; import ; import ; import ; import ; import ; import ; import ; import ; /** * Tool class for Http requests * * @author zhy * */ public class HttpUtils { private static final int TIMEOUT_IN_MILLIONS = 5000; public interface CallBack { void onRequestComplete(String result); } /** * Asynchronous Get Request * * @param urlStr * @param callBack */ public static void doGetAsyn(final String urlStr, final CallBack callBack) { new Thread() { public void run() { try { String result = doGet(urlStr); if (callBack != null) { (result); } } catch (Exception e) { (); } }; }.start(); } /** * Asynchronous Post request * @param urlStr * @param params * @param callBack * @throws Exception */ public static void doPostAsyn(final String urlStr, final String params, final CallBack callBack) throws Exception { new Thread() { public void run() { try { String result = doPost(urlStr, params); if (callBack != null) { (result); } } catch (Exception e) { (); } }; }.start(); } /** * Get request, get the returned data * * @param urlStr * @return * @throws Exception */ public static String doGet(String urlStr) { URL url = null; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { url = new URL(urlStr); conn = (HttpURLConnection) (); (TIMEOUT_IN_MILLIONS); (TIMEOUT_IN_MILLIONS); ("GET"); ("accept", "*/*"); ("connection", "Keep-Alive"); if (() == 200) { is = (); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[128]; while ((len = (buf)) != -1) { (buf, 0, len); } (); return (); } else { throw new RuntimeException(" responseCode is not 200 ... "); } } catch (Exception e) { (); } finally { try { if (is != null) (); } catch (IOException e) { } try { if (baos != null) (); } catch (IOException e) { } (); } return null ; } /** * Send a request to the specified URL for POST method * * @param url * The URL to send the request * @param param * Request parameters, the request parameters should be in the form of name1=value1&name2=value2. * @return Response result of the remote resource represented * @throws Exception */ public static String doPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // Open the connection to the URL HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // Set common request attributes ("accept", "*/*"); ("connection", "Keep-Alive"); ("POST"); ("Content-Type", "application/x-www-form-urlencoded"); ("charset", "utf-8"); (false); // The following two lines must be set to send a POST request (true); (true); (TIMEOUT_IN_MILLIONS); (TIMEOUT_IN_MILLIONS); if (param != null && !().equals("")) { // Get the output stream corresponding to the URLConnection object out = new PrintWriter(()); // Send request parameters (param); // Buffer of flush output stream (); } // Define the BufferedReader input stream to read the URL response in = new BufferedReader( new InputStreamReader(())); String line; while ((line = ()) != null) { result += line; } } catch (Exception e) { (); } // Use finally blocks to close the output stream and input stream finally { try { if (out != null) { (); } if (in != null) { (); } } catch (IOException ex) { (); } } return result; } }
Summarize
The above is a detailed explanation of the 10 common tool-type example codes introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!