Android Quick Development Series 10 Common Tool Classes

Reprinted from: http://blog.csdn.net/lmj623565791/article/details/38965311


1. Logging Tool Class L.java

  1. package com.zhy.utils;  
  2.   
  3. import android.util.Log;  
  4.   
  5. /** 
  6.  * Log Unified Management Class 
  7.  *  
  8.  *  
  9.  *  
  10.  */  
  11. public class L  
  12. {  
  13.   
  14.     private L()  
  15.     {  
  16.         /* cannot be instantiated */  
  17.         throw new UnsupportedOperationException("cannot be instantiated");  
  18.     }  
  19.   
  20.     public static boolean isDebug = true;//Whether a print bug is required can be initialized in the onCreate function of the application  
  21.     private static final String TAG = "way";  
  22.   
  23.     //The following four are functions of the default tag  
  24.     public static void i(String msg)  
  25.     {  
  26.         if (isDebug)  
  27.             Log.i(TAG, msg);  
  28.     }  
  29.   
  30.     public static void d(String msg)  
  31.     {  
  32.         if (isDebug)  
  33.             Log.d(TAG, msg);  
  34.     }  
  35.   
  36.     public static void e(String msg)  
  37.     {  
  38.         if (isDebug)  
  39.             Log.e(TAG, msg);  
  40.     }  
  41.   
  42.     public static void v(String msg)  
  43.     {  
  44.         if (isDebug)  
  45.             Log.v(TAG, msg);  
  46.     }  
  47.   
  48.     //The following is a function that passes in a custom tag  
  49.     public static void i(String tag, String msg)  
  50.     {  
  51.         if (isDebug)  
  52.             Log.i(tag, msg);  
  53.     }  
  54.   
  55.     public static void d(String tag, String msg)  
  56.     {  
  57.         if (isDebug)  
  58.             Log.i(tag, msg);  
  59.     }  
  60.   
  61.     public static void e(String tag, String msg)  
  62.     {  
  63.         if (isDebug)  
  64.             Log.i(tag, msg);  
  65.     }  
  66.   
  67.     public static void v(String tag, String msg)  
  68.     {  
  69.         if (isDebug)  
  70.             Log.i(tag, msg);  
  71.     }  
  72. }  


The classes I see on the internet, the name of the original creator should be on the annotation, a very simple one; there are also many classes available on the Internet that record logs on SDCard s, but I have never recorded them, so it's the simplest to introduce one, so you can evaluate if it needs to be expanded~~

2. Toast Unified Management Class

  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.widget.Toast;  
  5.   
  6. /** 
  7.  * Toast Unified Management Class 
  8.  *  
  9.  */  
  10. public class T  
  11. {  
  12.   
  13.     private T()  
  14.     {  
  15.         /* cannot be instantiated */  
  16.         throw new UnsupportedOperationException("cannot be instantiated");  
  17.     }  
  18.   
  19.     public static boolean isShow = true;  
  20.   
  21.     /** 
  22.      * Short time to show Toast 
  23.      *  
  24.      * @param context 
  25.      * @param message 
  26.      */  
  27.     public static void showShort(Context context, CharSequence message)  
  28.     {  
  29.         if (isShow)  
  30.             Toast.makeText(context, message, Toast.LENGTH_SHORT).show();  
  31.     }  
  32.   
  33.     /** 
  34.      * Short time to show Toast 
  35.      *  
  36.      * @param context 
  37.      * @param message 
  38.      */  
  39.     public static void showShort(Context context, int message)  
  40.     {  
  41.         if (isShow)  
  42.             Toast.makeText(context, message, Toast.LENGTH_SHORT).show();  
  43.     }  
  44.   
  45.     /** 
  46.      * Show Toast for a long time 
  47.      *  
  48.      * @param context 
  49.      * @param message 
  50.      */  
  51.     public static void showLong(Context context, CharSequence message)  
  52.     {  
  53.         if (isShow)  
  54.             Toast.makeText(context, message, Toast.LENGTH_LONG).show();  
  55.     }  
  56.   
  57.     /** 
  58.      * Show Toast for a long time 
  59.      *  
  60.      * @param context 
  61.      * @param message 
  62.      */  
  63.     public static void showLong(Context context, int message)  
  64.     {  
  65.         if (isShow)  
  66.             Toast.makeText(context, message, Toast.LENGTH_LONG).show();  
  67.     }  
  68.   
  69.     /** 
  70.      * Custom Display Toast Time 
  71.      *  
  72.      * @param context 
  73.      * @param message 
  74.      * @param duration 
  75.      */  
  76.     public static void show(Context context, CharSequence message, int duration)  
  77.     {  
  78.         if (isShow)  
  79.             Toast.makeText(context, message, duration).show();  
  80.     }  
  81.   
  82.     /** 
  83.      * Custom Display Toast Time 
  84.      *  
  85.      * @param context 
  86.      * @param message 
  87.      * @param duration 
  88.      */  
  89.     public static void show(Context context, int message, int duration)  
  90.     {  
  91.         if (isShow)  
  92.             Toast.makeText(context, message, duration).show();  
  93.     }  
  94.   
  95. }  


