`
uule
  • 浏览: 6323873 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

Android快速开发工具类

 
阅读更多

来源:http://blog.csdn.net/lmj623565791/article/details/38965311

Android开发必备工具类集合

 

1、日志工具类L.java

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.zhy.utils;  
  2.   
  3. import android.util.Log;  
  4.   
  5. /** 
  6.  * Log统一管理类 
  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;// 是否需要打印bug,可以在application的onCreate函数里面初始化  
  21.     private static final String TAG = "way";  
  22.   
  23.     // 下面四个是默认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.     // 下面是传入自定义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. }  



 

网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~

2、Toast统一管理类 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.widget.Toast;  
  5.   
  6. /** 
  7.  * Toast统一管理类 
  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.      * 短时间显示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.      * 短时间显示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.      * 长时间显示Toast 
  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.      * 长时间显示Toast 
  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.      * 自定义显示Toast时间 
  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.      * 自定义显示Toast时间 
  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. }  



 

也是非常简单的一个封装,能省则省了~~

3、SharedPreferences封装类SPUtils

 

import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
import java.util.Map;  
  
import android.content.Context;  
import android.content.SharedPreferences;  
  
public class SPUtils  
{  
    /** 
     * 保存在手机里面的文件名 
     */  
    public static final String FILE_NAME = "share_data";  
	public static final String LOGIN_DATA="loginData";
	public static final String IS_LOGIN= "IS_LOGIN";
  
    /** 
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 
     *  
     * @param context 
     * @param key 
     * @param object 
     */  
    public static void put(Context context, String key, Object object)  
    {  
  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
        SharedPreferences.Editor editor = sp.edit();  
  
        if (object instanceof String)  
        {  
            editor.putString(key, (String) object);  
        } else if (object instanceof Integer)  
        {  
            editor.putInt(key, (Integer) object);  
        } else if (object instanceof Boolean)  
        {  
            editor.putBoolean(key, (Boolean) object);  
        } else if (object instanceof Float)  
        {  
            editor.putFloat(key, (Float) object);  
        } else if (object instanceof Long)  
        {  
            editor.putLong(key, (Long) object);  
        } else  
        {  
            editor.putString(key, object.toString());  
        }  
  
        //SharedPreferencesCompat.apply(editor);  
		editor.commit();
    }  
  
    /** 
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值 
     *  
     * @param context 
     * @param key 
     * @param defaultObject 
     * @return 
     */  
    public static Object get(Context context, String key, Object defaultObject)  
    {  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
  
        if (defaultObject instanceof String)  
        {  
            return sp.getString(key, (String) defaultObject);  
        } else if (defaultObject instanceof Integer)  
        {  
            return sp.getInt(key, (Integer) defaultObject);  
        } else if (defaultObject instanceof Boolean)  
        {  
            return sp.getBoolean(key, (Boolean) defaultObject);  
        } else if (defaultObject instanceof Float)  
        {  
            return sp.getFloat(key, (Float) defaultObject);  
        } else if (defaultObject instanceof Long)  
        {  
            return sp.getLong(key, (Long) defaultObject);  
        }  
  
        return null;  
    }  
  
    /** 
     * 移除某个key值已经对应的值 
     * @param context 
     * @param key 
     */  
    public static void remove(Context context, String key)  
    {  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
        SharedPreferences.Editor editor = sp.edit();  
        editor.remove(key);  
        //SharedPreferencesCompat.apply(editor);  
		
		editor.commit();
    }  
  
    /** 
     * 清除所有数据 
     * @param context 
     */  
    public static void clear(Context context)  
    {  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
        SharedPreferences.Editor editor = sp.edit();  
        editor.clear();  
        SharedPreferencesCompat.apply(editor);  
    }  
  
    /** 
     * 查询某个key是否已经存在 
     * @param context 
     * @param key 
     * @return 
     */  
    public static boolean contains(Context context, String key)  
    {  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
        return sp.contains(key);  
    }  
  
    /** 
     * 返回所有的键值对 
     *  
     * @param context 
     * @return 
     */  
    public static Map<String, ?> getAll(Context context)  
    {  
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  
                Context.MODE_PRIVATE);  
        return sp.getAll();  
    }  
  
    /** 
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类 
     *  
     * @author zhy 
     *  
     */  
    private static class SharedPreferencesCompat  
    {  
        private static final Method sApplyMethod = findApplyMethod();  
  
        /** 
         * 反射查找apply的方法 
         *  
         * @return 
         */  
        @SuppressWarnings({ "unchecked", "rawtypes" })  
        private static Method findApplyMethod()  
        {  
            try  
            {  
                Class clz = SharedPreferences.Editor.class;  
                return clz.getMethod("apply");  
            } catch (NoSuchMethodException e)  
            {  
            }  
  
            return null;  
        }  
  
        /** 
         * 如果找到则使用apply执行,否则使用commit 
         *  
         * @param editor 
         */  
        public static void apply(SharedPreferences.Editor editor)  
        {  
            try  
            {  
                if (sApplyMethod != null)  
                {  
                    sApplyMethod.invoke(editor);  
                    return;  
                }  
            } catch (IllegalArgumentException e)  
            {  
            } catch (IllegalAccessException e)  
            {  
            } catch (InvocationTargetException e)  
            {  
            }  
            editor.commit();  
        }  
    }  
  
}  




 

调用判断是否登录
isLogin=(Boolean) SPUtil.get(getActivity(), SPUtil.IS_LOGIN, false);

存储登录状态:
//保存登录状态
SPUtil.set(LoginActivity.this, SPUtil.IS_LOGIN, true);
//保存登录个人信息
SPUtil.set(LoginActivity .this, SPUtil.LOGIN_DATA, result);

退出登录:
SPUtil.setParam(MySettingsActivity.this, SPUtil.IS_LOGIN, false);
SPUtil.removeParam(MySettingsActivity.this, SPUtil.LOGIN_DATA);

 

对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;

 

注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit

首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;

所以我们使用apply进行替代,apply异步的进行写入;

但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;

SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~

 

4、单位转换类 DensityUtils

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. package com.zhy.utils;  
  2.   
  3. import android.content.Context;  
  4. import android.util.TypedValue;  
  5.   
  6. /** 
  7.  * 常用单位转换的辅助类 
  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转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转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转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转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卡相关辅助类 SDCardUtils

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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卡相关的辅助类 
  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.      * 判断SDCard是否可用 
  24.      *  
  25.      * @return 
  26.      */  
  27.     public static boolean isSDCardEnable()  
  28.     {  
  29.         return Environment.getExternalStorageState().equals(  
  30.                 Environment.MEDIA_MOUNTED);  
  31.   
  32.     }  
  33.   
  34.     /** 
  35.      * 获取SD卡路径 
  36.      *  
  37.      * @return 
  38.      */  
  39.     public static String getSDCardPath()  
  40.     {  
  41.         return Environment.getExternalStorageDirectory().getAbsolutePath()  
  42.                 + File.separator;  
  43.     }  
  44.   
  45.     /** 
  46.      * 获取SD卡的剩余容量 单位byte 
  47.      *  
  48.      * @return 
  49.      */  
  50.     public static long getSDCardAllSize()  
  51.     {  
  52.         if (isSDCardEnable())  
  53.         {  
  54.             StatFs stat = new StatFs(getSDCardPath());  
  55.             // 获取空闲的数据块的数量  
  56.             long availableBlocks = (long) stat.getAvailableBlocks() - 4;  
  57.             // 获取单个数据块的大小(byte)  
  58.             long freeBlocks = stat.getAvailableBlocks();  
  59.             return freeBlocks * availableBlocks;  
  60.         }  
  61.         return 0;  
  62.     }  
  63.   
  64.     /** 
  65.      * 获取指定路径所在空间的剩余可用容量字节数,单位byte 
  66.      *  
  67.      * @param filePath 
  68.      * @return 容量字节 SDCard可用空间,内部存储可用空间 
  69.      */  
  70.     public static long getFreeBytes(String filePath)  
  71.     {  
  72.         // 如果是sd卡的下的路径,则获取sd卡可用容量  
  73.         if (filePath.startsWith(getSDCardPath()))  
  74.         {  
  75.             filePath = getSDCardPath();  
  76.         } else  
  77.         {// 如果是内部存储的路径,则获取内存存储的可用容量  
  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.      * 获取系统存储路径 
  87.      *  
  88.      * @return 
  89.      */  
  90.     public static String getRootDirectoryPath()  
  91.     {  
  92.         return Environment.getRootDirectory().getAbsolutePath();  
  93.     }  
  94.   
  95.   
  96. }  

 

 

6、屏幕相关辅助类 ScreenUtils

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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.  * 获得屏幕相关的辅助类 
  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.      * 获得屏幕高度 
  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.      * 获得屏幕宽度 
  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.      * 获得状态栏的高度 
  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.      * 获取当前屏幕截图,包含状态栏 
  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.      * 获取当前屏幕截图,不包含状态栏 
  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相关辅助类

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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相关的辅助类 
  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.      * 获取应用程序名称 
  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.      * [获取应用程序版本名称信息] 
  45.      *  
  46.      * @param context 
  47.      * @return 当前应用的版本名称 
  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、软键盘相关辅助类KeyBoardUtils

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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.  * 打开或关闭软键盘 
  9.  *  
  10.  * @author zhy 
  11.  *  
  12.  */  
  13. public class KeyBoardUtils  
  14. {  
  15.     /** 
  16.      * 打卡软键盘 
  17.      *  
  18.      * @param mEditText 
  19.      *            输入框 
  20.      * @param mContext 
  21.      *            上下文 
  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.      * 关闭软键盘 
  34.      *  
  35.      * @param mEditText 
  36.      *            输入框 
  37.      * @param mContext 
  38.      *            上下文 
  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、网络相关辅助类 NetUtils

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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.  * 跟网络相关的工具类 
  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.      * 判断网络是否连接 
  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.      * 判断是否是wifi连接 
  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.      * 打开网络设置界面 
  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相关辅助类 HttpUtils

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  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.  * Http请求的工具类 
  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.      * 异步的Get请求 
  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.      * 异步的Post请求 
  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请求,获得返回数据 
  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.      * 向指定 URL 发送POST方法的请求  
  156.      *   
  157.      * @param url  
  158.      *            发送请求的 URL  
  159.      * @param param  
  160.      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
  161.      * @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.             // 打开和URL之间的连接  
  173.             HttpURLConnection conn = (HttpURLConnection) realUrl  
  174.                     .openConnection();  
  175.             // 设置通用的请求属性  
  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.             // 发送POST请求必须设置如下两行  
  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.                 // 获取URLConnection对象对应的输出流  
  192.                 out = new PrintWriter(conn.getOutputStream());  
  193.                 // 发送请求参数  
  194.                 out.print(param);  
  195.                 // flush输出流的缓冲  
  196.                 out.flush();  
  197.             }  
  198.             // 定义BufferedReader输入流来读取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.         // 使用finally块来关闭输出流、输入流  
  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. }  


如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~

分享到:
评论

相关推荐

    Android快速开发工具类收集,软键盘sp日志反射屏幕wifi控件点击

    本资源“Android快速开发工具类收集”是一个全面的集合,包含了多种实用的工具类,旨在加速Android应用的开发过程。以下是这些工具类的一些核心知识点: 1. **软键盘控制**: - 在Android应用中,有时我们需要根据...

    Android-Android快速开发工具类收集

    "Android-Android快速开发工具类收集" 是一个整理了多个常用工具类的资源,旨在提高开发效率,减少网络搜索时间。下面将详细介绍这个资源中的关键知识点和可能包含的功能。 1. **StringUtil**: 字符串处理工具类,...

    android快速开发工具类(优)

    本篇文章将详细探讨“android快速开发工具类”这一主题,尤其是关于网络请求的`Api`工具类的实现。 首先,Android工具类通常包含静态方法,不持有任何实例状态,这样可以避免内存泄漏,并且可以直接通过类名调用,...

    安卓开发框架工具类相关-Android快速开发系列10个常用工具类.rar

    【标题】"安卓开发框架工具类相关-Android快速开发系列10个常用工具类.rar" 涉及的是Android应用程序开发中的一个关键方面——工具类的集合。在Android开发中,工具类通常包含一系列静态方法,用于执行常见的、重复...

    Android-AndroidStudio快速创建常用工具类的插件

    本篇文章将详细探讨“Android-AndroidStudio快速创建常用工具类的插件”,以及如何利用这个名为Utils_plugin-master的插件来提升开发效率。 首先,理解“工具类”在Android开发中的概念至关重要。工具类通常是一些...

    android 常用快速开发集成工具类

    这里提到的"android 常用快速开发集成工具类"就是这样的一个集合,它包含了在实际项目开发中可能会频繁使用的各种工具方法,帮助开发者快速实现功能,减少重复劳动。 这个工具类库可能包含以下几个方面的主要内容:...

    Android开发常用工具类

    在Android开发过程中,工具类(Utility Class)是开发者不可或缺的好帮手。它们通常包含一系列静态方法,用于执行特定任务,如日期时间处理、网络请求、数据解析等,从而提高代码的复用性和效率。以下是一些Android...

    Android快速开发9个常用工具类.zip

    "Android快速开发9个常用工具类.zip" 包含了九个这样的工具类,它们可能是Android开发者在日常工作中不可或缺的部分。下面将详细介绍这些工具类可能涉及的关键知识点。 1. **字符串处理工具类**:这类工具通常包含...

    Android快速开发系列 10个常用工具类 程序源码

    本资源"Android快速开发系列 10个常用工具类 程序源码"提供了10个实用的工具类,旨在帮助开发者更快捷地完成日常开发工作。以下是对这些工具类的详细解释: 1. **StringUtil**: 字符串处理工具类,包括字符串格式化...

    Android快速开发系列 10个常用工具类

    在这个"Android快速开发系列"中,我们将探讨10个非常实用的工具类,这些工具类可以帮助我们提高开发效率,优化代码结构。以下是每个工具类的核心知识点: 1. **StringUtil**: 这个工具类主要处理字符串操作,如格式...

    android开发必备工具类

    在Android开发过程中,工具类是不可或缺的一部分,它们可以极大地提高开发效率,简化代码,使得开发者能够更加专注于核心功能的实现。以下是一些Android开发中常用的工具类及其详细知识点: 1. **日志工具类**: -...

    Android快速开发不可或缺的11个工具类

    本文将深入探讨标题所提及的"Android快速开发不可或缺的11个工具类",帮助您更好地理解和运用这些工具。 1. **LogUtil**: 日志打印工具类 在Android开发中,日志是调试应用的重要手段。LogUtil封装了Android原生的...

    android快速开发最新工具类

    "android快速开发最新工具类"这个资源显然提供了一系列预构建的工具函数,涵盖了网络操作、内存卡读写、CPU信息获取以及视频处理等多个方面。下面我们将详细探讨这些关键知识点。 1. **网络操作**: 在Android中,...

    安卓开发框架工具类相关-Android快速开发不可或缺的辅助类.rar

    "安卓开发框架工具类相关-Android快速开发不可或缺的辅助类.rar"这个压缩包文件很可能包含了多个这样的工具类,用于简化Android开发过程。下面将详细探讨Android开发中常用的工具类及其可能包含的功能。 1. **日期...

    实例详解Android快速开发工具类总结

    本篇将详细介绍两个常用的Android开发工具类:日志工具类(Log.java)和Toast统一管理类(Tost.java)。 一、日志工具类(Log.java) 在Android开发中,日志(Log)用于调试和跟踪应用程序运行时的信息,是开发者...

    android开发常用工具类utils精装集合

    在Android应用开发中,工具类Utils是不可或缺的一部分。它们通常包含了一系列静态方法,为开发者提供便利的功能,提高代码的复用性和可维护性。"android开发常用工具类utils精装集合"是一个专门针对Android开发者的...

Global site tag (gtag.js) - Google Analytics