• 安卓中常用的工具类集合


    1.一个double类型数据精准四则运算类Arith.Java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. import java.math.BigDecimal;  
    2.   
    3. public class Arith{  
    4.     //默认除法运算精度  
    5.     private static final int DEF_DIV_SCALE = 10;  
    6.     //这个类不能实例化  
    7.     private Arith(){  
    8.           
    9.     }  
    10.    
    11.     /** 
    12.      * 提供精确的加法运算。 
    13.      * @param v1 被加数 
    14.      * @param v2 加数 
    15.      * @return 两个参数的和 
    16.      */  
    17.     public static double add(double v1,double v2){  
    18.         BigDecimal b1 = new BigDecimal(Double.toString(v1));  
    19.         BigDecimal b2 = new BigDecimal(Double.toString(v2));  
    20.         return b1.add(b2).doubleValue();  
    21.     }  
    22.     /** 
    23.      * 提供精确的减法运算。 
    24.      * @param v1 被减数 
    25.      * @param v2 减数 
    26.      * @return 两个参数的差 
    27.      */  
    28.     public static double sub(double v1,double v2){  
    29.         BigDecimal b1 = new BigDecimal(Double.toString(v1));  
    30.         BigDecimal b2 = new BigDecimal(Double.toString(v2));  
    31.         return b1.subtract(b2).doubleValue();  
    32.     }   
    33.     /** 
    34.      * 提供精确的乘法运算。 
    35.      * @param v1 被乘数 
    36.      * @param v2 乘数 
    37.      * @return 两个参数的积 
    38.      */  
    39.     public static double mul(double v1,double v2){  
    40.         BigDecimal b1 = new BigDecimal(Double.toString(v1));  
    41.         BigDecimal b2 = new BigDecimal(Double.toString(v2));  
    42.         return b1.multiply(b2).doubleValue();  
    43.     }  
    44.    
    45.     /** 
    46.      * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 
    47.      * 小数点以后10位,以后的数字四舍五入。 
    48.      * @param v1 被除数 
    49.      * @param v2 除数 
    50.      * @return 两个参数的商 
    51.      */  
    52.     public static double div(double v1,double v2){  
    53.         return div(v1,v2,DEF_DIV_SCALE);  
    54.     }  
    55.    
    56.     /** 
    57.      * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 
    58.      * 定精度,以后的数字四舍五入。 
    59.      * @param v1 被除数 
    60.      * @param v2 除数 
    61.      * @param scale 表示表示需要精确到小数点以后几位。 
    62.      * @return 两个参数的商 
    63.      */  
    64.     public static double div(double v1,double v2,int scale){  
    65.         if(scale<0){  
    66.             throw new IllegalArgumentException(  
    67.                 "The scale must be a positive integer or zero");  
    68.         }  
    69.         BigDecimal b1 = new BigDecimal(Double.toString(v1));  
    70.         BigDecimal b2 = new BigDecimal(Double.toString(v2));  
    71.         return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();  
    72.     }  
    73.    
    74.     /** 
    75.      * 提供精确的小数位四舍五入处理。 
    76.      * @param v 需要四舍五入的数字 
    77.      * @param scale 小数点后保留几位 
    78.      * @return 四舍五入后的结果 
    79.      */  
    80.     public static double round(double v,int scale){  
    81.         if(scale<0){  
    82.             throw new IllegalArgumentException(  
    83.                 "The scale must be a positive integer or zero");  
    84.         }  
    85.         BigDecimal b = new BigDecimal(Double.toString(v));  
    86.         BigDecimal one = new BigDecimal("1");  
    87.         return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();  
    88.     }  
    89.       
    90. }  

    2.PrefUtils.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. import android.content.Context;  
    2. import android.content.SharedPreferences;  
    3.   
    4. public class PrefUtils {  
    5.   
    6.     public static boolean getBoolean(Context context,String key,boolean defalt){  
    7.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    8.         Boolean b=sp.getBoolean(key, defalt);  
    9.         return b;  
    10.     }  
    11.       
    12.     public  static void  setBoolean(Context context,String key,Boolean value) {  
    13.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    14.         sp.edit().putBoolean(key, value).commit();  
    15.     }  
    16.       
    17.     public static String getString(Context context,String key,String defalt){  
    18.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    19.         String s=sp.getString(key, defalt);  
    20.         return s;  
    21.     }  
    22.       
    23.     public static void SetString(Context context,String key,String value){  
    24.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    25.         sp.edit().putString(key, value).commit();  
    26.           
    27.     }  
    28.       
    29.     public static int getInt(Context context,String key,int defalt){  
    30.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    31.         int l=sp.getInt(key, defalt);  
    32.         return l;  
    33.     }  
    34.       
    35.     public static void SetInt(Context context,String key,int value){  
    36.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    37.         sp.edit().putInt(key, value).commit();  
    38.           
    39.     }  
    40.     public static long getLong(Context context,String key,long defalt){  
    41.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    42.         long l=sp.getLong(key, defalt);  
    43.         return l;  
    44.     }  
    45.       
    46.     public static void SetLong(Context context,String key,long value){  
    47.         SharedPreferences sp=context.getSharedPreferences("config",Context.MODE_PRIVATE);  
    48.         sp.edit().putLong(key, value).commit();  
    49.           
    50.     }  
    51. }  

    3.log日志打印L.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class L    
    2. {    
    3.     
    4.     private L()    
    5.     {    
    6.         /* cannot be instantiated */    
    7.         throw new UnsupportedOperationException("cannot be instantiated");    
    8.     }    
    9.     
    10.     public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化    
    11.     private static final String TAG = "way";    
    12.     
    13.     // 下面四个是默认tag的函数    
    14.     public static void i(String msg)    
    15.     {    
    16.         if (isDebug)    
    17.             Log.i(TAG, msg);    
    18.     }    
    19.     
    20.     public static void d(String msg)    
    21.     {    
    22.         if (isDebug)    
    23.             Log.d(TAG, msg);    
    24.     }    
    25.     
    26.     public static void e(String msg)    
    27.     {    
    28.         if (isDebug)    
    29.             Log.e(TAG, msg);    
    30.     }    
    31.     
    32.     public static void v(String msg)    
    33.     {    
    34.         if (isDebug)    
    35.             Log.v(TAG, msg);    
    36.     }    
    37.     
    38.     // 下面是传入自定义tag的函数    
    39.     public static void i(String tag, String msg)    
    40.     {    
    41.         if (isDebug)    
    42.             Log.i(tag, msg);    
    43.     }    
    44.     
    45.     public static void d(String tag, String msg)    
    46.     {    
    47.         if (isDebug)    
    48.             Log.i(tag, msg);    
    49.     }    
    50.     
    51.     public static void e(String tag, String msg)    
    52.     {    
    53.         if (isDebug)    
    54.             Log.i(tag, msg);    
    55.     }    
    56.     
    57.     public static void v(String tag, String msg)    
    58.     {    
    59.         if (isDebug)    
    60.             Log.i(tag, msg);    
    61.     }    
    62. }  

    4.单位转换的工具类DensityUtils

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class DensityUtils    
    2. {    
    3.     private DensityUtils()    
    4.     {    
    5.         /* cannot be instantiated */    
    6.         throw new UnsupportedOperationException("cannot be instantiated");    
    7.     }    
    8.     
    9.     /**  
    10.      * dp转px  
    11.      *   
    12.      * @param context  
    13.      * @param val  
    14.      * @return  
    15.      */    
    16.     public static int dp2px(Context context, float dpVal)    
    17.     {    
    18.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,    
    19.                 dpVal, context.getResources().getDisplayMetrics());    
    20.     }    
    21.     
    22.     /**  
    23.      * sp转px  
    24.      *   
    25.      * @param context  
    26.      * @param val  
    27.      * @return  
    28.      */    
    29.     public static int sp2px(Context context, float spVal)    
    30.     {    
    31.         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,    
    32.                 spVal, context.getResources().getDisplayMetrics());    
    33.     }    
    34.     
    35.     /**  
    36.      * px转dp  
    37.      *   
    38.      * @param context  
    39.      * @param pxVal  
    40.      * @return  
    41.      */    
    42.     public static float px2dp(Context context, float pxVal)    
    43.     {    
    44.         final float scale = context.getResources().getDisplayMetrics().density;    
    45.         return (pxVal / scale);    
    46.     }    
    47.     
    48.     /**  
    49.      * px转sp  
    50.      *   
    51.      * @param fontScale  
    52.      * @param pxVal  
    53.      * @return  
    54.      */    
    55.     public static float px2sp(Context context, float pxVal)    
    56.     {    
    57.         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);    
    58.     }    
    59.     
    60. }    

    5.屏幕读取类ScreenUtils

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class ScreenUtils    
    2. {    
    3.     private ScreenUtils()    
    4.     {    
    5.         /* cannot be instantiated */    
    6.         throw new UnsupportedOperationException("cannot be instantiated");    
    7.     }    
    8.     
    9.     /**  
    10.      * 获得屏幕高度  
    11.      *   
    12.      * @param context  
    13.      * @return  
    14.      */    
    15.     public static int getScreenWidth(Context context)    
    16.     {    
    17.         WindowManager wm = (WindowManager) context    
    18.                 .getSystemService(Context.WINDOW_SERVICE);    
    19.         DisplayMetrics outMetrics = new DisplayMetrics();    
    20.         wm.getDefaultDisplay().getMetrics(outMetrics);    
    21.         return outMetrics.widthPixels;    
    22.     }    
    23.     
    24.     /**  
    25.      * 获得屏幕宽度  
    26.      *   
    27.      * @param context  
    28.      * @return  
    29.      */    
    30.     public static int getScreenHeight(Context context)    
    31.     {    
    32.         WindowManager wm = (WindowManager) context    
    33.                 .getSystemService(Context.WINDOW_SERVICE);    
    34.         DisplayMetrics outMetrics = new DisplayMetrics();    
    35.         wm.getDefaultDisplay().getMetrics(outMetrics);    
    36.         return outMetrics.heightPixels;    
    37.     }    
    38.     
    39.     /**  
    40.      * 获得状态栏的高度  
    41.      *   
    42.      * @param context  
    43.      * @return  
    44.      */    
    45.     public static int getStatusHeight(Context context)    
    46.     {    
    47.     
    48.         int statusHeight = -1;    
    49.         try    
    50.         {    
    51.             Class<?> clazz = Class.forName("com.android.internal.R$dimen");    
    52.             Object object = clazz.newInstance();    
    53.             int height = Integer.parseInt(clazz.getField("status_bar_height")    
    54.                     .get(object).toString());    
    55.             statusHeight = context.getResources().getDimensionPixelSize(height);    
    56.         } catch (Exception e)    
    57.         {    
    58.             e.printStackTrace();    
    59.         }    
    60.         return statusHeight;    
    61.     }    
    62.     
    63.     /**  
    64.      * 获取当前屏幕截图,包含状态栏  
    65.      *   
    66.      * @param activity  
    67.      * @return  
    68.      */    
    69.     public static Bitmap snapShotWithStatusBar(Activity activity)    
    70.     {    
    71.         View view = activity.getWindow().getDecorView();    
    72.         view.setDrawingCacheEnabled(true);    
    73.         view.buildDrawingCache();    
    74.         Bitmap bmp = view.getDrawingCache();    
    75.         int width = getScreenWidth(activity);    
    76.         int height = getScreenHeight(activity);    
    77.         Bitmap bp = null;    
    78.         bp = Bitmap.createBitmap(bmp, 0, 0, width, height);    
    79.         view.destroyDrawingCache();    
    80.         return bp;    
    81.     
    82.     }    
    83.     
    84.     /**  
    85.      * 获取当前屏幕截图,不包含状态栏  
    86.      *   
    87.      * @param activity  
    88.      * @return  
    89.      */    
    90.     public static Bitmap snapShotWithoutStatusBar(Activity activity)    
    91.     {    
    92.         View view = activity.getWindow().getDecorView();    
    93.         view.setDrawingCacheEnabled(true);    
    94.         view.buildDrawingCache();    
    95.         Bitmap bmp = view.getDrawingCache();    
    96.         Rect frame = new Rect();    
    97.         activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);    
    98.         int statusBarHeight = frame.top;    
    99.     
    100.         int width = getScreenWidth(activity);    
    101.         int height = getScreenHeight(activity);    
    102.         Bitmap bp = null;    
    103.         bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height    
    104.                 - statusBarHeight);    
    105.         view.destroyDrawingCache();    
    106.         return bp;    
    107.     
    108.     }    
    109.     
    110. }    

    6.文件操作类FileUtil.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class FileUtil {  
    2.     private static FileUtil util;  
    3.   
    4.     public static FileUtil init() { // 单例,个人习惯用Init,标准是getInstance  
    5.         if (util == null)  
    6.             util = new FileUtil();  
    7.         return util;  
    8.     }  
    9.   
    10.     private FileUtil() {  
    11.   
    12.     }  
    13.       
    14.     private Context context = null;  
    15.     public void setContext(Context c){  
    16.         this.context = c;  
    17.     }  
    18.     public Context getContext(){  
    19.         return context;  
    20.     }  
    21.   
    22.     /** 
    23.      *  
    24.      * @param path传入路径字符串 
    25.      * @return File 
    26.      */  
    27.     public File creatFileIfNotExist(String path) {  
    28.         System.out.println("cr");  
    29.         File file = new File(path);  
    30.         if (!file.exists()) {  
    31.             try {  
    32.                 new File(path.substring(0, path.lastIndexOf(File.separator)))  
    33.                         .mkdirs();  
    34.                 file.createNewFile();  
    35.   
    36.             } catch (IOException e) {  
    37.                 e.printStackTrace();  
    38.   
    39.             }  
    40.         }  
    41.         return file;  
    42.     }  
    43.   
    44.     /** 
    45.      *  
    46.      * @param path传入路径字符串 
    47.      * @return File 
    48.      */  
    49.     public File creatDirIfNotExist(String path) {  
    50.         File file = new File(path);  
    51.         if (!file.exists()) {  
    52.             try {  
    53.                 file.mkdirs();  
    54.   
    55.             } catch (Exception e) {  
    56.                 e.printStackTrace();  
    57.   
    58.             }  
    59.         }  
    60.         return file;  
    61.     }  
    62.   
    63.     /** 
    64.      *  
    65.      * @param path 
    66.      * @return 
    67.      */  
    68.     public boolean IsExist(String path) {  
    69.         File file = new File(path);  
    70.         if (!file.exists())  
    71.             return false;  
    72.         else  
    73.             return true;  
    74.     }  
    75.   
    76.     /** 
    77.      * 创建新的文件,如果有旧文件,先删除再创建 
    78.      *  
    79.      * @param path 
    80.      * @return 
    81.      */  
    82.     public File creatNewFile(String path) {  
    83.         File file = new File(path);  
    84.         if (IsExist(path))  
    85.             file.delete();  
    86.         creatFileIfNotExist(path);  
    87.         return file;  
    88.     }  
    89.   
    90.     /** 
    91.      * 删除文件 
    92.      *  
    93.      * @param path 
    94.      * @return 
    95.      */  
    96.     public boolean deleteFile(String path) {  
    97.         File file = new File(path);  
    98.         if (IsExist(path))  
    99.             file.delete();  
    100.         return true;  
    101.     }  
    102.   
    103.     // 删除一个目录  
    104.     public boolean deleteFileDir(String path) {  
    105.         boolean flag = false;  
    106.         File file = new File(path);  
    107.         if (!IsExist(path)) {  
    108.             return flag;  
    109.         }  
    110.         if (!file.isDirectory()) {  
    111.   
    112.             file.delete();  
    113.             return true;  
    114.         }  
    115.         String[] filelist = file.list();  
    116.         File temp = null;  
    117.         for (int i = 0; i < filelist.length; i++) {  
    118.             if (path.endsWith(File.separator)) {  
    119.                 temp = new File(path + filelist[i]);  
    120.             } else {  
    121.                 temp = new File(path + File.separator + filelist[i]);  
    122.             }  
    123.             if (temp.isFile()) {  
    124.   
    125.                 temp.delete();  
    126.             }  
    127.             if (temp.isDirectory()) {  
    128.                 deleteFileDir(path + "/" + filelist[i]);// 先删除文件夹里面的文件  
    129.             }  
    130.         }  
    131.         file.delete();  
    132.   
    133.         flag = true;  
    134.         return flag;  
    135.     }  
    136.   
    137.     // 删除文件夹  
    138.     // param folderPath 文件夹完整绝对路径  
    139.   
    140.     public void delFolder(String folderPath) {  
    141.         try {  
    142.             delAllFile(folderPath); // 删除完里面所有内容  
    143.             String filePath = folderPath;  
    144.             filePath = filePath.toString();  
    145.             java.io.File myFilePath = new java.io.File(filePath);  
    146.             myFilePath.delete(); // 删除空文件夹  
    147.         } catch (Exception e) {  
    148.             e.printStackTrace();  
    149.         }  
    150.     }  
    151.   
    152.     // 删除指定文件夹下所有文件  
    153.     // param path 文件夹完整绝对路径  
    154.     public boolean delAllFile(String path) {  
    155.         boolean flag = false;  
    156.         File file = new File(path);  
    157.         if (!file.exists()) {  
    158.             return flag;  
    159.         }  
    160.         if (!file.isDirectory()) {  
    161.             return flag;  
    162.         }  
    163.         String[] tempList = file.list();  
    164.         File temp = null;  
    165.         for (int i = 0; i < tempList.length; i++) {  
    166.             if (path.endsWith(File.separator)) {  
    167.                 temp = new File(path + tempList[i]);  
    168.             } else {  
    169.                 temp = new File(path + File.separator + tempList[i]);  
    170.             }  
    171.             if (temp.isFile()) {  
    172.                 temp.delete();  
    173.             }  
    174.             if (temp.isDirectory()) {  
    175.                 delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件  
    176.                 delFolder(path + "/" + tempList[i]);// 再删除空文件夹  
    177.                 flag = true;  
    178.             }  
    179.         }  
    180.         return flag;  
    181.     }  
    182.   
    183.     public String[] getFlieName(String rootpath) {  
    184.         File root = new File(rootpath);  
    185.         File[] filesOrDirs = root.listFiles();  
    186.         if (filesOrDirs != null) {  
    187.             String[] dir = new String[filesOrDirs.length];  
    188.             int num = 0;  
    189.             for (int i = 0; i < filesOrDirs.length; i++) {  
    190.                 if (filesOrDirs[i].isDirectory()) {  
    191.                     dir[i] = filesOrDirs[i].getName();  
    192.   
    193.                     num++;  
    194.                 }  
    195.             }  
    196.             String[] dir_r = new String[num];  
    197.             num = 0;  
    198.             for (int i = 0; i < dir.length; i++) {  
    199.                 if (dir[i] != null && !dir[i].equals("")) {  
    200.                     dir_r[num] = dir[i];  
    201.                     num++;  
    202.                 }  
    203.             }  
    204.             return dir_r;  
    205.         } else  
    206.             return null;  
    207.     }  
    208.   
    209.     /** 
    210.      * //获得流 
    211.      *  
    212.      * @param path 
    213.      * @return 
    214.      * @throws FileNotFoundException 
    215.      * @throws UnsupportedEncodingException 
    216.      */  
    217.     public BufferedWriter getWriter(String path) throws FileNotFoundException,  
    218.             UnsupportedEncodingException {  
    219.         FileOutputStream fileout = null;  
    220.         fileout = new FileOutputStream(new File(path));  
    221.         OutputStreamWriter writer = null;  
    222.         writer = new OutputStreamWriter(fileout, "UTF-8");  
    223.         BufferedWriter w = new BufferedWriter(writer); // 缓冲区  
    224.         return w;  
    225.     }  
    226.   
    227.     public InputStream getInputStream(String path) throws FileNotFoundException {  
    228.         // if(Comments.DEBUG) System.out.println("path:"+path);  
    229.         FileInputStream filein = null;  
    230.         // if(Comments.DEBUG) System.out.println("2");  
    231.         // File file = creatFileIfNotExist(path);  
    232.         File file = new File(path);  
    233.         filein = new FileInputStream(file);  
    234.         BufferedInputStream in = null;  
    235.         if (filein != null)  
    236.             in = new BufferedInputStream(filein);  
    237.         return in;  
    238.     }  
    239.   
    240.     public boolean StateXmlControl(String path) {  
    241.         File f = new File(path);  
    242.         if (!f.exists())  
    243.             return false;  
    244.         if (f.length() == 0)  
    245.             return false;  
    246.         return true;  
    247.     }  
    248.   
    249.     /** 
    250.      * 将InputStream转换成byte数组 
    251.      *  
    252.      * @param in 
    253.      *            InputStream 
    254.      * @return byte[] 
    255.      * @throws IOException 
    256.      */  
    257.     public static byte[] InputStreamTOByte(InputStream in) throws IOException {  
    258.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
    259.         byte[] data = new byte[6 * 1024];  
    260.         int count = -1;  
    261.         while ((count = in.read(data, 0, 4 * 1024)) != -1)  
    262.             outStream.write(data, 0, count);  
    263.         data = null;  
    264.         return outStream.toByteArray();  
    265.     }  
    266.   
    267.     /** 
    268.      * 将OutputStream转换成byte数组 
    269.      *  
    270.      * @param in 
    271.      *            OutputStream 
    272.      * @return byte[] 
    273.      * @throws IOException 
    274.      */  
    275.     public static byte[] OutputStreamTOByte(OutputStream out)  
    276.             throws IOException {  
    277.   
    278.         byte[] data = new byte[6 * 1024];  
    279.         out.write(data);  
    280.         return data;  
    281.     }  
    282.   
    283.     /** 
    284.      * 将byte数组转换成InputStream 
    285.      *  
    286.      * @param in 
    287.      * @return 
    288.      * @throws Exception 
    289.      */  
    290.     public static InputStream byteTOInputStream(byte[] in) {  
    291.         ByteArrayInputStream is = new ByteArrayInputStream(in);  
    292.         return is;  
    293.     }  
    294.   
    295.     /** 
    296.      * 将byte数组转换成OutputStream 
    297.      *  
    298.      * @param in 
    299.      * @return 
    300.      * @throws IOException 
    301.      * @throws Exception 
    302.      */  
    303.     public static OutputStream byteTOOutputStream(byte[] in) throws IOException {  
    304.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
    305.         out.write(in);  
    306.         return out;  
    307.     }  
    308.   
    309.     /** 
    310.      * 把输入流中的数据输入到Path里的文件里 
    311.      *  
    312.      * @param path 
    313.      * @param fileName 
    314.      * @param inputStream 
    315.      * @return 
    316.      */  
    317.     public File writeFromInputToSD(String path, InputStream inputStream) {  
    318.         File file = null;  
    319.         OutputStream output = null;  
    320.         try {  
    321.             file = creatFileIfNotExist(path);  
    322.             output = new FileOutputStream(file);  
    323.             byte[] buffer = new byte[4 * 1024];  
    324.             int temp;  
    325.             while ((temp = inputStream.read(buffer)) != -1) {  
    326.                 output.write(buffer, 0, temp);  
    327.             }  
    328.             output.flush();  
    329.         } catch (Exception e) {  
    330.             e.printStackTrace();  
    331.         } finally {  
    332.             try {  
    333.                 output.close();  
    334.             } catch (Exception e) {  
    335.                 e.printStackTrace();  
    336.             }  
    337.         }  
    338.         return file;  
    339.     }  
    340.   
    341.     /** 
    342.      * 把数据输入到Path里的文件里 
    343.      *  
    344.      * @param path 
    345.      * @param fileName 
    346.      * @param inputStream 
    347.      * @return 
    348.      */  
    349.     public File writeFromInputToSD(String path, byte[] b) {  
    350.         File file = null;  
    351.         OutputStream output = null;  
    352.         try {  
    353.             file = creatFileIfNotExist(path);  
    354.             output = new FileOutputStream(file);  
    355.             output.write(b);  
    356.             output.flush();  
    357.         } catch (Exception e) {  
    358.             e.printStackTrace();  
    359.         } finally {  
    360.             try {  
    361.                 output.close();  
    362.             } catch (Exception e) {  
    363.                 e.printStackTrace();  
    364.             }  
    365.         }  
    366.         return file;  
    367.     }  
    368.   
    369.     /** 
    370.      * 方法:把一段文本保存到给定的路径中. 
    371.      */  
    372.     public void saveTxtFile(String filePath, String text) {  
    373.         try {  
    374.             // 首先构建一个文件输出流,用于向文件中写入数据.  
    375.             creatFileIfNotExist(filePath);  
    376.             String txt = readTextLine(filePath);  
    377.             text = text + txt;  
    378.             FileOutputStream out = new FileOutputStream(filePath);  
    379.             // 构建一个写入器,用于向流中写入字符数据  
    380.             OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");  
    381.             writer.write(text);  
    382.             // 关闭Writer,关闭输出流  
    383.             writer.close();  
    384.             out.close();  
    385.         } catch (Exception e) {  
    386.             String ext = e.getLocalizedMessage();  
    387.             // Toast.makeText(this, ext, Toast.LENGTH_LONG).show();  
    388.         }  
    389.   
    390.     }  
    391.   
    392.     public void clearTxtFile(String filePath) {  
    393.         try {  
    394.             // 首先构建一个文件输出流,用于向文件中写入数据.  
    395.             String text = "";  
    396.             FileOutputStream out = new FileOutputStream(filePath);  
    397.             // 构建一个写入器,用于向流中写入字符数据  
    398.             OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");  
    399.             writer.write(text);  
    400.             // 关闭Writer,关闭输出流  
    401.             writer.close();  
    402.             out.close();  
    403.         } catch (Exception e) {  
    404.             String ext = e.getLocalizedMessage();  
    405.             // Toast.makeText(this, ext, Toast.LENGTH_LONG).show();  
    406.         }  
    407.     }  
    408.   
    409.     // 读取一个给定的文本文件内容,并把内容以一个字符串的形式返回  
    410.     public String readTextLine(String textFile) {  
    411.         try {  
    412.             // 首先构建一个文件输入流,该流用于从文本文件中读取数据  
    413.             FileInputStream input = new FileInputStream(textFile);  
    414.             // 为了能够从流中读取文本数据,我们首先要构建一个特定的Reader的实例,  
    415.             // 因为我们是从一个输入流中读取数据,所以这里适合使用InputStreamReader.  
    416.             InputStreamReader streamReader = new InputStreamReader(input,  
    417.                     "gb2312");  
    418.             // 为了能够实现一次读取一行文本的功能,我们使用了 LineNumberReader类,  
    419.             // 要构建LineNumberReader的实例,必须要传一个Reader实例做参数,  
    420.             // 我们传入前面已经构建好的Reder.  
    421.             LineNumberReader reader = new LineNumberReader(streamReader);  
    422.             // 字符串line用来保存每次读取到的一行文本.  
    423.             String line = null;  
    424.             // 这里我们使用一个StringBuilder来存储读取到的每一行文本,  
    425.             // 之所以不用String,是因为它每次修改都会产生一个新的实例,  
    426.             // 所以浪费空间,效率低.  
    427.             StringBuilder allLine = new StringBuilder();  
    428.             // 每次读取到一行,直到读取完成  
    429.             while ((line = reader.readLine()) != null) {  
    430.                 allLine.append(line);  
    431.                 // 这里每一行后面,加上一个换行符,LINUX中换行是” ”,  
    432.                 // windows中换行是” ”.  
    433.                 allLine.append(" ");  
    434.             }  
    435.             // 把Reader和Stream关闭  
    436.             streamReader.close();  
    437.             reader.close();  
    438.             input.close();  
    439.             // 把读取的字符串返回  
    440.             return allLine.toString();  
    441.         } catch (Exception e) {  
    442.             // Toast.makeText(this, e.getLocalizedMessage(),  
    443.             // Toast.LENGTH_LONG).show();  
    444.             return "";  
    445.         }  
    446.     }  
    447.   
    448.     // 转换dip为px  
    449.     public int convertDipOrPx(Context context, int dip) {  
    450.         float scale = context.getResources().getDisplayMetrics().density;  
    451.         return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));  
    452.     }  
    453.   
    454.     // 转换px为dip  
    455.     public int convertPxOrDip(Context context, int px) {  
    456.         float scale = context.getResources().getDisplayMetrics().density;  
    457.         return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));  
    458.     }  
    459.   
    460.     /** 
    461.      * 将px值转换为sp值,保证文字大小不变 
    462.      *  
    463.      * @param pxValue 
    464.      * @param fontScale 
    465.      *            (DisplayMetrics类中属性scaledDensity) 
    466.      * @return 
    467.      */  
    468.     public int px2sp(Context context, float pxValue) {  
    469.         float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
    470.         return (int) (pxValue / fontScale + 0.5f);  
    471.     }  
    472.   
    473.     /** 
    474.      * 将sp值转换为px值,保证文字大小不变 
    475.      *  
    476.      * @param spValue 
    477.      * @param fontScale 
    478.      *            (DisplayMetrics类中属性scaledDensity) 
    479.      * @return 
    480.      */  
    481.     public int sp2px(Context context, float spValue) {  
    482.         float fontScale = context.getResources().getDisplayMetrics().scaledDensity;  
    483.         return (int) (spValue * fontScale + 0.5f);  
    484.     }  
    485.   
    486.     // 把字加长,使其可以滚动,在音乐界面  
    487.     public String dealString(String st, int size) {  
    488.         int value = size;  
    489.         if (st.length() >= value)  
    490.             return "  " + st + "  ";  
    491.         else {  
    492.             int t = (value - st.length()) / 2;  
    493.             for (int i = 0; i < t; i++) {  
    494.                 st = " " + st + "  ";  
    495.             }  
    496.             return st;  
    497.         }  
    498.     }  
    499.   
    500.     public String getTimeByFormat(String format) {  
    501.         SimpleDateFormat formatter = new SimpleDateFormat(format);  
    502.         Date curDate = new Date(System.currentTimeMillis());// 获取当前时间  
    503.         String str = formatter.format(curDate);  
    504.         return str;  
    505.     }  
    506.   
    507.     public String getDateTimeBylong(long time_data, String dateformat_batt) {  
    508.         java.util.Date date = new java.util.Date(time_data);  
    509.         SimpleDateFormat format = new SimpleDateFormat(dateformat_batt);  
    510.         return format.format(date);  
    511.     }  
    512.   
    513.     // 取前面的名字 "."  
    514.     public String getNameByFlag(String source, String flag) {  
    515.         // String[] source_spli = source.split(flag);  
    516.         String s = source.toLowerCase().replace(flag, "");  
    517.         return s.trim();  
    518.     }  
    519.   
    520.     /** 
    521.      * 取Asset文件夹下文件 
    522.      * @param paramContext 
    523.      * @param paramString 
    524.      * @return 
    525.      * @throws IOException 
    526.      */  
    527.     public InputStream getAssetsInputStream(Context paramContext,  
    528.             String paramString) throws IOException {  
    529.         return paramContext.getResources().getAssets().open(paramString);  
    530.     }  
    531.       
    532.     //以省内存的方式读取图片  
    533.         public Bitmap getBitmap(InputStream is){  
    534.                BitmapFactory.Options opt = new BitmapFactory.Options();     
    535.                 opt.inPreferredConfig = Bitmap.Config.RGB_565;      
    536.                opt.inPurgeable = true;     
    537.                opt.inInputShareable = true;   
    538.                opt.inSampleSize = 4;  
    539.                   //获取资源图片     
    540.                //InputStream is = mContext.getResources().openRawResource(resId);     
    541.                    return BitmapFactory.decodeStream(is,null,opt);     
    542.         }  
    543.   
    544. }  


    7.软键盘操作KeyBoardUtils.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class KeyBoardUtils    
    2. {    
    3.     /**  
    4.      * 打卡软键盘  
    5.      *   
    6.      * @param mEditText  
    7.      *            输入框  
    8.      * @param mContext  
    9.      *            上下文  
    10.      */    
    11.     public static void openKeybord(EditText mEditText, Context mContext)    
    12.     {    
    13.         InputMethodManager imm = (InputMethodManager) mContext    
    14.                 .getSystemService(Context.INPUT_METHOD_SERVICE);    
    15.         imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);    
    16.         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,    
    17.                 InputMethodManager.HIDE_IMPLICIT_ONLY);    
    18.     }    
    19.     
    20.     /**  
    21.      * 关闭软键盘  
    22.      *   
    23.      * @param mEditText  
    24.      *            输入框  
    25.      * @param mContext  
    26.      *            上下文  
    27.      */    
    28.     public static void closeKeybord(EditText mEditText, Context mContext)    
    29.     {    
    30.         InputMethodManager imm = (InputMethodManager) mContext    
    31.                 .getSystemService(Context.INPUT_METHOD_SERVICE);    
    32.     
    33.         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);    
    34.     }    
    35. }    

    8.网络连接类NetUtils.java

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public class NetUtils    
    2. {    
    3.     private NetUtils()    
    4.     {    
    5.         /* cannot be instantiated */    
    6.         throw new UnsupportedOperationException("cannot be instantiated");    
    7.     }    
    8.     
    9.     /**  
    10.      * 判断网络是否连接  
    11.      *   
    12.      * @param context  
    13.      * @return  
    14.      */    
    15.     public static boolean isConnected(Context context)    
    16.     {    
    17.     
    18.         ConnectivityManager connectivity = (ConnectivityManager) context    
    19.                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
    20.     
    21.         if (null != connectivity)    
    22.         {    
    23.     
    24.             NetworkInfo info = connectivity.getActiveNetworkInfo();    
    25.             if (null != info && info.isConnected())    
    26.             {    
    27.                 if (info.getState() == NetworkInfo.State.CONNECTED)    
    28.                 {    
    29.                     return true;    
    30.                 }    
    31.             }    
    32.         }    
    33.         return false;    
    34.     }    
    35.     
    36.     /**  
    37.      * 判断是否是wifi连接  
    38.      */    
    39.     public static boolean isWifi(Context context)    
    40.     {    
    41.         ConnectivityManager cm = (ConnectivityManager) context    
    42.                 .getSystemService(Context.CONNECTIVITY_SERVICE);    
    43.     
    44.         if (cm == null)    
    45.             return false;    
    46.         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;    
    47.     
    48.     }    
    49.     
    50.     /**  
    51.      * 打开网络设置界面  
    52.      */    
    53.     public static void openSetting(Activity activity)    
    54.     {    
    55.         Intent intent = new Intent("/");    
    56.         ComponentName cm = new ComponentName("com.android.settings",    
    57.                 "com.android.settings.WirelessSettings");    
    58.         intent.setComponent(cm);    
    59.         intent.setAction("android.intent.action.VIEW");    
    60.         activity.startActivityForResult(intent, 0);    
    61.     }    
    62.     
    63. }    

    9.检测某程序是否安装

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. public static boolean isInstalledApp(Context context, String packageName)  
    2.     {  
    3.         Boolean flag = false;  
    4.   
    5.         try  
    6.         {  
    7.             PackageManager pm = context.getPackageManager();  
    8.             List<PackageInfo> pkgs = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);  
    9.             for (PackageInfo pkg : pkgs)  
    10.             {  
    11.                 // 当找到了名字和该包名相同的时候,返回  
    12.                 if ((pkg.packageName).equals(packageName))  
    13.                 {  
    14.                     return flag = true;  
    15.                 }  
    16.             }  
    17.         }  
    18.         catch (Exception e)  
    19.         {  
    20.             // TODO Auto-generated catch block  
    21.             e.printStackTrace();  
    22.         }  
    23.   
    24.         return flag;  
    25.     }  

    10.安装apk文件

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. /** 
    2.      * 安装.apk文件 
    3.      *  
    4.      * @param context 
    5.      */  
    6.     public void install(Context context, String fileName)  
    7.     {  
    8.         if (TextUtils.isEmpty(fileName) || context == null)  
    9.         {  
    10.             return;  
    11.         }  
    12.         try  
    13.         {  
    14.             Intent intent = new Intent(Intent.ACTION_VIEW);  
    15.             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    16.             intent.setAction(android.content.Intent.ACTION_VIEW);  
    17.             intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");  
    18.             context.startActivity(intent);  
    19.         }  
    20.         catch (Exception e)  
    21.         {  
    22.             e.printStackTrace();  
    23.         }  
    24.     }  
    25.   
    26.     /** 
    27.      * 安装.apk文件 
    28.      *  
    29.      * @param context 
    30.      */  
    31.     public void install(Context context, File file)  
    32.     {  
    33.         try  
    34.         {  
    35.             Intent intent = new Intent(Intent.ACTION_VIEW);  
    36.             intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
    37.             context.startActivity(intent);  
    38.         }  
    39.         catch (Exception e)  
    40.         {  
    41.             e.printStackTrace();  
    42.         }  
    43.     }  


    11.string.xml中%s的用法

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. 在strings.xml中添加字符串  
    2. string name="text">Hello,%s!</string>  
    3. 代码中使用  
    4. textView.setText(String.format(getResources().getString(R.string.text),"Android"));  
    5. 输出结果:Hello,Android!  


    12.根据mac地址+deviceid获取设备唯一编码

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. private static String DEVICEKEY = "";  
    2.   
    3.     /** 
    4.      * 根据mac地址+deviceid 
    5.      * 获取设备唯一编码 
    6.      * @return 
    7.      */  
    8.     public static String getDeviceKey()  
    9.     {  
    10.         if ("".equals(DEVICEKEY))  
    11.         {  
    12.             String macAddress = "";  
    13.             WifiManager wifiMgr = (WifiManager)MainApplication.getIns().getSystemService(MainApplication.WIFI_SERVICE);  
    14.             WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());  
    15.             if (null != info)  
    16.             {  
    17.                 macAddress = info.getMacAddress();  
    18.             }  
    19.             TelephonyManager telephonyManager =  
    20.                 (TelephonyManager)MainApplication.getIns().getSystemService(MainApplication.TELEPHONY_SERVICE);  
    21.             String deviceId = telephonyManager.getDeviceId();  
    22.             DEVICEKEY = MD5Util.toMD5("android" + Constant.APPKEY + Constant.APPPWD + macAddress + deviceId);  
    23.         }  
    24.         return DEVICEKEY;  
    25.     }  

    13.获取手机及SIM卡相关信息

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. /** 
    2.      * 获取手机及SIM卡相关信息 
    3.      * @param context 
    4.      * @return 
    5.      */  
    6.     public static Map<String, String> getPhoneInfo(Context context) {  
    7.         Map<String, String> map = new HashMap<String, String>();  
    8.         TelephonyManager tm = (TelephonyManager) context  
    9.                 .getSystemService(Context.TELEPHONY_SERVICE);  
    10.         String imei = tm.getDeviceId();  
    11.         String imsi = tm.getSubscriberId();  
    12.         String phoneMode = android.os.Build.MODEL;   
    13.         String phoneSDk = android.os.Build.VERSION.RELEASE;  
    14.         map.put("imei", imei);  
    15.         map.put("imsi", imsi);  
    16.         map.put("phoneMode", phoneMode+"##"+phoneSDk);  
    17.         map.put("model", phoneMode);  
    18.         map.put("sdk", phoneSDk);  
    19.         return map;  
    20.     }  

    12.二维码工具类,需要zxing.jar类库支持

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
      1. import android.graphics.Bitmap;  
      2.   
      3. import com.google.zxing.BarcodeFormat;  
      4. import com.google.zxing.MultiFormatWriter;  
      5. import com.google.zxing.WriterException;  
      6. import com.google.zxing.common.BitMatrix;  
      7.   
      8. /**  
      9.  * 二维码工具类 
      10.   
      11.  */  
      12.   
      13. public class QrCodeUtils {  
      14.       
      15.     /** 
      16.      * 传入字符串生成二维码 
      17.      * @param str 
      18.      * @return 
      19.      * @throws WriterException 
      20.      */  
      21.     public static Bitmap Create2DCode(String str) throws WriterException {  
      22.         // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败  
      23.         BitMatrix matrix = new MultiFormatWriter().encode(str,  
      24.                 BarcodeFormat.QR_CODE, 300, 300);  
      25.         int width = matrix.getWidth();  
      26.         int height = matrix.getHeight();  
      27.         // 二维矩阵转为一维像素数组,也就是一直横着排了  
      28.         int[] pixels = new int[width * height];  
      29.         for (int y = 0; y < height; y++) {  
      30.             for (int x = 0; x < width; x++) {  
      31.                 if (matrix.get(x, y)) {  
      32.                     pixels[y * width + x] = 0xff000000;  
      33.                 }  
      34.   
      35.             }  
      36.         }  
      37.   
      38.         Bitmap bitmap = Bitmap.createBitmap(width, height,  
      39.                 Bitmap.Config.ARGB_8888);  
      40.         // 通过像素数组生成bitmap,具体参考api  
      41.         bitmap.setPixels(pixels, 0, width, 0, 0, width, height);  
      42.         return bitmap;  
      43.     }  
      44. }  
  • 相关阅读:
    散列
    Mac os 使用brew install 安装工具时报错 fatal: not in a git directory Error: Command failed with exit 128: git
    java虚拟机内存溢出
    windows 环境变量 立即生效
    phoenix 建表无法映射hbase已有字段的问题解决
    Phoenix
    Elasticsearch搭建集群步骤:
    分层架构的优缺点
    stateTest
    常用命令
  • 原文地址:https://www.cnblogs.com/jiangbeixiaoqiao/p/6635709.html
Copyright © 2020-2023  润新知