It's also a very simple encapsulation that saves ~~

3. SharedPreferences encapsulation class SPUtils

  1. package com.zhy.utils;  
  2.   
  3. import java.lang.reflect.InvocationTargetException;  
  4. import java.lang.reflect.Method;  
  5. import java.util.Map;  
  6.   
  7. import android.content.Context;  
  8. import android.content.SharedPreferences;  
  9.   
  10. public class SPUtils  
  11. {  
  12.     /** 
  13.      * File name saved in the phone 
  14.      */  
  15.     public static final String FILE_NAME = "share_data";  
  16.   
  17.     /** 
  18.      * How to save data, we need to get the specific type of data to save, and then call different save methods depending on the type 
  19.      *  
  20.      * @param context 
  21.      * @param key 
  22.      * @param object 
  23.      */  
  24.     public static void put(Context context, String key, Object object)  
  25.     {  
  26.   
  27.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  28.                 Context.MODE_PRIVATE);  
  29.         SharedPreferences.Editor editor = sp.edit();  
  30.   
  31.         if (object instanceof String)  
  32.         {  
  33.             editor.putString(key, (String) object);  
  34.         } else if (object instanceof Integer)  
  35.         {  
  36.             editor.putInt(key, (Integer) object);  
  37.         } else if (object instanceof Boolean)  
  38.         {  
  39.             editor.putBoolean(key, (Boolean) object);  
  40.         } else if (object instanceof Float)  
  41.         {  
  42.             editor.putFloat(key, (Float) object);  
  43.         } else if (object instanceof Long)  
  44.         {  
  45.             editor.putLong(key, (Long) object);  
  46.         } else  
  47.         {  
  48.             editor.putString(key, object.toString());  
  49.         }  
  50.   
  51.         SharedPreferencesCompat.apply(editor);  
  52.     }  
  53.   
  54.     /** 
  55.      * To get the method to save the data, we get the specific type of data to save based on the default value, and then call the relative method to get the value 
  56.      *  
  57.      * @param context 
  58.      * @param key 
  59.      * @param defaultObject 
  60.      * @return 
  61.      */  
  62.     public static Object get(Context context, String key, Object defaultObject)  
  63.     {  
  64.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  65.                 Context.MODE_PRIVATE);  
  66.   
  67.         if (defaultObject instanceof String)  
  68.         {  
  69.             return sp.getString(key, (String) defaultObject);  
  70.         } else if (defaultObject instanceof Integer)  
  71.         {  
  72.             return sp.getInt(key, (Integer) defaultObject);  
  73.         } else if (defaultObject instanceof Boolean)  
  74.         {  
  75.             return sp.getBoolean(key, (Boolean) defaultObject);  
  76.         } else if (defaultObject instanceof Float)  
  77.         {  
  78.             return sp.getFloat(key, (Float) defaultObject);  
  79.         } else if (defaultObject instanceof Long)  
  80.         {  
  81.             return sp.getLong(key, (Long) defaultObject);  
  82.         }  
  83.   
  84.         return null;  
  85.     }  
  86.   
  87.     /** 
  88.      * Remove a value that already corresponds to a key value 
  89.      * @param context 
  90.      * @param key 
  91.      */  
  92.     public static void remove(Context context, String key)  
  93.     {  
  94.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  95.                 Context.MODE_PRIVATE);  
  96.         SharedPreferences.Editor editor = sp.edit();  
  97.         editor.remove(key);  
  98.         SharedPreferencesCompat.apply(editor);  
  99.     }  
  100.   
  101.     /** 
  102.      * Clear all data 
  103.      * @param context 
  104.      */  
  105.     public static void clear(Context context)  
  106.     {  
  107.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  108.                 Context.MODE_PRIVATE);  
  109.         SharedPreferences.Editor editor = sp.edit();  
  110.         editor.clear();  
  111.         SharedPreferencesCompat.apply(editor);  
  112.     }  
  113.   
  114.     /** 
  115.      * Query if a key already exists 
  116.      * @param context 
  117.      * @param key 
  118.      * @return 
  119.      */  
  120.     public static boolean contains(Context context, String key)  
  121.     {  
  122.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  123.                 Context.MODE_PRIVATE);  
  124.         return sp.contains(key);  
  125.     }  
  126.   
  127.     /** 
  128.      * Returns all key-value pairs 
  129.      *  
  130.      * @param context 
  131.      * @return 
  132.      */  
  133.     public static Map<String, ?> getAll(Context context)  
  134.     {  
  135.         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
  136.                 Context.MODE_PRIVATE);  
  137.         return sp.getAll();  
  138.     }  
  139.   
  140.     /** 
  141.      * Create a compatible class that resolves the SharedPreferencesCompat.apply method 
  142.      *  
  143.      * @author zhy 
  144.      *  
  145.      */  
  146.     private static class SharedPreferencesCompat  
  147.     {  
  148.         private static final Method sApplyMethod = findApplyMethod();  
  149.   
  150.         /** 
  151.          * Reflection method for finding apply 
  152.          *  
  153.          * @return 
  154.          */  
  155.         @SuppressWarnings({ "unchecked""rawtypes" })  
  156.         private static Method findApplyMethod()  
  157.         {  
  158.             try  
  159.             {  
  160.                 Class clz = SharedPreferences.Editor.class;  
  161.                 return clz.getMethod("apply");  
  162.             } catch (NoSuchMethodException e)  
  163.             {  
  164.             }  
  165.   
  166.             return null;  
  167.         }  
  168.   
  169.         /** 
  170.          * Use apply if found, commit otherwise 
  171.          *  
  172.          * @param editor 
  173.          */  
  174.         public static void apply(SharedPreferences.Editor editor)  
  175.         {  
  176.             try  
  177.             {  
  178.                 if (sApplyMethod != null)  
  179.                 {  
  180.                     sApplyMethod.invoke(editor);  
  181.                     return;  
  182.                 }  
  183.             } catch (IllegalArgumentException e)  
  184.             {  
  185.             } catch (IllegalAccessException e)  
  186.             {  
  187.             } catch (InvocationTargetException e)  
  188.             {  
  189.             }  
  190.             editor.commit();  
  191.         }  
  192.     }  
  193.   
  194. }  

