转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311

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);
}
}

网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到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();
} }

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

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();
}
} }

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

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

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

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

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

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

 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();
} }

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; } }

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;
} }

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);
}
}

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);
} }

Android 工具类大全的更多相关文章

  1. 【Android 工具类】经常使用工具类(方法)大全

    收集经常使用的工具类或者方法: 1.获取手机分辨率 /** * 获取手机分辨率 */ public static String getDisplayMetrix(Context context) { ...

  2. [Android Pro] 常用的android工具类和库

    reference to  : http://blog.csdn.net/lovexieyuan520/article/details/50614086 这篇博客主要记录我认为比较有用的Android ...

  3. 摘录android工具类

    import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.Pac ...

  4. android 工具类 数据库管理

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/xuduzhoud/article/details/27540301 数据库工具类,优雅的管理andr ...

  5. Android工具类整合

    Android-JSONUtil工具类 常用的Json工具类,包含Json转换成实体.实体转json字符串.list集合转换成json.数组转换成json public class JSONUtil ...

  6. android 工具类之SharePreference

    /** * SharedPreferences的一个工具类,调用setParam就能保存String, Integer, Boolean, Float, Long类型的参数 * 同样调用getPara ...

  7. 对象属性拷贝工具类大全==>Bean的属性拷贝从此不用愁

    大家在做java开发时,肯定会遇到api层参数对象传递给服务层,或者把service层的对象传递给dao层,他们之间又不是同一个类型对象,但字段又是一样,如果还是用普通的get.set方式来处理话,比 ...

  8. Java Utils工具类大全(转)

    源码和jar见:https://github.com/evil0ps/utils #Java Utils --- 封装了一些常用Java操作方法,便于重复开发利用. 另外希望身为Java牛牛的你们一起 ...

  9. android 工具类 DateUtil

    提取了一些在开发过程中可能会用到的日期相关的函数作为工具类.供大家參考: /** * 日期操作工具类. * * @author shimiso */ public class DateUtil { p ...

随机推荐

  1. SWFUpload初体验 For Struts1.x

    SWFUpload是一个客户端文件上传工具,最初由Vinterwebb.se开发,它通过整合Flash与JavaScript技术为WEB开发者提供了一个具有丰富功能继而超越传统<input ty ...

  2. Struts2 配置Action详解

     Struts2的核心功能是action,对于开发人员来说,使用Struts2主要就是编写action,action类通常都要实现com.opensymphony.xwork2.Action接口,并实 ...

  3. 拼接sql

    String whereArgs = taskTable + " where 1=1 "; if (upCheck) { whereArgs += " and type ...

  4. Camera & Render

    1.void Render(); Description Render the camera manually. This will render the camera. It will use th ...

  5. render组件

    [render组件] Render继承于Component. It contians general functionality for all renderers. A renderer is wh ...

  6. 编码总结,以及对BOM的理解

    一.前言 在跨平台.跨操作系统或者跨区域之间,经常会涉及到编码的问题,因为前段时间在项目中,遇到了因为编码而产生乱码的问题,以前对编码也是一知半解,所以决定对编码有一个更为深入的了解,因此才有了这篇自 ...

  7. 详解C++右值引用

    C++0x标准出来很长时间了,引入了很多牛逼的特性[1].其中一个便是右值引用,Thomas Becker的文章[2]很全面的介绍了这个特性,读后有如醍醐灌顶,翻译在此以便深入理解. 目录 概述 mo ...

  8. 在子页面使用layer弹出层时只显示遮罩层,不显示弹出框问题

    最近子页面使用layer弹出层时只显示遮罩层,不显示弹出框,这个问题搞了很久,最后才发现,在子页面上使用弹出框时,如果只使用layer.alert()或者layer.open()时,会默认在当前页面弹 ...

  9. CSS外边距合并的几种情况

    CSS外边距合并的几种情况 外边距合并指的是,当两个垂直外边距相遇时,它们将形成一个外边距.合并后的外边距的高度等于两个发生合并的外边距的高度中的较大者. 外边距在CSS1中就有 The width ...

  10. Red Hat 6.5 Samba服务器的搭建(登录访问)

    搭建Samba服务器是为了实现Linux共享目录之后,在Windows可以直接访问该共享目录. 现在介绍如何在红帽6.5系统中搭建Samba服务. 搭建Samba服务之前,yum源必须配置好,本地源和 ...