android 常用类
转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】
打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~
在此感谢群里给我发项目中工具类的兄弟/姐妹~
1、日志工具类L.java
- package com.zhy.utils;
- import android.util.Log;
- /**
- * Log统一管理类
- *
- *
- *
- */
- public class L
- {
- private L()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化
- private static final String TAG = "way";
- // 下面四个是默认tag的函数
- public static void i(String msg)
- {
- if (isDebug)
- Log.i(TAG, msg);
- }
- public static void d(String msg)
- {
- if (isDebug)
- Log.d(TAG, msg);
- }
- public static void e(String msg)
- {
- if (isDebug)
- Log.e(TAG, msg);
- }
- public static void v(String msg)
- {
- if (isDebug)
- Log.v(TAG, msg);
- }
- // 下面是传入自定义tag的函数
- public static void i(String tag, String msg)
- {
- if (isDebug)
- Log.i(tag, msg);
- }
- public static void d(String tag, String msg)
- {
- if (isDebug)
- Log.i(tag, msg);
- }
- public static void e(String tag, String msg)
- {
- if (isDebug)
- Log.i(tag, msg);
- }
- public static void v(String tag, String msg)
- {
- if (isDebug)
- Log.i(tag, msg);
- }
- }
package com.zhy.utils;import android.util.Log;/*** Log统一管理类* * * */
public class L
{private L(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化private static final String TAG = "way";// 下面四个是默认tag的函数public static void i(String msg){if (isDebug)Log.i(TAG, msg);}public static void d(String msg){if (isDebug)Log.d(TAG, msg);}public static void e(String msg){if (isDebug)Log.e(TAG, msg);}public static void v(String msg){if (isDebug)Log.v(TAG, msg);}// 下面是传入自定义tag的函数public static void i(String tag, String msg){if (isDebug)Log.i(tag, msg);}public static void d(String tag, String msg){if (isDebug)Log.i(tag, msg);}public static void e(String tag, String msg){if (isDebug)Log.i(tag, msg);}public static void v(String tag, String msg){if (isDebug)Log.i(tag, msg);}
}
网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~
2、Toast统一管理类
- package com.zhy.utils;
- import android.content.Context;
- import android.widget.Toast;
- /**
- * Toast统一管理类
- *
- */
- public class T
- {
- private T()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- public static boolean isShow = true;
- /**
- * 短时间显示Toast
- *
- * @param context
- * @param message
- */
- public static void showShort(Context context, CharSequence message)
- {
- if (isShow)
- Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
- }
- /**
- * 短时间显示Toast
- *
- * @param context
- * @param message
- */
- public static void showShort(Context context, int message)
- {
- if (isShow)
- Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
- }
- /**
- * 长时间显示Toast
- *
- * @param context
- * @param message
- */
- public static void showLong(Context context, CharSequence message)
- {
- if (isShow)
- Toast.makeText(context, message, Toast.LENGTH_LONG).show();
- }
- /**
- * 长时间显示Toast
- *
- * @param context
- * @param message
- */
- public static void showLong(Context context, int message)
- {
- if (isShow)
- Toast.makeText(context, message, Toast.LENGTH_LONG).show();
- }
- /**
- * 自定义显示Toast时间
- *
- * @param context
- * @param message
- * @param duration
- */
- public static void show(Context context, CharSequence message, int duration)
- {
- if (isShow)
- Toast.makeText(context, message, duration).show();
- }
- /**
- * 自定义显示Toast时间
- *
- * @param context
- * @param message
- * @param duration
- */
- public static void show(Context context, int message, int duration)
- {
- if (isShow)
- Toast.makeText(context, message, duration).show();
- }
- }
package com.zhy.utils;import android.content.Context;
import android.widget.Toast;/*** Toast统一管理类* */
public class T
{private T(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}public static boolean isShow = true;/*** 短时间显示Toast* * @param context* @param message*/public static void showShort(Context context, CharSequence message){if (isShow)Toast.makeText(context, message, Toast.LENGTH_SHORT).show();}/*** 短时间显示Toast* * @param context* @param message*/public static void showShort(Context context, int message){if (isShow)Toast.makeText(context, message, Toast.LENGTH_SHORT).show();}/*** 长时间显示Toast* * @param context* @param message*/public static void showLong(Context context, CharSequence message){if (isShow)Toast.makeText(context, message, Toast.LENGTH_LONG).show();}/*** 长时间显示Toast* * @param context* @param message*/public static void showLong(Context context, int message){if (isShow)Toast.makeText(context, message, Toast.LENGTH_LONG).show();}/*** 自定义显示Toast时间* * @param context* @param message* @param duration*/public static void show(Context context, CharSequence message, int duration){if (isShow)Toast.makeText(context, message, duration).show();}/*** 自定义显示Toast时间* * @param context* @param message* @param duration*/public static void show(Context context, int message, int duration){if (isShow)Toast.makeText(context, message, duration).show();}}
也是非常简单的一个封装,能省则省了~~
3、SharedPreferences封装类SPUtils
- package com.zhy.utils;
- 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";
- /**
- * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
- *
- * @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);
- }
- /**
- * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
- *
- * @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);
- }
- /**
- * 清除所有数据
- * @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();
- }
- }
- }
package com.zhy.utils;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";/*** 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法* * @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);}/*** 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值* * @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);}/*** 清除所有数据* @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();}}}
对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;
SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~
4、单位转换类 DensityUtils
- package com.zhy.utils;
- import android.content.Context;
- import android.util.TypedValue;
- /**
- * 常用单位转换的辅助类
- *
- *
- *
- */
- public class DensityUtils
- {
- private DensityUtils()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- /**
- * dp转px
- *
- * @param context
- * @param val
- * @return
- */
- public static int dp2px(Context context, float dpVal)
- {
- return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
- dpVal, context.getResources().getDisplayMetrics());
- }
- /**
- * sp转px
- *
- * @param context
- * @param val
- * @return
- */
- public static int sp2px(Context context, float spVal)
- {
- return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
- spVal, context.getResources().getDisplayMetrics());
- }
- /**
- * px转dp
- *
- * @param context
- * @param pxVal
- * @return
- */
- public static float px2dp(Context context, float pxVal)
- {
- final float scale = context.getResources().getDisplayMetrics().density;
- return (pxVal / scale);
- }
- /**
- * px转sp
- *
- * @param fontScale
- * @param pxVal
- * @return
- */
- public static float px2sp(Context context, float pxVal)
- {
- return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
- }
- }
package com.zhy.utils;import android.content.Context;
import android.util.TypedValue;/*** 常用单位转换的辅助类* * * */
public class DensityUtils
{private DensityUtils(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** dp转px* * @param context* @param val* @return*/public static int dp2px(Context context, float dpVal){return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal, context.getResources().getDisplayMetrics());}/*** sp转px* * @param context* @param val* @return*/public static int sp2px(Context context, float spVal){return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,spVal, context.getResources().getDisplayMetrics());}/*** px转dp* * @param context* @param pxVal* @return*/public static float px2dp(Context context, float pxVal){final float scale = context.getResources().getDisplayMetrics().density;return (pxVal / scale);}/*** px转sp* * @param fontScale* @param pxVal* @return*/public static float px2sp(Context context, float pxVal){return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);}}
5、SD卡相关辅助类 SDCardUtils
- package com.zhy.utils;
- import java.io.File;
- import android.os.Environment;
- import android.os.StatFs;
- /**
- * SD卡相关的辅助类
- *
- *
- *
- */
- public class SDCardUtils
- {
- private SDCardUtils()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- /**
- * 判断SDCard是否可用
- *
- * @return
- */
- public static boolean isSDCardEnable()
- {
- return Environment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED);
- }
- /**
- * 获取SD卡路径
- *
- * @return
- */
- public static String getSDCardPath()
- {
- return Environment.getExternalStorageDirectory().getAbsolutePath()
- + File.separator;
- }
- /**
- * 获取SD卡的剩余容量 单位byte
- *
- * @return
- */
- public static long getSDCardAllSize()
- {
- if (isSDCardEnable())
- {
- StatFs stat = new StatFs(getSDCardPath());
- // 获取空闲的数据块的数量
- long availableBlocks = (long) stat.getAvailableBlocks() - 4;
- // 获取单个数据块的大小(byte)
- long freeBlocks = stat.getAvailableBlocks();
- return freeBlocks * availableBlocks;
- }
- return 0;
- }
- /**
- * 获取指定路径所在空间的剩余可用容量字节数,单位byte
- *
- * @param filePath
- * @return 容量字节 SDCard可用空间,内部存储可用空间
- */
- public static long getFreeBytes(String filePath)
- {
- // 如果是sd卡的下的路径,则获取sd卡可用容量
- if (filePath.startsWith(getSDCardPath()))
- {
- filePath = getSDCardPath();
- } else
- {// 如果是内部存储的路径,则获取内存存储的可用容量
- filePath = Environment.getDataDirectory().getAbsolutePath();
- }
- StatFs stat = new StatFs(filePath);
- long availableBlocks = (long) stat.getAvailableBlocks() - 4;
- return stat.getBlockSize() * availableBlocks;
- }
- /**
- * 获取系统存储路径
- *
- * @return
- */
- public static String getRootDirectoryPath()
- {
- return Environment.getRootDirectory().getAbsolutePath();
- }
- }
package com.zhy.utils;import java.io.File;import android.os.Environment;
import android.os.StatFs;/*** SD卡相关的辅助类* * * */
public class SDCardUtils
{private SDCardUtils(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** 判断SDCard是否可用* * @return*/public static boolean isSDCardEnable(){return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);}/*** 获取SD卡路径* * @return*/public static String getSDCardPath(){return Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator;}/*** 获取SD卡的剩余容量 单位byte* * @return*/public static long getSDCardAllSize(){if (isSDCardEnable()){StatFs stat = new StatFs(getSDCardPath());// 获取空闲的数据块的数量long availableBlocks = (long) stat.getAvailableBlocks() - 4;// 获取单个数据块的大小(byte)long freeBlocks = stat.getAvailableBlocks();return freeBlocks * availableBlocks;}return 0;}/*** 获取指定路径所在空间的剩余可用容量字节数,单位byte* * @param filePath* @return 容量字节 SDCard可用空间,内部存储可用空间*/public static long getFreeBytes(String filePath){// 如果是sd卡的下的路径,则获取sd卡可用容量if (filePath.startsWith(getSDCardPath())){filePath = getSDCardPath();} else{// 如果是内部存储的路径,则获取内存存储的可用容量filePath = Environment.getDataDirectory().getAbsolutePath();}StatFs stat = new StatFs(filePath);long availableBlocks = (long) stat.getAvailableBlocks() - 4;return stat.getBlockSize() * availableBlocks;}/*** 获取系统存储路径* * @return*/public static String getRootDirectoryPath(){return Environment.getRootDirectory().getAbsolutePath();}}
6、屏幕相关辅助类 ScreenUtils
- package com.zhy.utils;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Rect;
- import android.util.DisplayMetrics;
- import android.view.View;
- import android.view.WindowManager;
- /**
- * 获得屏幕相关的辅助类
- *
- *
- *
- */
- public class ScreenUtils
- {
- private ScreenUtils()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- /**
- * 获得屏幕高度
- *
- * @param context
- * @return
- */
- public static int getScreenWidth(Context context)
- {
- WindowManager wm = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- DisplayMetrics outMetrics = new DisplayMetrics();
- wm.getDefaultDisplay().getMetrics(outMetrics);
- return outMetrics.widthPixels;
- }
- /**
- * 获得屏幕宽度
- *
- * @param context
- * @return
- */
- public static int getScreenHeight(Context context)
- {
- WindowManager wm = (WindowManager) context
- .getSystemService(Context.WINDOW_SERVICE);
- DisplayMetrics outMetrics = new DisplayMetrics();
- wm.getDefaultDisplay().getMetrics(outMetrics);
- return outMetrics.heightPixels;
- }
- /**
- * 获得状态栏的高度
- *
- * @param context
- * @return
- */
- public static int getStatusHeight(Context context)
- {
- int statusHeight = -1;
- try
- {
- Class<?> clazz = Class.forName("com.android.internal.R$dimen");
- Object object = clazz.newInstance();
- int height = Integer.parseInt(clazz.getField("status_bar_height")
- .get(object).toString());
- statusHeight = context.getResources().getDimensionPixelSize(height);
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- return statusHeight;
- }
- /**
- * 获取当前屏幕截图,包含状态栏
- *
- * @param activity
- * @return
- */
- public static Bitmap snapShotWithStatusBar(Activity activity)
- {
- View view = activity.getWindow().getDecorView();
- view.setDrawingCacheEnabled(true);
- view.buildDrawingCache();
- Bitmap bmp = view.getDrawingCache();
- int width = getScreenWidth(activity);
- int height = getScreenHeight(activity);
- Bitmap bp = null;
- bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
- view.destroyDrawingCache();
- return bp;
- }
- /**
- * 获取当前屏幕截图,不包含状态栏
- *
- * @param activity
- * @return
- */
- public static Bitmap snapShotWithoutStatusBar(Activity activity)
- {
- View view = activity.getWindow().getDecorView();
- view.setDrawingCacheEnabled(true);
- view.buildDrawingCache();
- Bitmap bmp = view.getDrawingCache();
- Rect frame = new Rect();
- activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- int statusBarHeight = frame.top;
- int width = getScreenWidth(activity);
- int height = getScreenHeight(activity);
- Bitmap bp = null;
- bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- - statusBarHeight);
- view.destroyDrawingCache();
- return bp;
- }
- }
package com.zhy.utils;import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;/*** 获得屏幕相关的辅助类* * * */
public class ScreenUtils
{private ScreenUtils(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** 获得屏幕高度* * @param context* @return*/public static int getScreenWidth(Context context){WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(outMetrics);return outMetrics.widthPixels;}/*** 获得屏幕宽度* * @param context* @return*/public static int getScreenHeight(Context context){WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics outMetrics = new DisplayMetrics();wm.getDefaultDisplay().getMetrics(outMetrics);return outMetrics.heightPixels;}/*** 获得状态栏的高度* * @param context* @return*/public static int getStatusHeight(Context context){int statusHeight = -1;try{Class<?> clazz = Class.forName("com.android.internal.R$dimen");Object object = clazz.newInstance();int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());statusHeight = context.getResources().getDimensionPixelSize(height);} catch (Exception e){e.printStackTrace();}return statusHeight;}/*** 获取当前屏幕截图,包含状态栏* * @param activity* @return*/public static Bitmap snapShotWithStatusBar(Activity activity){View view = activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bmp = view.getDrawingCache();int width = getScreenWidth(activity);int height = getScreenHeight(activity);Bitmap bp = null;bp = Bitmap.createBitmap(bmp, 0, 0, width, height);view.destroyDrawingCache();return bp;}/*** 获取当前屏幕截图,不包含状态栏* * @param activity* @return*/public static Bitmap snapShotWithoutStatusBar(Activity activity){View view = activity.getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap bmp = view.getDrawingCache();Rect frame = new Rect();activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight = frame.top;int width = getScreenWidth(activity);int height = getScreenHeight(activity);Bitmap bp = null;bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height- statusBarHeight);view.destroyDrawingCache();return bp;}}
7、App相关辅助类
- package com.zhy.utils;
- import android.content.Context;
- import android.content.pm.PackageInfo;
- import android.content.pm.PackageManager;
- import android.content.pm.PackageManager.NameNotFoundException;
- /**
- * 跟App相关的辅助类
- *
- *
- *
- */
- public class AppUtils
- {
- private AppUtils()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- /**
- * 获取应用程序名称
- */
- public static String getAppName(Context context)
- {
- try
- {
- PackageManager packageManager = context.getPackageManager();
- PackageInfo packageInfo = packageManager.getPackageInfo(
- context.getPackageName(), 0);
- int labelRes = packageInfo.applicationInfo.labelRes;
- return context.getResources().getString(labelRes);
- } catch (NameNotFoundException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * [获取应用程序版本名称信息]
- *
- * @param context
- * @return 当前应用的版本名称
- */
- public static String getVersionName(Context context)
- {
- try
- {
- PackageManager packageManager = context.getPackageManager();
- PackageInfo packageInfo = packageManager.getPackageInfo(
- context.getPackageName(), 0);
- return packageInfo.versionName;
- } catch (NameNotFoundException e)
- {
- e.printStackTrace();
- }
- return null;
- }
- }
package com.zhy.utils;import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;/*** 跟App相关的辅助类* * * */
public class AppUtils
{private AppUtils(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** 获取应用程序名称*/public static String getAppName(Context context){try{PackageManager packageManager = context.getPackageManager();PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);int labelRes = packageInfo.applicationInfo.labelRes;return context.getResources().getString(labelRes);} catch (NameNotFoundException e){e.printStackTrace();}return null;}/*** [获取应用程序版本名称信息]* * @param context* @return 当前应用的版本名称*/public static String getVersionName(Context context){try{PackageManager packageManager = context.getPackageManager();PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);return packageInfo.versionName;} catch (NameNotFoundException e){e.printStackTrace();}return null;}}
8、软键盘相关辅助类KeyBoardUtils
- package com.zhy.utils;
- import android.content.Context;
- import android.view.inputmethod.InputMethodManager;
- import android.widget.EditText;
- /**
- * 打开或关闭软键盘
- *
- * @author zhy
- *
- */
- public class KeyBoardUtils
- {
- /**
- * 打卡软键盘
- *
- * @param mEditText
- * 输入框
- * @param mContext
- * 上下文
- */
- public static void openKeybord(EditText mEditText, Context mContext)
- {
- InputMethodManager imm = (InputMethodManager) mContext
- .getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
- imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
- InputMethodManager.HIDE_IMPLICIT_ONLY);
- }
- /**
- * 关闭软键盘
- *
- * @param mEditText
- * 输入框
- * @param mContext
- * 上下文
- */
- public static void closeKeybord(EditText mEditText, Context mContext)
- {
- InputMethodManager imm = (InputMethodManager) mContext
- .getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
- }
- }
package com.zhy.utils;import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;/*** 打开或关闭软键盘* * @author zhy* */
public class KeyBoardUtils
{/*** 打卡软键盘* * @param mEditText* 输入框* @param mContext* 上下文*/public static void openKeybord(EditText mEditText, Context mContext){InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);}/*** 关闭软键盘* * @param mEditText* 输入框* @param mContext* 上下文*/public static void closeKeybord(EditText mEditText, Context mContext){InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);}
}
9、网络相关辅助类 NetUtils
- package com.zhy.utils;
- import android.app.Activity;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- /**
- * 跟网络相关的工具类
- *
- *
- *
- */
- public class NetUtils
- {
- private NetUtils()
- {
- /* cannot be instantiated */
- throw new UnsupportedOperationException("cannot be instantiated");
- }
- /**
- * 判断网络是否连接
- *
- * @param context
- * @return
- */
- public static boolean isConnected(Context context)
- {
- ConnectivityManager connectivity = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (null != connectivity)
- {
- NetworkInfo info = connectivity.getActiveNetworkInfo();
- if (null != info && info.isConnected())
- {
- if (info.getState() == NetworkInfo.State.CONNECTED)
- {
- return true;
- }
- }
- }
- return false;
- }
- /**
- * 判断是否是wifi连接
- */
- public static boolean isWifi(Context context)
- {
- ConnectivityManager cm = (ConnectivityManager) context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if (cm == null)
- return false;
- return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;
- }
- /**
- * 打开网络设置界面
- */
- public static void openSetting(Activity activity)
- {
- Intent intent = new Intent("/");
- ComponentName cm = new ComponentName("com.android.settings",
- "com.android.settings.WirelessSettings");
- intent.setComponent(cm);
- intent.setAction("android.intent.action.VIEW");
- activity.startActivityForResult(intent, 0);
- }
- }
package com.zhy.utils;import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;/*** 跟网络相关的工具类* * * */
public class NetUtils
{private NetUtils(){/* cannot be instantiated */throw new UnsupportedOperationException("cannot be instantiated");}/*** 判断网络是否连接* * @param context* @return*/public static boolean isConnected(Context context){ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (null != connectivity){NetworkInfo info = connectivity.getActiveNetworkInfo();if (null != info && info.isConnected()){if (info.getState() == NetworkInfo.State.CONNECTED){return true;}}}return false;}/*** 判断是否是wifi连接*/public static boolean isWifi(Context context){ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);if (cm == null)return false;return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;}/*** 打开网络设置界面*/public static void openSetting(Activity activity){Intent intent = new Intent("/");ComponentName cm = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");intent.setComponent(cm);intent.setAction("android.intent.action.VIEW");activity.startActivityForResult(intent, 0);}}
10、Http相关辅助类 HttpUtils
- package com.zhy.utils;
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- /**
- * Http请求的工具类
- *
- * @author zhy
- *
- */
- public class HttpUtils
- {
- private static final int TIMEOUT_IN_MILLIONS = 5000;
- public interface CallBack
- {
- void onRequestComplete(String result);
- }
- /**
- * 异步的Get请求
- *
- * @param urlStr
- * @param callBack
- */
- public static void doGetAsyn(final String urlStr, final CallBack callBack)
- {
- new Thread()
- {
- public void run()
- {
- try
- {
- String result = doGet(urlStr);
- if (callBack != null)
- {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- * 异步的Post请求
- * @param urlStr
- * @param params
- * @param callBack
- * @throws Exception
- */
- public static void doPostAsyn(final String urlStr, final String params,
- final CallBack callBack) throws Exception
- {
- new Thread()
- {
- public void run()
- {
- try
- {
- String result = doPost(urlStr, params);
- if (callBack != null)
- {
- callBack.onRequestComplete(result);
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- * Get请求,获得返回数据
- *
- * @param urlStr
- * @return
- * @throws Exception
- */
- public static String doGet(String urlStr)
- {
- URL url = null;
- HttpURLConnection conn = null;
- InputStream is = null;
- ByteArrayOutputStream baos = null;
- try
- {
- url = new URL(urlStr);
- conn = (HttpURLConnection) url.openConnection();
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- if (conn.getResponseCode() == 200)
- {
- is = conn.getInputStream();
- baos = new ByteArrayOutputStream();
- int len = -1;
- byte[] buf = new byte[128];
- while ((len = is.read(buf)) != -1)
- {
- baos.write(buf, 0, len);
- }
- baos.flush();
- return baos.toString();
- } else
- {
- throw new RuntimeException(" responseCode is not 200 ... ");
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- } finally
- {
- try
- {
- if (is != null)
- is.close();
- } catch (IOException e)
- {
- }
- try
- {
- if (baos != null)
- baos.close();
- } catch (IOException e)
- {
- }
- conn.disconnect();
- }
- return null ;
- }
- /**
- * 向指定 URL 发送POST方法的请求
- *
- * @param url
- * 发送请求的 URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return 所代表远程资源的响应结果
- * @throws Exception
- */
- public static String doPost(String url, String param)
- {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try
- {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- HttpURLConnection conn = (HttpURLConnection) realUrl
- .openConnection();
- // 设置通用的请求属性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setRequestProperty("charset", "utf-8");
- conn.setUseCaches(false);
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- if (param != null && !param.trim().equals(""))
- {
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(conn.getOutputStream());
- // 发送请求参数
- out.print(param);
- // flush输出流的缓冲
- out.flush();
- }
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(
- new InputStreamReader(conn.getInputStream()));
- String line;
- while ((line = in.readLine()) != null)
- {
- result += line;
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally
- {
- try
- {
- if (out != null)
- {
- out.close();
- }
- if (in != null)
- {
- in.close();
- }
- } catch (IOException ex)
- {
- ex.printStackTrace();
- }
- }
- return result;
- }
- }
package com.zhy.utils;import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;/*** Http请求的工具类* * @author zhy* */
public class HttpUtils
{private static final int TIMEOUT_IN_MILLIONS = 5000;public interface CallBack{void onRequestComplete(String result);}/*** 异步的Get请求* * @param urlStr* @param callBack*/public static void doGetAsyn(final String urlStr, final CallBack callBack){new Thread(){public void run(){try{String result = doGet(urlStr);if (callBack != null){callBack.onRequestComplete(result);}} catch (Exception e){e.printStackTrace();}};}.start();}/*** 异步的Post请求* @param urlStr* @param params* @param callBack* @throws Exception*/public static void doPostAsyn(final String urlStr, final String params,final CallBack callBack) throws Exception{new Thread(){public void run(){try{String result = doPost(urlStr, params);if (callBack != null){callBack.onRequestComplete(result);}} catch (Exception e){e.printStackTrace();}};}.start();}/*** Get请求,获得返回数据* * @param urlStr* @return* @throws Exception*/public static String doGet(String urlStr) {URL url = null;HttpURLConnection conn = null;InputStream is = null;ByteArrayOutputStream baos = null;try{url = new URL(urlStr);conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(TIMEOUT_IN_MILLIONS);conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);conn.setRequestMethod("GET");conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");if (conn.getResponseCode() == 200){is = conn.getInputStream();baos = new ByteArrayOutputStream();int len = -1;byte[] buf = new byte[128];while ((len = is.read(buf)) != -1){baos.write(buf, 0, len);}baos.flush();return baos.toString();} else{throw new RuntimeException(" responseCode is not 200 ... ");}} catch (Exception e){e.printStackTrace();} finally{try{if (is != null)is.close();} catch (IOException e){}try{if (baos != null)baos.close();} catch (IOException e){}conn.disconnect();}return null ;}/*** 向指定 URL 发送POST方法的请求* * @param url* 发送请求的 URL* @param param* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。* @return 所代表远程资源的响应结果* @throws Exception*/public static String doPost(String url, String param) {PrintWriter out = null;BufferedReader in = null;String result = "";try{URL realUrl = new URL(url);// 打开和URL之间的连接HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();// 设置通用的请求属性conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("charset", "utf-8");conn.setUseCaches(false);// 发送POST请求必须设置如下两行conn.setDoOutput(true);conn.setDoInput(true);conn.setReadTimeout(TIMEOUT_IN_MILLIONS);conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);if (param != null && !param.trim().equals("")){// 获取URLConnection对象对应的输出流out = new PrintWriter(conn.getOutputStream());// 发送请求参数out.print(param);// flush输出流的缓冲out.flush();}// 定义BufferedReader输入流来读取URL的响应in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null){result += line;}} catch (Exception e){e.printStackTrace();}// 使用finally块来关闭输出流、输入流finally{try{if (out != null){out.close();}if (in != null){in.close();}} catch (IOException ex){ex.printStackTrace();}}return result;}
}
如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~
关注
评价
分享
赞
- 更多
转载于:https://www.cnblogs.com/lzjsky/p/5068781.html
android 常用类相关推荐
- Android常用的工具类
2019独角兽企业重金招聘Python工程师标准>>> 最新最准确内容建议直接访问原文:Android常用的工具类 主要介绍总结的Android开发中常用的工具类,大部分同样适用于J ...
- android工具类怎么写,用kotlin写了一些android常用的一些工具类
最近在学习kotlin语言,写了一些android常用的工具类 FileUtils.kt 文件操作类 创建多级文件目录 mkDir(dirPath: String) 创建文件 creatFile(fi ...
- android app初始化sdk,Android SDK使用系列教程——2.SDK初始化和常用类介绍
本帖最后由 碎羽 于 2015-6-18 11:36 编辑 上次讲到SDK的下载和导入,这次来讲讲SDK的初始化和常用类的介绍. 一.初始化SDK 初始化SDK,首先要获得对应设备的AppID.App ...
- Android 常用工具类转换
Android 常用单位转换的工具类 1. 常用单位转换的工具类 /*** 常用单位转换的工具类*/ public class ViewUtil {private ViewUtil() {/** ca ...
- android控件常用的属性,android?常用的控件属性
1.Android RelativeLayout 属性 // 相对于给定ID控件 android:layout_above 将该控件的底部置于给定ID的控件之上; android:layout_bel ...
- android AtomicBoolean类的使用
今天,简洁讲讲如何使用 AtomicBoolean这个类. 类 在java.util.concurrent.atomic包下,有AtomicBoolean , AtomicInteger, At ...
- 清零 css,css样式清零及常用类
/*css样式清零及常用类*/@charset "utf-8";/*CSS Reset*/ /*"微软雅黑","5FAE8F6F96C59ED1&qu ...
- java 参数代替所有类_Java中的常用类
1 常用类NO13 [ Int Interger short Short byte Byte double Double float Float Boolean Boolea ...
- Android Canvas类介绍和Android Draw Rect 坐标图示
当我们调整好画笔之后,现在需要绘制到画布上,这就得用Canvas类了.在Android中既然把Canvas当做画布,那么就可以在画布上绘制我们想要的任何东西.除了在画布上绘制之外,还需要设置一些关于画 ...
最新文章
- 大型云原生项目在数字化企业落地过程解密
- 美图秀秀web开发文档
- 阿里云物模型层功能分析
- bzoj1684[Usaco2005 Oct]Close Encounter*
- SAP Spartacus单元测试里Component实例的创建细节
- c++三维静态数组的定义与作为函数的传递
- 02.改善深层神经网络:超参数调试、正则化以及优化 W3. 超参数调试、Batch Norm和程序框架(作业:TensorFlow教程+数字手势预测)
- 7、JsonCpp简单使用(3)
- java多线程编程_Java多线程编程
- 苹果AR/VR头显将通过Memojis和SharePlay支持FaceTime
- 此“小霸王”非彼小霸王?官方声明:小霸王并未破产!
- Atitit 颜色平均值cloor grb hsv模式的区别对比
- 支持iphone的打印服务器,无需购买WiFi打印机,实现电脑、iPad、iPhone共享无线打印...
- 验证码错误的可能问题
- 深度学习在文本分类中的应用
- asp:DropDownList动态绑定数据,设置默认值
- [java] POI shiftRows 移动后合并的单元格被拆分了
- 随机森林(Random Forest)算法原理
- 【Python】【小明爬楼梯】
- 三国——CEO PK 孟德 2010-10-23
热门文章
- Linux中pthread源码在哪,pthread - 源码下载|系统编程|Linux/Unix编程|源代码 - 源码中国...
- win10解决Mysql net start mysql启动,提示发生系统错误 5 拒绝访问
- 文件操作03——图片文件合成器
- 对于插入和删除数据越频繁的操作 ,单链表较顺序存储结构效率越有优势
- html5画布画点,在HTML5画布上绘制一个点
- php多维数组打印出最长的数组,将php中的多维数组打印到html表中
- linux centos7如何格式化磁盘,Linux CentOS 7 磁盘格式化mke2fs、mkfs.ext4、磁盘挂载及手动增加swap空间...
- oraclf 复杂查询练习_刷完这些烧脑的SQL练习题,复杂查询才能熟能生巧
- java调用天气预报api_java调用中国天气网api获得天气预报信息
- mysql handler socket_MySQL的NoSQL插件HandlerSocket