Suggested encapsulation of the use of SharedPreference, publishing put, get, remove, clear and so on;

Note that all commit operations inside have been replaced with SharedPreferencesCompat.apply in order to replace commit with apply whenever possible

First of all, why, because the commit method is synchronous, and most of our commit operations are UI threads, after all, IO operations, as asynchronous as possible;

So instead of using apply, apply writes asynchronously;

But apply is equivalent to commit as a new API, and we adapted it for better compatibility;

SharedPreferencesCompat also provides a reference for creating compatible classes~~


4. Unit Conversion Class DensityUtils

  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.util.TypedValue;  
  5.   
  6. /** 
  7.  * Auxiliary Classes for Common Unit Conversion 
  8.  *  
  9.  *  
  10.  *  
  11.  */  
  12. public class DensityUtils  
  13. {  
  14.     private DensityUtils()  
  15.     {  
  16.         /* cannot be instantiated */  
  17.         throw new UnsupportedOperationException("cannot be instantiated");  
  18.     }  
  19.   
  20.     /** 
  21.      * dp To px 
  22.      *  
  23.      * @param context 
  24.      * @param val 
  25.      * @return 
  26.      */  
  27.     public static int dp2px(Context context, float dpVal)  
  28.     {  
  29.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,  
  30.                 dpVal, context.getResources().getDisplayMetrics());  
  31.     }  
  32.   
  33.     /** 
  34.      * sp To px 
  35.      *  
  36.      * @param context 
  37.      * @param val 
  38.      * @return 
  39.      */  
  40.     public static int sp2px(Context context, float spVal)  
  41.     {  
  42.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,  
  43.                 spVal, context.getResources().getDisplayMetrics());  
  44.     }  
  45.   
  46.     /** 
  47.      * px To dp 
  48.      *  
  49.      * @param context 
  50.      * @param pxVal 
  51.      * @return 
  52.      */  
  53.     public static float px2dp(Context context, float pxVal)  
  54.     {  
  55.         final float scale = context.getResources().getDisplayMetrics().density;  
  56.         return (pxVal / scale);  
  57.     }  
  58.   
  59.     /** 
  60.      * px Transfer to sp 
  61.      *  
  62.      * @param fontScale 
  63.      * @param pxVal 
  64.      * @return 
  65.      */  
  66.     public static float px2sp(Context context, float pxVal)  
  67.     {  
  68.         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);  
  69.     }  
  70.   
  71. }  

