欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android快速开发系列 10个常用工具类实例代码详解

程序员文章站 2023-12-04 20:31:52
打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~在此感谢群里给我发项目中工具类的兄弟/姐妹~ 1、日志工...

打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出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);
 }
}

网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到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也可以给大家创建兼容类提供了一定的参考~~

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

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

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

总结

以上所述是小编给大家介绍的android快速开发系列 10个常用工具类实例代码详解,希望对大家有所帮助