打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~
在此感谢群里给我发项目中工具类的兄弟/姐妹~
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)
log.d(tag, msg);
public static void e(string msg)
log.e(tag, msg);
public static void v(string msg)
log.v(tag, msg);
// 下面是传入自定义tag的函数
public static void i(string tag, string msg)
public static void d(string tag, string msg)
public static void e(string tag, string msg)
public static void v(string tag, string msg)
}
网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到sdcard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~
import android.content.context;
import android.widget.toast;
* toast统一管理类
public class t
private t()
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();
public static void showshort(context context, int message)
* 长时间显示toast
public static void showlong(context context, charsequence message)
toast.maketext(context, message, toast.length_long).show();
public static void showlong(context context, int message)
* 自定义显示toast时间
* @param duration
public static void show(context context, charsequence message, int duration)
toast.maketext(context, message, duration).show();
public static void show(context context, int message, int duration)
也是非常简单的一个封装,能省则省了~~
import java.lang.reflect.invocationtargetexception;
import java.lang.reflect.method;
import java.util.map;
import android.content.sharedpreferences;
public class sputils
* 保存在手机里面的文件名
public static final string file_name = "share_data";
* 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
* @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 defaultobject
* @return
public static object get(context context, string key, object defaultobject)
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值已经对应的值
public static void remove(context context, string key)
editor.remove(key);
* 清除所有数据
public static void clear(context context)
editor.clear();
* 查询某个key是否已经存在
public static boolean contains(context context, string key)
return sp.contains(key);
* 返回所有的键值对
public static map<string, ?> getall(context context)
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)
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也可以给大家创建兼容类提供了一定的参考~~
import android.util.typedvalue;
* 常用单位转换的辅助类
public class densityutils
private densityutils()
* dp转px
* @param val
public static int dp2px(context context, float dpval)
return (int) typedvalue.applydimension(typedvalue.complex_unit_dip,
dpval, context.getresources().getdisplaymetrics());
* sp转px
public static int sp2px(context context, float spval)
return (int) typedvalue.applydimension(typedvalue.complex_unit_sp,
spval, context.getresources().getdisplaymetrics());
* px转dp
* @param pxval
public static float px2dp(context context, float pxval)
final float scale = context.getresources().getdisplaymetrics().density;
return (pxval / scale);
* px转sp
* @param fontscale
public static float px2sp(context context, float pxval)
return (pxval / context.getresources().getdisplaymetrics().scaleddensity);
import java.io.file;
import android.os.environment;
import android.os.statfs;
* sd卡相关的辅助类
public class sdcardutils
private sdcardutils()
* 判断sdcard是否可用
public static boolean issdcardenable()
return environment.getexternalstoragestate().equals(
environment.media_mounted);
* 获取sd卡路径
public static string getsdcardpath()
return environment.getexternalstoragedirectory().getabsolutepath()
+ file.separator;
* 获取sd卡的剩余容量 单位byte
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();
{// 如果是内部存储的路径,则获取内存存储的可用容量
filepath = environment.getdatadirectory().getabsolutepath();
statfs stat = new statfs(filepath);
long availableblocks = (long) stat.getavailableblocks() - 4;
return stat.getblocksize() * availableblocks;
* 获取系统存储路径
public static string getrootdirectorypath()
return environment.getrootdirectory().getabsolutepath();
import android.app.activity;
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()
* 获得屏幕高度
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;
* 获得屏幕宽度
public static int getscreenheight(context context)
return outmetrics.heightpixels;
* 获得状态栏的高度
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
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;
* 获取当前屏幕截图,不包含状态栏
public static bitmap snapshotwithoutstatusbar(activity activity)
rect frame = new rect();
activity.getwindow().getdecorview().getwindowvisibledisplayframe(frame);
int statusbarheight = frame.top;
bp = bitmap.createbitmap(bmp, 0, statusbarheight, width, height
- statusbarheight);
import android.content.pm.packageinfo;
import android.content.pm.packagemanager;
import android.content.pm.packagemanager.namenotfoundexception;
* 跟app相关的辅助类
public class apputils
private apputils()
* 获取应用程序名称
public static string getappname(context context)
packagemanager packagemanager = context.getpackagemanager();
packageinfo packageinfo = packagemanager.getpackageinfo(
context.getpackagename(), 0);
int labelres = packageinfo.applicationinfo.labelres;
return context.getresources().getstring(labelres);
} catch (namenotfoundexception e)
* [获取应用程序版本名称信息]
* @return 当前应用的版本名称
public static string getversionname(context context)
return packageinfo.versionname;
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);
* 关闭软键盘
public static void closekeybord(edittext medittext, context mcontext)
imm.hidesoftinputfromwindow(medittext.getwindowtoken(), 0);
import android.content.componentname;
import android.content.intent;
import android.net.connectivitymanager;
import android.net.networkinfo;
* 跟网络相关的工具类
public class netutils
private netutils()
* 判断网络是否连接
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
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);
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请求的工具类
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 params
* @throws exception
public static void dopostasyn(final string urlstr, final string params,
final callback callback) throws exception
string result = dopost(urlstr, params);
* get请求,获得返回数据
public static string doget(string urlstr)
url url = null;
httpurlconnection conn = null;
inputstream is = null;
bytearrayoutputstream baos = null;
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 ... ");
} finally
if (is != null)
is.close();
} catch (ioexception e)
if (baos != null)
baos.close();
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 = "";
url realurl = new url(url);
// 打开和url之间的连接
httpurlconnection conn = (httpurlconnection) realurl
.openconnection();
// 设置通用的请求属性
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);
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;
// 使用finally块来关闭输出流、输入流
finally
if (out != null)
out.close();
if (in != null)
in.close();
} catch (ioexception ex)
ex.printstacktrace();
return result;
如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~
<a target="_blank" href="http://download.csdn.net/detail/lmj623565791/7869487">源码点击下载</a>