5. SD Card Utils

  1. package com.zhy.utils;  
  2.   
  3. import java.io.File;  
  4.   
  5. import android.os.Environment;  
  6. import android.os.StatFs;  
  7.   
  8. /** 
  9.  * SD Card-related auxiliary classes 
  10.  *  
  11.  *  
  12.  *  
  13.  */  
  14. public class SDCardUtils  
  15. {  
  16.     private SDCardUtils()  
  17.     {  
  18.         /* cannot be instantiated */  
  19.         throw new UnsupportedOperationException("cannot be instantiated");  
  20.     }  
  21.   
  22.     /** 
  23.      * Determine if SDCard is available 
  24.      *  
  25.      * @return 
  26.      */  
  27.     public static boolean isSDCardEnable()  
  28.     {  
  29.         return Environment.getExternalStorageState().equals(  
  30.                 Environment.MEDIA_MOUNTED);  
  31.   
  32.     }  
  33.   
  34.     /** 
  35.      * Get SD card path 
  36.      *  
  37.      * @return 
  38.      */  
  39.     public static String getSDCardPath()  
  40.     {  
  41.         return Environment.getExternalStorageDirectory().getAbsolutePath()  
  42.                 + File.separator;  
  43.     }  
  44.   
  45.     /** 
  46.      * Get the remaining capacity of the SD card in byte 
  47.      *  
  48.      * @return 
  49.      */  
  50.     public static long getSDCardAllSize()  
  51.     {  
  52.         if (isSDCardEnable())  
  53.         {  
  54.             StatFs stat = new StatFs(getSDCardPath());  
  55.             //Get the number of free data blocks  
  56.             long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
  57.             //Get the size of a single data block (byte)  
  58.             long freeBlocks = stat.getAvailableBlocks();  
  59.             return freeBlocks * availableBlocks;  
  60.         }  
  61.         return 0;  
  62.     }  
  63.   
  64.     /** 
  65.      * Gets the number of bytes of remaining available capacity in the space of the specified path, in byte 
  66.      *  
  67.      * @param filePath 
  68.      * @return Capacity bytes SDCard free space, internal storage free space 
  69.      */  
  70.     public static long getFreeBytes(String filePath)  
  71.     {  
  72.         //Get the available capacity of the sd card if it is the path below the sd card  
  73.         if (filePath.startsWith(getSDCardPath()))  
  74.         {  
  75.             filePath = getSDCardPath();  
  76.         } else  
  77.         {//Get the available capacity of memory storage if it is an internal storage path  
  78.             filePath = Environment.getDataDirectory().getAbsolutePath();  
  79.         }  
  80.         StatFs stat = new StatFs(filePath);  
  81.         long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
  82.         return stat.getBlockSize() * availableBlocks;  
  83.     }  
  84.   
  85.     /** 
  86.      * Get System Storage Path 
  87.      *  
  88.      * @return 
  89.      */  
  90.     public static String getRootDirectoryPath()  
  91.     {  
  92.         return Environment.getRootDirectory().getAbsolutePath();  
  93.     }  
  94.   
  95.   
  96. }  

