Android 之常用工具类(后续)
来源:互联网 发布:虚荣 vgpro数据不准 编辑:程序博客网 时间:2024/05/22 16:43
- SharedPreferencesUtils 共享首选项
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.util.Base64;/** * * @author 作者:易皇星 * @da2016年9月23日 时间: @toTODO 类描述: */public class SharedPreferencesUtils { /** * 保存在手机里面的文件名 */ private static SharedPreferencesUtils mSpUtils; public static final String FILE_NAME = "share_data";private SharedPreferencesUtils (){}//提供单例 懒汉模式 线程安全 public static synchronized SharedPreferencesUtils getInstance(){ if(mSpUtils==null){ mSpUtils=new SharedPreferencesUtils(); } return mSpUtils; }/** * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法 * * @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()); } // 一定要提交 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); 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(); editor.commit(); } /** * 查询某个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(); } /** * 针对复杂类型存储<对象> * * @param key * @param object */ public static void saveObject(Context context,String key, Object object){ SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out=null; try { out=new ObjectOutputStream(baos); out.writeObject(object); String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT)); Editor editor = sp.edit(); editor.putString(key, objectVal); editor.commit(); } catch (Exception e) { // TODO: handle exception }finally{ try { if (baos != null) { baos.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * * 获取sp保存的对象 * @param key * @param clazz * @return */ public static <T> T getObject(Context context,String key, Class<T> cls){ SharedPreferences sp = context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE); if(sp.contains(key)){ String objectVal = sp.getString(key, null); byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT); ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = null; try { ois = new ObjectInputStream(bais); T t = (T) ois.readObject(); return t; } catch (Exception e) { // TODO: handle exception }finally{ try { if (bais != null) { bais.close(); } if (ois != null) { ois.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; }}
2.App相关辅助类 APPUtils.java
public class APPUtils { private APPUtils() { } /** * 获取应用程序名称 */ 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; }}
3.屏幕相关辅助类 ScreenUtils.java
public class ScreenUtils { private ScreenUtils() { } /** * 获得屏幕高度 * * @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; }}
4.软键盘相关辅助类KeyBoardUtils.java
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); }}
5.网络相关辅助类 NetUtils.java
public class NetUtils{ private NetUtils() { /* cannot be instantiated */ } /** * 判断网络是否连接 */ 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); }}
6.单例工具类 SingletonUtils.java
public abstract class SingletonUtils<T> { private T instance; protected abstract T newInstance(); public final T getInstance() { if (instance == null) { synchronized (SingletonUtils.class) { if (instance == null) { instance = newInstance(); } } } return instance; }}
7. 关于图片的BitmapUtils
private static Bitmap output;/** * 转换图片转换成圆角. * * @param bitmap * 传入Bitmap对象 * @return the bitmap */ public static Bitmap toRoundBitmap(Bitmap bitmap) { if (bitmap == null) { return null; } int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); return output; } /** * 将图片圆形化 * * @param bitmap * @return */ public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) { Bitmap output = null; if (bitmap != null) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); float roundPx; float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; if (width <= height) { roundPx = width / 2; top = 0; bottom = width; left = 0; right = width; height = width; dst_left = 0; dst_top = 0; dst_right = width; dst_bottom = width; } else { roundPx = height / 2; float clip = (width - height) / 2; left = clip; right = width - clip; top = 0; bottom = height; width = height; dst_left = 0; dst_top = 0; dst_right = height; dst_bottom = height; } output = Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(output); canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG)); final int color = 0xff424242; final Paint paint = new Paint(); final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom); final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom); final RectF rectF = new RectF(dst); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, src, dst, paint); bitmap = output; return bitmap; } output = null; return null; }
8.有关身份证验证CardUtils
private static String strYear; private static String strMonth; private static String strDay; private static String sex; /** * * 正则验证身份证是否有效 * * @param idCard 身份证号码 * @return */ public static boolean ifIdCard(String idCard){ String idCardReg="^(\\d{15}$|^\\d{18}$|^\\d{17}(\\d|X|x))$"; if(idCard.matches(idCardReg)){ return true; }else { return false; } }/** * * @param mesg 根据身份份证号获取生日 * @return */ public static String SetbirthDay(String mesg){ if(mesg!=null&&mesg!=""&& mesg.length()==18){ strYear = mesg.substring(6, 10); strMonth = mesg.substring(10, 12); strDay = mesg.substring(12, 14); } return strYear+"-"+strMonth+"-"+strDay; }/** * * @param mesg 根据身份证号获取性别 * @return */ public static String setSex(String mesg){ if(mesg!=null &&mesg!="" &&mesg.length()==18){ sex = mesg.substring(16, 17); } if(mesg!=null &&mesg!="" &&mesg.length()==18){ if(Integer.parseInt(sex)%2==0){ sex = "女"; }else{ sex ="男"; } } return sex; }
9。调用系统震动工具类:
import android.app.Activity;import android.app.Service;import android.content.Context;import android.os.Vibrator;/** * * * @author 易皇星 * @da2016年9月22日 @toTODO 调用系统震动 */public class VibratorUtil { /** * final Activity activity :调用该方法的Activity实例 * long milliseconds :震动的时长,单位是毫秒 * long[] pattern :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒 * boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次 */ public static void Vibrate(final Activity activity, long milliseconds) { Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(milliseconds); } /** * * * @param mContext * @param pattern long[] pattern = { 100, 400, 100, 400 }; * @param isRepeat 默认false */ public static void Vibrate(final Context mContext, long[] pattern,boolean isRepeat) { Vibrator vib = (Vibrator) mContext.getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(pattern, isRepeat ? 1 : -1); } }
10。发送验证码,随机产生的数字字符串工具类
import java.util.Random;/** * * * @author 作者:易皇星 * @da2016年9月23日 时间: @toTODO 类描述: 发送验证码,随机产生的数字字符串 */public class RandomUtils {/** * * @param length 产生多长的数字字符串 * @return */ public static String getRandomNumbers(int length){ Random mRandom=new Random(); StringBuffer sb=new StringBuffer(); for (int i = 0; i < length; i++) { //表示在0-9之间产生一个随机素 int number=mRandom.nextInt(10); sb.append(number); } String mandomNumber = sb.toString(); return mandomNumber; }}
11。 当输入框中的值为空少,设置友好晃动动画工具类
import android.view.animation.Animation;import android.view.animation.CycleInterpolator;import android.view.animation.TranslateAnimation;/** * * * @author 作者:易皇星 * @da2016年9月29日 时间: @toTODO 类描述: 设置晃动动画 */public class AnimationUtils { /** * 晃动动画 * * @param counts 1秒钟晃动多少下 * @return */ public static Animation shakeAnimation(int counts) { Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); return translateAnimation; }}
12。实现心跳的View工具类
import android.view.View;import android.view.animation.AccelerateInterpolator;import android.view.animation.AlphaAnimation;import android.view.animation.Animation;import android.view.animation.Animation.AnimationListener;import android.view.animation.AnimationSet;import android.view.animation.DecelerateInterpolator;import android.view.animation.ScaleAnimation;public class playHeartbeatAnimationUtils { private static final float ZOOM_MAX = 1.3f; private static final float ZOOM_MIN = 1.0f; /** * * @param view * 需要实现心跳的View */ public static void playHeartbeatAnimation(final View view) { /** * 放大动画 */ AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(ZOOM_MIN, ZOOM_MAX, ZOOM_MIN, ZOOM_MAX, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(1.0f, 0.8f)); animationSet.setDuration(500); animationSet.setInterpolator(new AccelerateInterpolator()); animationSet.setFillAfter(true); animationSet.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { /** * 缩小动画 */ AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(ZOOM_MAX, ZOOM_MIN, ZOOM_MAX, ZOOM_MIN, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(0.8f, 1.0f)); animationSet.setDuration(600); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setFillAfter(false); // 实现心跳的View view.startAnimation(animationSet); } }); // 实现心跳的View view.startAnimation(animationSet); }}
1 0
- Android 之常用工具类(后续)
- android之常用工具类
- android之常用工具类
- android开发之常用工具类
- Android常用工具类(收藏)
- Android常用工具类(收藏)
- Android常用工具类(收藏)
- Android常用工具类(一)
- Android常用工具类(收藏)
- Android常用工具类之 Toast工具类
- Android常用工具类之 Log工具类
- Android之10个常用工具类
- Android开发常用工具类之File操作
- Android开发常用工具类之图像处理
- Android开发常用工具类之图像处理
- Android开发常用工具类之File操作
- Android常用工具之Logutils
- Android常用工具之加密方式
- 输出一个数n的全排列
- 判断名称为name的session值是否已经设置 . session('?name');
- UIAPPEARANCE入门教程(上)
- Hello World
- socket/thread/core
- Android 之常用工具类(后续)
- UIAPPEARANCE入门教程(下)
- overflow知多少(转)
- Android开发技巧——大图裁剪
- Android 检查设备是否存在 导航栏 NavigationBar
- 经纬度坐标转换成屏幕坐标
- 0/1背包问题
- Untiy PoolManager随手记
- python中if __name__ == '__main__': 的解析