zoukankan      html  css  js  c++  java
  • 摘录android工具类

     1 import android.content.Context;
     2 import android.content.pm.PackageInfo;
     3 import android.content.pm.PackageManager;
     4 import android.content.pm.PackageManager.NameNotFoundException;
     5 
     6 //跟App相关的辅助类
     7 public class AppUtils
     8 {
     9 
    10     private AppUtils()
    11     {
    12         /* cannot be instantiated */
    13         throw new UnsupportedOperationException("cannot be instantiated");
    14 
    15     }
    16 
    17     /**
    18      * 获取应用程序名称
    19      */
    20     public static String getAppName(Context context)
    21     {
    22         try
    23         {
    24             PackageManager packageManager = context.getPackageManager();
    25             PackageInfo packageInfo = packageManager.getPackageInfo(
    26                     context.getPackageName(), 0);
    27             int labelRes = packageInfo.applicationInfo.labelRes;
    28             return context.getResources().getString(labelRes);
    29         } catch (NameNotFoundException e)
    30         {
    31             e.printStackTrace();
    32         }
    33         return null;
    34     }
    35 
    36     /**
    37      * [获取应用程序版本名称信息]
    38      * 
    39      * @param context
    40      * @return 当前应用的版本名称
    41      */
    42     public static String getVersionName(Context context)
    43     {
    44         try
    45         {
    46             PackageManager packageManager = context.getPackageManager();
    47             PackageInfo packageInfo = packageManager.getPackageInfo(
    48                     context.getPackageName(), 0);
    49             return packageInfo.versionName;
    50 
    51         } catch (NameNotFoundException e)
    52         {
    53             e.printStackTrace();
    54         }
    55         return null;
    56     }
    57 
    58 }
    View Code

    二、常用单位转换的辅助类

     1 import android.content.Context;
     2 import android.util.TypedValue;
     3 
     4 //常用单位转换的辅助类
     5 public class DensityUtils
     6 {
     7     private DensityUtils()
     8     {
     9         /* cannot be instantiated */
    10         throw new UnsupportedOperationException("cannot be instantiated");
    11     }
    12 
    13     /**
    14      * dp转px
    15      * 
    16      * @param context
    17      * @param val
    18      * @return
    19      */
    20     public static int dp2px(Context context, float dpVal)
    21     {
    22         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
    23                 dpVal, context.getResources().getDisplayMetrics());
    24     }
    25 
    26     /**
    27      * sp转px
    28      * 
    29      * @param context
    30      * @param val
    31      * @return
    32      */
    33     public static int sp2px(Context context, float spVal)
    34     {
    35         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
    36                 spVal, context.getResources().getDisplayMetrics());
    37     }
    38 
    39     /**
    40      * px转dp
    41      * 
    42      * @param context
    43      * @param pxVal
    44      * @return
    45      */
    46     public static float px2dp(Context context, float pxVal)
    47     {
    48         final float scale = context.getResources().getDisplayMetrics().density;
    49         return (pxVal / scale);
    50     }
    51 
    52     /**
    53      * px转sp
    54      * 
    55      * @param fontScale
    56      * @param pxVal
    57      * @return
    58      */
    59     public static float px2sp(Context context, float pxVal)
    60     {
    61         return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    62     }
    63 
    64 }
    View Code

    三、Http请求的工具类

      1 import java.io.BufferedReader;
      2 import java.io.ByteArrayOutputStream;
      3 import java.io.IOException;
      4 import java.io.InputStream;
      5 import java.io.InputStreamReader;
      6 import java.io.PrintWriter;
      7 import java.net.HttpURLConnection;
      8 import java.net.URL;
      9 
     10 //Http请求的工具类
     11 public class HttpUtils
     12 {
     13 
     14     private static final int TIMEOUT_IN_MILLIONS = 5000;
     15 
     16     public interface CallBack
     17     {
     18         void onRequestComplete(String result);
     19     }
     20 
     21 
     22     /**
     23      * 异步的Get请求
     24      * 
     25      * @param urlStr
     26      * @param callBack
     27      */
     28     public static void doGetAsyn(final String urlStr, final CallBack callBack)
     29     {
     30         new Thread()
     31         {
     32             public void run()
     33             {
     34                 try
     35                 {
     36                     String result = doGet(urlStr);
     37                     if (callBack != null)
     38                     {
     39                         callBack.onRequestComplete(result);
     40                     }
     41                 } catch (Exception e)
     42                 {
     43                     e.printStackTrace();
     44                 }
     45 
     46             };
     47         }.start();
     48     }
     49 
     50     /**
     51      * 异步的Post请求
     52      * @param urlStr
     53      * @param params
     54      * @param callBack
     55      * @throws Exception
     56      */
     57     public static void doPostAsyn(final String urlStr, final String params,
     58             final CallBack callBack) throws Exception
     59     {
     60         new Thread()
     61         {
     62             public void run()
     63             {
     64                 try
     65                 {
     66                     String result = doPost(urlStr, params);
     67                     if (callBack != null)
     68                     {
     69                         callBack.onRequestComplete(result);
     70                     }
     71                 } catch (Exception e)
     72                 {
     73                     e.printStackTrace();
     74                 }
     75 
     76             };
     77         }.start();
     78 
     79     }
     80 
     81     /**
     82      * Get请求,获得返回数据
     83      * 
     84      * @param urlStr
     85      * @return
     86      * @throws Exception
     87      */
     88     public static String doGet(String urlStr) 
     89     {
     90         URL url = null;
     91         HttpURLConnection conn = null;
     92         InputStream is = null;
     93         ByteArrayOutputStream baos = null;
     94         try
     95         {
     96             url = new URL(urlStr);
     97             conn = (HttpURLConnection) url.openConnection();
     98             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
     99             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
    100             conn.setRequestMethod("GET");
    101             conn.setRequestProperty("accept", "*/*");
    102             conn.setRequestProperty("connection", "Keep-Alive");
    103             if (conn.getResponseCode() == 200)
    104             {
    105                 is = conn.getInputStream();
    106                 baos = new ByteArrayOutputStream();
    107                 int len = -1;
    108                 byte[] buf = new byte[128];
    109 
    110                 while ((len = is.read(buf)) != -1)
    111                 {
    112                     baos.write(buf, 0, len);
    113                 }
    114                 baos.flush();
    115                 return baos.toString();
    116             } else
    117             {
    118                 throw new RuntimeException(" responseCode is not 200 ... ");
    119             }
    120 
    121         } catch (Exception e)
    122         {
    123             e.printStackTrace();
    124         } finally
    125         {
    126             try
    127             {
    128                 if (is != null)
    129                     is.close();
    130             } catch (IOException e)
    131             {
    132             }
    133             try
    134             {
    135                 if (baos != null)
    136                     baos.close();
    137             } catch (IOException e)
    138             {
    139             }
    140             conn.disconnect();
    141         }
    142         
    143         return null ;
    144 
    145     }
    146 
    147     /**
    148      * 向指定 URL 发送POST方法的请求
    149      * 
    150      * @param url
    151      *            发送请求的 URL
    152      * @param param
    153      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
    154      * @return 所代表远程资源的响应结果
    155      * @throws Exception
    156      */
    157     public static String doPost(String url, String param) 
    158     {
    159         PrintWriter out = null;
    160         BufferedReader in = null;
    161         String result = "";
    162         try
    163         {
    164             URL realUrl = new URL(url);
    165             // 打开和URL之间的连接
    166             HttpURLConnection conn = (HttpURLConnection) realUrl
    167                     .openConnection();
    168             // 设置通用的请求属性
    169             conn.setRequestProperty("accept", "*/*");
    170             conn.setRequestProperty("connection", "Keep-Alive");
    171             conn.setRequestMethod("POST");
    172             conn.setRequestProperty("Content-Type",
    173                     "application/x-www-form-urlencoded");
    174             conn.setRequestProperty("charset", "utf-8");
    175             conn.setUseCaches(false);
    176             // 发送POST请求必须设置如下两行
    177             conn.setDoOutput(true);
    178             conn.setDoInput(true);
    179             conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
    180             conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
    181 
    182             if (param != null && !param.trim().equals(""))
    183             {
    184                 // 获取URLConnection对象对应的输出流
    185                 out = new PrintWriter(conn.getOutputStream());
    186                 // 发送请求参数
    187                 out.print(param);
    188                 // flush输出流的缓冲
    189                 out.flush();
    190             }
    191             // 定义BufferedReader输入流来读取URL的响应
    192             in = new BufferedReader(
    193                     new InputStreamReader(conn.getInputStream()));
    194             String line;
    195             while ((line = in.readLine()) != null)
    196             {
    197                 result += line;
    198             }
    199         } catch (Exception e)
    200         {
    201             e.printStackTrace();
    202         }
    203         // 使用finally块来关闭输出流、输入流
    204         finally
    205         {
    206             try
    207             {
    208                 if (out != null)
    209                 {
    210                     out.close();
    211                 }
    212                 if (in != null)
    213                 {
    214                     in.close();
    215                 }
    216             } catch (IOException ex)
    217             {
    218                 ex.printStackTrace();
    219             }
    220         }
    221         return result;
    222     }
    223 }
    View Code

    四、打开关闭软键盘

     1 import android.content.Context;
     2 import android.view.inputmethod.InputMethodManager;
     3 import android.widget.EditText;
     4 
     5 //打开或关闭软键盘
     6 public class KeyBoardUtils
     7 {
     8     /**
     9      * 打卡软键盘
    10      * 
    11      * @param mEditText输入框
    12      * @param mContext上下文
    13      */
    14     public static void openKeybord(EditText mEditText, Context mContext)
    15     {
    16         InputMethodManager imm = (InputMethodManager) mContext
    17                 .getSystemService(Context.INPUT_METHOD_SERVICE);
    18         imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
    19         imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
    20                 InputMethodManager.HIDE_IMPLICIT_ONLY);
    21     }
    22 
    23     /**
    24      * 关闭软键盘
    25      * 
    26      * @param mEditText输入框
    27      * @param mContext上下文
    28      */
    29     public static void closeKeybord(EditText mEditText, Context mContext)
    30     {
    31         InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    32 
    33         imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    34     }
    35 }
    View Code

    五、统一管理类

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

    六、网络工具类

     1 import android.app.Activity;
     2 import android.content.ComponentName;
     3 import android.content.Context;
     4 import android.content.Intent;
     5 import android.net.ConnectivityManager;
     6 import android.net.NetworkInfo;
     7 
     8 //跟网络相关的工具类
     9 public class NetUtils
    10 {
    11     private NetUtils()
    12     {
    13         /* cannot be instantiated */
    14         throw new UnsupportedOperationException("cannot be instantiated");
    15     }
    16 
    17     /**
    18      * 判断网络是否连接
    19      * 
    20      * @param context
    21      * @return
    22      */
    23     public static boolean isConnected(Context context)
    24     {
    25 
    26         ConnectivityManager connectivity = (ConnectivityManager) context
    27                 .getSystemService(Context.CONNECTIVITY_SERVICE);
    28 
    29         if (null != connectivity)
    30         {
    31 
    32             NetworkInfo info = connectivity.getActiveNetworkInfo();
    33             if (null != info && info.isConnected())
    34             {
    35                 if (info.getState() == NetworkInfo.State.CONNECTED)
    36                 {
    37                     return true;
    38                 }
    39             }
    40         }
    41         return false;
    42     }
    43 
    44     /**
    45      * 判断是否是wifi连接
    46      */
    47     public static boolean isWifi(Context context)
    48     {
    49         ConnectivityManager cm = (ConnectivityManager) context
    50                 .getSystemService(Context.CONNECTIVITY_SERVICE);
    51 
    52         if (cm == null)
    53             return false;
    54         return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
    55 
    56     }
    57 
    58     /**
    59      * 打开网络设置界面
    60      */
    61     public static void openSetting(Activity activity)
    62     {
    63         Intent intent = new Intent("/");
    64         ComponentName cm = new ComponentName("com.android.settings",
    65                 "com.android.settings.WirelessSettings");
    66         intent.setComponent(cm);
    67         intent.setAction("android.intent.action.VIEW");
    68         activity.startActivityForResult(intent, 0);
    69     }
    70 
    71 }
    View Code

    七、屏幕操作辅助类

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

    八、sd操作类

     1 import java.io.File;
     2 
     3 import android.os.Environment;
     4 import android.os.StatFs;
     5 
     6 //SD卡相关的辅助类
     7 public class SDCardUtils
     8 {
     9     private SDCardUtils()
    10     {
    11         /* cannot be instantiated */
    12         throw new UnsupportedOperationException("cannot be instantiated");
    13     }
    14 
    15     /**
    16      * 判断SDCard是否可用
    17      * 
    18      * @return
    19      */
    20     public static boolean isSDCardEnable()
    21     {
    22         return Environment.getExternalStorageState().equals(
    23                 Environment.MEDIA_MOUNTED);
    24 
    25     }
    26 
    27     /**
    28      * 获取SD卡路径
    29      * 
    30      * @return
    31      */
    32     public static String getSDCardPath()
    33     {
    34         return Environment.getExternalStorageDirectory().getAbsolutePath()
    35                 + File.separator;
    36     }
    37 
    38     /**
    39      * 获取SD卡的剩余容量 单位byte
    40      * 
    41      * @return
    42      */
    43     public static long getSDCardAllSize()
    44     {
    45         if (isSDCardEnable())
    46         {
    47             StatFs stat = new StatFs(getSDCardPath());
    48             // 获取空闲的数据块的数量
    49             long availableBlocks = (long) stat.getAvailableBlocks() - 4;
    50             // 获取单个数据块的大小(byte)
    51             long freeBlocks = stat.getAvailableBlocks();
    52             return freeBlocks * availableBlocks;
    53         }
    54         return 0;
    55     }
    56 
    57     /**
    58      * 获取指定路径所在空间的剩余可用容量字节数,单位byte
    59      * 
    60      * @param filePath
    61      * @return 容量字节 SDCard可用空间,内部存储可用空间
    62      */
    63     public static long getFreeBytes(String filePath)
    64     {
    65         // 如果是sd卡的下的路径,则获取sd卡可用容量
    66         if (filePath.startsWith(getSDCardPath()))
    67         {
    68             filePath = getSDCardPath();
    69         } else
    70         {// 如果是内部存储的路径,则获取内存存储的可用容量
    71             filePath = Environment.getDataDirectory().getAbsolutePath();
    72         }
    73         StatFs stat = new StatFs(filePath);
    74         long availableBlocks = (long) stat.getAvailableBlocks() - 4;
    75         return stat.getBlockSize() * availableBlocks;
    76     }
    77 
    78     /**
    79      * 获取系统存储路径
    80      * 
    81      * @return
    82      */
    83     public static String getRootDirectoryPath()
    84     {
    85         return Environment.getRootDirectory().getAbsolutePath();
    86     }
    87 
    88 
    89 }
    View Code

    九、存储类

      1 import java.lang.reflect.InvocationTargetException;
      2 import java.lang.reflect.Method;
      3 import java.util.Map;
      4 
      5 import android.content.Context;
      6 import android.content.SharedPreferences;
      7 
      8 public class SPUtils
      9 {
     10     public SPUtils()
     11     {
     12         /* cannot be instantiated */
     13         throw new UnsupportedOperationException("cannot be instantiated");
     14     }
     15 
     16     /**
     17      * 保存在手机里面的文件名
     18      */
     19     public static final String FILE_NAME = "share_data";
     20 
     21     /**
     22      * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     23      * 
     24      * @param context
     25      * @param key
     26      * @param object
     27      */
     28     public static void put(Context context, String key, Object object)
     29     {
     30 
     31         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
     32                 Context.MODE_PRIVATE);
     33         SharedPreferences.Editor editor = sp.edit();
     34 
     35         if (object instanceof String)
     36         {
     37             editor.putString(key, (String) object);
     38         } else if (object instanceof Integer)
     39         {
     40             editor.putInt(key, (Integer) object);
     41         } else if (object instanceof Boolean)
     42         {
     43             editor.putBoolean(key, (Boolean) object);
     44         } else if (object instanceof Float)
     45         {
     46             editor.putFloat(key, (Float) object);
     47         } else if (object instanceof Long)
     48         {
     49             editor.putLong(key, (Long) object);
     50         } else
     51         {
     52             editor.putString(key, object.toString());
     53         }
     54 
     55         SharedPreferencesCompat.apply(editor);
     56     }
     57 
     58     /**
     59      * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     60      * 
     61      * @param context
     62      * @param key
     63      * @param defaultObject
     64      * @return
     65      */
     66     public static Object get(Context context, String key, Object defaultObject)
     67     {
     68         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
     69                 Context.MODE_PRIVATE);
     70 
     71         if (defaultObject instanceof String)
     72         {
     73             return sp.getString(key, (String) defaultObject);
     74         } else if (defaultObject instanceof Integer)
     75         {
     76             return sp.getInt(key, (Integer) defaultObject);
     77         } else if (defaultObject instanceof Boolean)
     78         {
     79             return sp.getBoolean(key, (Boolean) defaultObject);
     80         } else if (defaultObject instanceof Float)
     81         {
     82             return sp.getFloat(key, (Float) defaultObject);
     83         } else if (defaultObject instanceof Long)
     84         {
     85             return sp.getLong(key, (Long) defaultObject);
     86         }
     87 
     88         return null;
     89     }
     90 
     91     /**
     92      * 移除某个key值已经对应的值
     93      * 
     94      * @param context
     95      * @param key
     96      */
     97     public static void remove(Context context, String key)
     98     {
     99         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
    100                 Context.MODE_PRIVATE);
    101         SharedPreferences.Editor editor = sp.edit();
    102         editor.remove(key);
    103         SharedPreferencesCompat.apply(editor);
    104     }
    105 
    106     /**
    107      * 清除所有数据
    108      * 
    109      * @param context
    110      */
    111     public static void clear(Context context)
    112     {
    113         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
    114                 Context.MODE_PRIVATE);
    115         SharedPreferences.Editor editor = sp.edit();
    116         editor.clear();
    117         SharedPreferencesCompat.apply(editor);
    118     }
    119 
    120     /**
    121      * 查询某个key是否已经存在
    122      * 
    123      * @param context
    124      * @param key
    125      * @return
    126      */
    127     public static boolean contains(Context context, String key)
    128     {
    129         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
    130                 Context.MODE_PRIVATE);
    131         return sp.contains(key);
    132     }
    133 
    134     /**
    135      * 返回所有的键值对
    136      * 
    137      * @param context
    138      * @return
    139      */
    140     public static Map<String, ?> getAll(Context context)
    141     {
    142         SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
    143                 Context.MODE_PRIVATE);
    144         return sp.getAll();
    145     }
    146 
    147     /**
    148      * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
    149      * 
    150      * @author zhy
    151      * 
    152      */
    153     private static class SharedPreferencesCompat
    154     {
    155         private static final Method sApplyMethod = findApplyMethod();
    156 
    157         /**
    158          * 反射查找apply的方法
    159          * 
    160          * @return
    161          */
    162         @SuppressWarnings({ "unchecked", "rawtypes" })
    163         private static Method findApplyMethod()
    164         {
    165             try
    166             {
    167                 Class clz = SharedPreferences.Editor.class;
    168                 return clz.getMethod("apply");
    169             } catch (NoSuchMethodException e)
    170             {
    171             }
    172 
    173             return null;
    174         }
    175 
    176         /**
    177          * 如果找到则使用apply执行,否则使用commit
    178          * 
    179          * @param editor
    180          */
    181         public static void apply(SharedPreferences.Editor editor)
    182         {
    183             try
    184             {
    185                 if (sApplyMethod != null)
    186                 {
    187                     sApplyMethod.invoke(editor);
    188                     return;
    189                 }
    190             } catch (IllegalArgumentException e)
    191             {
    192             } catch (IllegalAccessException e)
    193             {
    194             } catch (InvocationTargetException e)
    195             {
    196             }
    197             editor.commit();
    198         }
    199     }
    200 
    201 }
    View Code

    十、Toast操作类

     1 import android.content.Context;
     2 import android.widget.Toast;
     3 
     4  //Toast统一管理类
     5 public class T
     6 {
     7 
     8     private T()
     9     {
    10         /* cannot be instantiated */
    11         throw new UnsupportedOperationException("cannot be instantiated");
    12     }
    13 
    14     public static boolean isShow = true;
    15 
    16     /**
    17      * 短时间显示Toast
    18      * 
    19      * @param context
    20      * @param message
    21      */
    22     public static void showShort(Context context, CharSequence message)
    23     {
    24         if (isShow)
    25             Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    26     }
    27 
    28     /**
    29      * 短时间显示Toast
    30      * 
    31      * @param context
    32      * @param message
    33      */
    34     public static void showShort(Context context, int message)
    35     {
    36         if (isShow)
    37             Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
    38     }
    39 
    40     /**
    41      * 长时间显示Toast
    42      * 
    43      * @param context
    44      * @param message
    45      */
    46     public static void showLong(Context context, CharSequence message)
    47     {
    48         if (isShow)
    49             Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    50     }
    51 
    52     /**
    53      * 长时间显示Toast
    54      * 
    55      * @param context
    56      * @param message
    57      */
    58     public static void showLong(Context context, int message)
    59     {
    60         if (isShow)
    61             Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    62     }
    63 
    64     /**
    65      * 自定义显示Toast时间
    66      * 
    67      * @param context
    68      * @param message
    69      * @param duration
    70      */
    71     public static void show(Context context, CharSequence message, int duration)
    72     {
    73         if (isShow)
    74             Toast.makeText(context, message, duration).show();
    75     }
    76 
    77     /**
    78      * 自定义显示Toast时间
    79      * 
    80      * @param context
    81      * @param message
    82      * @param duration
    83      */
    84     public static void show(Context context, int message, int duration)
    85     {
    86         if (isShow)
    87             Toast.makeText(context, message, duration).show();
    88     }
    89 
    90 }
    View Code

    十一、操作图片类

      1 import java.io.BufferedReader;
      2 import java.io.ByteArrayOutputStream;
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.IOException;
      6 import java.io.InputStream;
      7 import java.io.InputStreamReader;
      8 import java.lang.ref.WeakReference;
      9 
     10 import android.app.Activity;
     11 import android.content.Context;
     12 import android.graphics.Bitmap;
     13 import android.graphics.BitmapFactory;
     14 import android.graphics.Matrix;
     15 import android.graphics.Bitmap.CompressFormat;
     16 import android.graphics.Typeface;
     17 import android.net.ConnectivityManager;
     18 import android.net.NetworkInfo.State;
     19 import android.util.Base64;
     20 import android.view.View;
     21 import android.view.ViewGroup;
     22 import android.view.ViewGroup.LayoutParams;
     23 import android.widget.Button;
     24 import android.widget.EditText;
     25 import android.widget.TextView;
     26 
     27 public class ToolFor9Ge 
     28 {
     29     // 缩放/裁剪图片
     30      public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight)
     31      { 
     32          // 获得图片的宽高
     33          int width = bm.getWidth();
     34          int height = bm.getHeight();
     35          // 计算缩放比例
     36          float scaleWidth = ((float) newWidth) / width;
     37          float scaleHeight = ((float) newHeight) / height;
     38          // 取得想要缩放的matrix参数
     39          Matrix matrix = new Matrix();
     40          matrix.postScale(scaleWidth, scaleHeight);
     41          // 得到新的图片
     42          Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
     43          return newbm;
     44      }
     45      
     46      // 判断有无网络链接
     47      public static boolean checkNetworkInfo(Context mContext) {
     48            ConnectivityManager conMan = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
     49            State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
     50            State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
     51            if (mobile == State.CONNECTED || mobile == State.CONNECTING)
     52               return true;
     53            if (wifi == State.CONNECTED || wifi == State.CONNECTING)
     54               return true;
     55            return false;
     56      }
     57      
     58      // 从路径获取文件名
     59      public static String getFileName(String pathandname){ 
     60          int start=pathandname.lastIndexOf("/");  
     61          int end=pathandname.lastIndexOf(".");  
     62          if(start!=-1 && end!=-1){  
     63              return pathandname.substring(start+1,end);    
     64          }else{  
     65              return null;  
     66          }             
     67      }
     68      
     69      // 通过路径生成Base64文件
     70      public static String getBase64FromPath(String path)
     71      {
     72          String base64="";
     73          try
     74          {
     75              File file = new File(path);
     76              byte[] buffer = new byte[(int) file.length() + 100];  
     77             @SuppressWarnings("resource")
     78             int length = new FileInputStream(file).read(buffer);  
     79              base64 = Base64.encodeToString(buffer, 0, length,  Base64.DEFAULT);
     80          }
     81          catch (IOException e) {
     82             e.printStackTrace();
     83         }
     84          return base64;
     85      }
     86      
     87      //通过文件路径获取到bitmap
     88      public static Bitmap getBitmapFromPath(String path, int w, int h) {
     89         BitmapFactory.Options opts = new BitmapFactory.Options();
     90         // 设置为ture只获取图片大小
     91         opts.inJustDecodeBounds = true;
     92         opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
     93         // 返回为空
     94         BitmapFactory.decodeFile(path, opts);
     95         int width = opts.outWidth;
     96         int height = opts.outHeight;
     97         float scaleWidth = 0.f, scaleHeight = 0.f;
     98         if (width > w || height > h) {
     99             // 缩放
    100             scaleWidth = ((float) width) / w;
    101             scaleHeight = ((float) height) / h;
    102         }
    103         opts.inJustDecodeBounds = false;
    104         float scale = Math.max(scaleWidth, scaleHeight);
    105         opts.inSampleSize = (int)scale;
    106         WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
    107         return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    108     }
    109      
    110      //把bitmap转换成base64
    111      public static String getBase64FromBitmap(Bitmap bitmap, int bitmapQuality)
    112      {
    113          ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    114          bitmap.compress(CompressFormat.PNG, bitmapQuality, bStream);
    115          byte[] bytes = bStream.toByteArray();
    116          return Base64.encodeToString(bytes, Base64.DEFAULT);
    117      }
    118      
    119      //把base64转换成bitmap
    120      public static Bitmap getBitmapFromBase64(String string)
    121      {
    122          byte[] bitmapArray = null;
    123          try {
    124          bitmapArray = Base64.decode(string, Base64.DEFAULT);
    125          } catch (Exception e) {
    126          e.printStackTrace();
    127          }
    128          return BitmapFactory.decodeByteArray(bitmapArray, 0,bitmapArray.length);
    129      }
    130      
    131      //把Stream转换成String
    132      public static String convertStreamToString(InputStream is) {
    133          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    134             StringBuilder sb = new StringBuilder();
    135             String line = null;
    136 
    137             try {
    138                 while ((line = reader.readLine()) != null) {
    139                     sb.append(line + "/n");
    140                 }
    141             } catch (IOException e) {
    142                 e.printStackTrace();
    143             } finally {
    144                 try {
    145                     is.close();
    146                 } catch (IOException e) {
    147                     e.printStackTrace();
    148                 }
    149             }
    150             return sb.toString();    
    151      }    
    152      
    153      // 修改整个界面所有控件的字体
    154      public static void changeFonts(ViewGroup root,String path, Activity act) {  
    155         //path是字体路径
    156          Typeface tf = Typeface.createFromAsset(act.getAssets(),path);  
    157         for (int i = 0; i < root.getChildCount(); i++) {  
    158             View v = root.getChildAt(i); 
    159             if (v instanceof TextView) {  
    160                ((TextView) v).setTypeface(tf);  
    161             } else if (v instanceof Button) {  
    162                ((Button) v).setTypeface(tf);  
    163             } else if (v instanceof EditText) {  
    164                ((EditText) v).setTypeface(tf);  
    165             } else if (v instanceof ViewGroup) {  
    166                changeFonts((ViewGroup) v, path,act);  
    167             } 
    168         }  
    169      }
    170      
    171      // 修改整个界面所有控件的字体大小
    172       public static void changeTextSize(ViewGroup root,int size, Activity act) {  
    173          for (int i = 0; i < root.getChildCount(); i++) {  
    174              View v = root.getChildAt(i);  
    175              if (v instanceof TextView) {  
    176                 ((TextView) v).setTextSize(size);
    177              } else if (v instanceof Button) {  
    178                 ((Button) v).setTextSize(size);
    179              } else if (v instanceof EditText) {  
    180                 ((EditText) v).setTextSize(size);  
    181              } else if (v instanceof ViewGroup) {  
    182                 changeTextSize((ViewGroup) v,size,act);  
    183              }  
    184          }  
    185       }
    186       
    187       // 不改变控件位置,修改控件大小
    188     public static void changeWH(View v,int W,int H)
    189     {
    190         LayoutParams params = (LayoutParams)v.getLayoutParams();
    191         params.width = W;
    192         params.height = H;
    193         v.setLayoutParams(params);
    194     }
    195     
    196     // 修改控件的高
    197     public static void changeH(View v,int H)
    198     {
    199         LayoutParams params = (LayoutParams)v.getLayoutParams();
    200         params.height = H;
    201         v.setLayoutParams(params);
    202     }
    203         
    204 
    205 }
    View Code

    以上代码也是借鉴他人成果,此处展示仅为学习交流。

  • 相关阅读:
    168. Excel Sheet Column Title
    171. Excel Sheet Column Number
    264. Ugly Number II java solutions
    152. Maximum Product Subarray java solutions
    309. Best Time to Buy and Sell Stock with Cooldown java solutions
    120. Triangle java solutions
    300. Longest Increasing Subsequence java solutions
    63. Unique Paths II java solutions
    221. Maximal Square java solutions
    279. Perfect Squares java solutions
  • 原文地址:https://www.cnblogs.com/dalan/p/4117652.html
Copyright © 2011-2022 走看看