6. ScreenUtils ScreenUtils

  1. package com.zhy.utils;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.graphics.Bitmap;  
  6. import android.graphics.Rect;  
  7. import android.util.DisplayMetrics;  
  8. import android.view.View;  
  9. import android.view.WindowManager;  
  10.   
  11. /** 
  12.  * Get screen-related ancillary classes 
  13.  *  
  14.  *  
  15.  *  
  16.  */  
  17. public class ScreenUtils  
  18. {  
  19.     private ScreenUtils()  
  20.     {  
  21.         /* cannot be instantiated */  
  22.         throw new UnsupportedOperationException("cannot be instantiated");  
  23.     }  
  24.   
  25.     /** 
  26.      * Get screen height 
  27.      *  
  28.      * @param context 
  29.      * @return 
  30.      */  
  31.     public static int getScreenWidth(Context context)  
  32.     {  
  33.         WindowManager wm = (WindowManager) context  
  34.                 .getSystemService(Context.WINDOW_SERVICE);  
  35.         DisplayMetrics outMetrics = new DisplayMetrics();  
  36.         wm.getDefaultDisplay().getMetrics(outMetrics);  
  37.         return outMetrics.widthPixels;  
  38.     }  
  39.   
  40.     /** 
  41.      * Get screen width 
  42.      *  
  43.      * @param context 
  44.      * @return 
  45.      */  
  46.     public static int getScreenHeight(Context context)  
  47.     {  
  48.         WindowManager wm = (WindowManager) context  
  49.                 .getSystemService(Context.WINDOW_SERVICE);  
  50.         DisplayMetrics outMetrics = new DisplayMetrics();  
  51.         wm.getDefaultDisplay().getMetrics(outMetrics);  
  52.         return outMetrics.heightPixels;  
  53.     }  
  54.   
  55.     /** 
  56.      * Get the height of the status bar 
  57.      *  
  58.      * @param context 
  59.      * @return 
  60.      */  
  61.     public static int getStatusHeight(Context context)  
  62.     {  
  63.   
  64.         int statusHeight = -1;  
  65.         try  
  66.         {  
  67.             Class<?> clazz = Class.forName("com.android.internal.R$dimen");  
  68.             Object object = clazz.newInstance();  
  69.             int height = Integer.parseInt(clazz.getField("status_bar_height")  
  70.                     .get(object).toString());  
  71.             statusHeight = context.getResources().getDimensionPixelSize(height);  
  72.         } catch (Exception e)  
  73.         {  
  74.             e.printStackTrace();  
  75.         }  
  76.         return statusHeight;  
  77.     }  
  78.   
  79.     /** 
  80.      * Get the current screen capture, including the status bar 
  81.      *  
  82.      * @param activity 
  83.      * @return 
  84.      */  
  85.     public static Bitmap snapShotWithStatusBar(Activity activity)  
  86.     {  
  87.         View view = activity.getWindow().getDecorView();  
  88.         view.setDrawingCacheEnabled(true);  
  89.         view.buildDrawingCache();  
  90.         Bitmap bmp = view.getDrawingCache();  
  91.         int width = getScreenWidth(activity);  
  92.         int height = getScreenHeight(activity);  
  93.         Bitmap bp = null;  
  94.         bp = Bitmap.createBitmap(bmp, 00, width, height);  
  95.         view.destroyDrawingCache();  
  96.         return bp;  
  97.   
  98.     }  
  99.   
  100.     /** 
  101.      * Get the current screen capture without a status bar 
  102.      *  
  103.      * @param activity 
  104.      * @return 
  105.      */  
  106.     public static Bitmap snapShotWithoutStatusBar(Activity activity)  
  107.     {  
  108.         View view = activity.getWindow().getDecorView();  
  109.         view.setDrawingCacheEnabled(true);  
  110.         view.buildDrawingCache();  
  111.         Bitmap bmp = view.getDrawingCache();  
  112.         Rect frame = new Rect();  
  113.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);  
  114.         int statusBarHeight = frame.top;  
  115.   
  116.         int width = getScreenWidth(activity);  
  117.         int height = getScreenHeight(activity);  
  118.         Bitmap bp = null;  
  119.         bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height  
  120.                 - statusBarHeight);  
  121.         view.destroyDrawingCache();  
  122.         return bp;  
  123.   
  124.     }  
  125.   
  126. }  

7. App-related auxiliary classes

  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.content.pm.PackageInfo;  
  5. import android.content.pm.PackageManager;  
  6. import android.content.pm.PackageManager.NameNotFoundException;  
  7.   
  8. /** 
  9.  * App-related auxiliary classes 
  10.  *  
  11.  *  
  12.  *  
  13.  */  
  14. public class AppUtils  
  15. {  
  16.   
  17.     private AppUtils()  
  18.     {  
  19.         /* cannot be instantiated */  
  20.         throw new UnsupportedOperationException("cannot be instantiated");  
  21.   
  22.     }  
  23.   
  24.     /** 
  25.      * Get the application name 
  26.      */  
  27.     public static String getAppName(Context context)  
  28.     {  
  29.         try  
  30.         {  
  31.             PackageManager packageManager = context.getPackageManager();  
  32.             PackageInfo packageInfo = packageManager.getPackageInfo(  
  33.                     context.getPackageName(), 0);  
  34.             int labelRes = packageInfo.applicationInfo.labelRes;  
  35.             return context.getResources().getString(labelRes);  
  36.         } catch (NameNotFoundException e)  
  37.         {  
  38.             e.printStackTrace();  
  39.         }  
  40.         return null;  
  41.     }  
  42.   
  43.     /** 
  44.      * [Get application version name information] 
  45.      *  
  46.      * @param context 
  47.      * @return Currently applied version name 
  48.      */  
  49.     public static String getVersionName(Context context)  
  50.     {  
  51.         try  
  52.         {  
  53.             PackageManager packageManager = context.getPackageManager();  
  54.             PackageInfo packageInfo = packageManager.getPackageInfo(  
  55.                     context.getPackageName(), 0);  
  56.             return packageInfo.versionName;  
  57.   
  58.         } catch (NameNotFoundException e)  
  59.         {  
  60.             e.printStackTrace();  
  61.         }  
  62.         return null;  
  63.     }  
  64.   
  65. }  

8. Softkeyboard-related auxiliary class KeyBoardUtils

  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.view.inputmethod.InputMethodManager;  
  5. import android.widget.EditText;  
  6.   
  7. /** 
  8.  * Turn on or off the soft keyboard 
  9.  *  
  10.  * @author zhy 
  11.  *  
  12.  */  
  13. public class KeyBoardUtils  
  14. {  
  15.     /** 
  16.      * Soft keyboard for clock-in 
  17.      *  
  18.      * @param mEditText 
  19.      *            Input Box 
  20.      * @param mContext 
  21.      *            context 
  22.      */  
  23.     public static void openKeybord(EditText mEditText, Context mContext)  
  24.     {  
  25.         InputMethodManager imm = (InputMethodManager) mContext  
  26.                 .getSystemService(Context.INPUT_METHOD_SERVICE);  
  27.         imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);  
  28.         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,  
  29.                 InputMethodManager.HIDE_IMPLICIT_ONLY);  
  30.     }  
  31.   
  32.     /** 
  33.      * Turn off the soft keyboard 
  34.      *  
  35.      * @param mEditText 
  36.      *            Input Box 
  37.      * @param mContext 
  38.      *            context 
  39.      */  
  40.     public static void closeKeybord(EditText mEditText, Context mContext)  
  41.     {  
  42.         InputMethodManager imm = (InputMethodManager) mContext  
  43.                 .getSystemService(Context.INPUT_METHOD_SERVICE);  
  44.   
  45.         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);  
  46.     }  
  47. }  

9. Network-related auxiliary class NetUtils

  1. package com.zhy.utils;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.net.ConnectivityManager;  
  8. import android.net.NetworkInfo;  
  9.   
  10. /** 
  11.  * Network-related Tool Classes 
  12.  *  
  13.  *  
  14.  *  
  15.  */  
  16. public class NetUtils  
  17. {  
  18.     private NetUtils()  
  19.     {  
  20.         /* cannot be instantiated */  
  21.         throw new UnsupportedOperationException("cannot be instantiated");  
  22.     }  
  23.   
  24.     /** 
  25.      * Determine whether the network is connected 
  26.      *  
  27.      * @param context 
  28.      * @return 
  29.      */  
  30.     public static boolean isConnected(Context context)  
  31.     {  
  32.   
  33.         ConnectivityManager connectivity = (ConnectivityManager) context  
  34.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  35.   
  36.         if (null != connectivity)  
  37.         {  
  38.   
  39.             NetworkInfo info = connectivity.getActiveNetworkInfo();  
  40.             if (null != info && info.isConnected())  
  41.             {  
  42.                 if (info.getState() == NetworkInfo.State.CONNECTED)  
  43.                 {  
  44.                     return true;  
  45.                 }  
  46.             }  
  47.         }  
  48.         return false;  
  49.     }  
  50.   
  51.     /** 
  52.      * Determine if it is a wifi connection 
  53.      */  
  54.     public static boolean isWifi(Context context)  
  55.     {  
  56.         ConnectivityManager cm = (ConnectivityManager) context  
  57.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  58.   
  59.         if (cm == null)  
  60.             return false;  
  61.         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;  
  62.   
  63.     }  
  64.   
  65.     /** 
  66.      * Open Network Setup Interface 
  67.      */  
  68.     public static void openSetting(Activity activity)  
  69.     {  
  70.         Intent intent = new Intent("/");  
  71.         ComponentName cm = new ComponentName("com.android.settings",  
  72.                 "com.android.settings.WirelessSettings");  
  73.         intent.setComponent(cm);  
  74.         intent.setAction("android.intent.action.VIEW");  
  75.         activity.startActivityForResult(intent, 0);  
  76.     }  
  77.   
  78. }  


10. Http-related auxiliary class HttpUtils

[java] view plain copy
 
  1. package com.zhy.utils;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.PrintWriter;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11.   
  12. /** 
  13. * Tool class for Http requests
  14.  *  
  15.  * @author zhy 
  16.  *  
  17.  */  
  18. public class HttpUtils  
  19. {  
  20.   
  21.     private static final int TIMEOUT_IN_MILLIONS = 5000;  
  22.   
  23.     public interface CallBack  
  24.     {  
  25.         void onRequestComplete(String result);  
  26.     }  
  27.   
  28.   
  29.     /** 
  30. * Asynchronous Get Requests
  31.      *  
  32.      * @param urlStr 
  33.      * @param callBack 
  34.      */  
  35.     public static void doGetAsyn(final String urlStr, final CallBack callBack)  
  36.     {  
  37.         new Thread()  
  38.         {  
  39.             public void run()  
  40.             {  
  41.                 try  
  42.                 {  
  43.                     String result = doGet(urlStr);  
  44.                     if (callBack != null)  
  45.                     {  
  46.                         callBack.onRequestComplete(result);  
  47.                     }  
  48.                 } catch (Exception e)  
  49.                 {  
  50.                     e.printStackTrace();  
  51.                 }  
  52.   
  53.             };  
  54.         }.start();  
  55.     }  
  56.   
  57.     /** 
  58. * Asynchronous Post Request
  59.      * @param urlStr 
  60.      * @param params 
  61.      * @param callBack 
  62.      * @throws Exception 
  63.      */  
  64.     public static void doPostAsyn(final String urlStr, final String params,  
  65.             final CallBack callBack) throws Exception  
  66.     {  
  67.         new Thread()  
  68.         {  
  69.             public void run()  
  70.             {  
  71.                 try  
  72.                 {  
  73.                     String result = doPost(urlStr, params);  
  74.                     if (callBack != null)  
  75.                     {  
  76.                         callBack.onRequestComplete(result);  
  77.                     }  
  78.                 } catch (Exception e)  
  79.                 {  
  80.                     e.printStackTrace();  
  81.                 }  
  82.   
  83.             };  
  84.         }.start();  
  85.   
  86.     }  
  87.   
  88.     /** 
  89. * Get request, get return data
  90.      *  
  91.      * @param urlStr 
  92.      * @return 
  93.      * @throws Exception 
  94.      */  
  95.     public static String doGet(String urlStr)   
  96.     {  
  97.         URL url = null;  
  98.         HttpURLConnection conn = null;  
  99.         InputStream is = null;  
  100.         ByteArrayOutputStream baos = null;  
  101.         try  
  102.         {  
  103.             url = new URL(urlStr);  
  104.             conn = (HttpURLConnection) url.openConnection();  
  105.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
  106.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
  107.             conn.setRequestMethod("GET");  
  108.             conn.setRequestProperty("accept", "*/*");  
  109.             conn.setRequestProperty("connection", "Keep-Alive");  
  110.             if (conn.getResponseCode() == 200)  
  111.             {  
  112.                 is = conn.getInputStream();  
  113.                 baos = new ByteArrayOutputStream();  
  114.                 int len = -1;  
  115.                 byte[] buf = new byte[128];  
  116.   
  117.                 while ((len = is.read(buf)) != -1)  
  118.                 {  
  119.                     baos.write(buf, 0, len);  
  120.                 }  
  121.                 baos.flush();  
  122.                 return baos.toString();  
  123.             } else  
  124.             {  
  125.                 throw new RuntimeException(" responseCode is not 200 ... ");  
  126.             }  
  127.   
  128.         } catch (Exception e)  
  129.         {  
  130.             e.printStackTrace();  
  131.         } finally  
  132.         {  
  133.             try  
  134.             {  
  135.                 if (is != null)  
  136.                     is.close();  
  137.             } catch (IOException e)  
  138.             {  
  139.             }  
  140.             try  
  141.             {  
  142.                 if (baos != null)  
  143.                     baos.close();  
  144.             } catch (IOException e)  
  145.             {  
  146.             }  
  147.             conn.disconnect();  
  148.         }  
  149.           
  150.         return null ;  
  151.   
  152.     }  
  153.   
  154.     /**  
  155. * Send POST method request to specified URL
  156.      *   
  157.      * @param url  
  158. * URL to send the request
  159.      * @param param  
  160. Request parameters, which should be in the form of name1=value1&name2=value2.*
  161. Response results of remote resources represented by * @return
  162.      * @throws Exception  
  163.      */  
  164.     public static String doPost(String url, String param)   
  165.     {  
  166.         PrintWriter out = null;  
  167.         BufferedReader in = null;  
  168.         String result = "";  
  169.         try  
  170.         {  
  171.             URL realUrl = new URL(url);  
  172. // Open the connection to the URL
  173.             HttpURLConnection conn = (HttpURLConnection) realUrl  
  174.                     .openConnection();  
  175. // Set Common Request Properties
  176.             conn.setRequestProperty("accept", "*/*");  
  177.             conn.setRequestProperty("connection", "Keep-Alive");  
  178.             conn.setRequestMethod("POST");  
  179.             conn.setRequestProperty("Content-Type",  
  180.                     "application/x-www-form-urlencoded");  
  181.             conn.setRequestProperty("charset", "utf-8");  
  182.             conn.setUseCaches(false);  
  183. The following two lines are required for // sending POST requests
  184.             conn.setDoOutput(true);  
  185.             conn.setDoInput(true);  
  186.             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);  
  187.             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);  
  188.   
  189.             if (param != null && !param.trim().equals(""))  
  190.             {  
  191. // Get the output stream corresponding to the URLConnection object
  192.                 out = new PrintWriter(conn.getOutputStream());  
  193. * Send Request Parameters //
  194.                 out.print(param);  
  195. Buffering of // flush output stream
  196.                 out.flush();  
  197.             }  
  198. // Define the BufferedReader input stream to read the response of the URL
  199.             in = new BufferedReader(  
  200.                     new InputStreamReader(conn.getInputStream()));  
  201.             String line;  
  202.             while ((line = in.readLine()) != null)  
  203.             {  
  204.                 result += line;  
  205.             }  
  206.         } catch (Exception e)  
  207.         {  
  208.             e.printStackTrace();  
  209.         }  
  210. // Use finally blocks to close output and input streams
  211.         finally  
  212.         {  
  213.             try  
  214.             {  
  215.                 if (out != null)  
  216.                 {  
  217.                     out.close();  
  218.                 }  
  219.                 if (in != null)  
  220.                 {  
  221.                     in.close();  
  222.                 }  
  223.             } catch (IOException ex)  
  224.             {  
  225.                 ex.printStackTrace();  
  226.             }  
  227.         }  
  228.         return result;  
  229.     }  
  230. }  


Reprinted from: http://blog.csdn.net/lmj623565791/article/details/38965311

Reproduction purpose: record

Keywords: Android Java network

Added by tibo on Sun, 07 Jul 2019 22:29:03 +0300