我是靠谱客的博主 受伤棉花糖,最近开发中收集的这篇文章主要介绍android 开发工具类,Android开发中常用到的工具类整理,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

原标题:Android开发中常用到的工具类整理

2018年 ,新的一年满血复活,新年总要有点新的东西,作为一个程序员界的新晋司机,也是时候整理一些东西了,两三年的路走来,代码也是边写边忘、边走边丢,很多问题忙着忙着就忘了,决定写点随笔供自己闲余时间回望,有需要的读者也可以随意瞄几眼,哪里有错有问题可以提出来,虽然我不见得会改,O(∩_∩)O哈哈~

日常开发中很多东西都是写过无数遍的,我本人没有每次都去重新写的习惯(不知道有没有小伙伴会如此耿直??)那么整理好自己的工具类还是有必要的。这里就记录几个目前为止我使用较多的。

常用工具类/** * 根据手机的分辨率从 dp 的单位 转成为 px(像素) */publicstaticintdip2px(Context context, floatdpValue){

finalfloatscale = context.getResources().getDisplayMetrics().density;

return( int) (dpValue * scale + 0.5f); }

/** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */publicstaticintpx2dip(Context context, floatpxValue){

finalfloatscale = context.getResources().getDisplayMetrics().density;

return( int) (pxValue / scale + 0.5f); }

/** * Md5 32位 or 16位 加密 * *@paramplainText *@return32位加密 */publicstaticString Md5(String plainText){ StringBuffer buf = null;

try{ MessageDigest md = MessageDigest.getInstance( "MD5"); md.update(plainText.getBytes());

byteb[] = md.digest();

inti; buf = newStringBuffer( "");

for( intoffset = 0; offset < b.length; offset++) { i = b[offset];

if(i < 0) i += 256;

if(i < 16) buf.append( "0"); buf.append(Integer.toHexString(i)); } } catch(NoSuchAlgorithmException e) { e.printStackTrace(); } returnbuf.toString(); }

/** * 手机号正则判断 *@paramstr *@return*@throwsPatternSyntaxException */publicstaticbooleanisPhoneNumber(String str)throwsPatternSyntaxException{

if(str != null) { String pattern = "(13d|14[579]|15[^4D]|17[^49D]|18d)d{8}"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(str);

returnm.matches(); } else{

returnfalse; } }

/** * 检测当前网络的类型 是否是wifi * *@paramcontext *@return*/publicstaticintcheckedNetWorkType(Context context){

if(!checkedNetWork(context)) {

return0; //无网络} ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) {

return1; //wifi} else{

return2; //非wifi} }

/** * 检查是否连接网络 * *@paramcontext *@return*/publicstaticbooleancheckedNetWork(Context context){

// 获得连接设备管理器ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if(cm == null) returnfalse; /** * 获取网络连接对象 */NetworkInfo networkInfo = cm.getActiveNetworkInfo();

if(networkInfo == null|| !networkInfo.isAvailable()) {

returnfalse; } returntrue; }

/** * 检测GPS是否打开 * *@return*/publicstaticbooleancheckGPSIsOpen(Context context){

booleanisOpen; LocationManager locationManager = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE);

if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)||locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ isOpen= true; } else{ isOpen = false; } returnisOpen; }

/** * 跳转GPS设置 */publicstaticvoidopenGPSSettings(finalContext context){

if(checkGPSIsOpen(context)) {

// initLocation(); //自己写的定位方法} else{ // //没有打开则弹出对话框AlertDialog.Builder builder = newAlertDialog.Builder(context, R.style.AlertDialogCustom); builder.setTitle( "温馨提示"); builder.setMessage( "当前应用需要打开定位功能。请点击"设置"-"定位服务"打开定位功能。");

//设置对话框是可取消的builder.setCancelable( false); builder.setPositiveButton( "设置", newDialogInterface.OnClickListener() {

@OverridepublicvoidonClick(DialogInterface dialogInterface, inti){ dialogInterface.dismiss(); //跳转GPS设置界面Intent intent = newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); context.startActivity(intent); } }); builder.setNegativeButton( "取消", newDialogInterface.OnClickListener() {

@OverridepublicvoidonClick(DialogInterface dialogInterface, inti){ dialogInterface.dismiss(); ActivityManager.getInstance().exit(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }

/** * 字符串进行Base64编码 *@paramstr */publicstaticString StringToBase64(String str){ String encodedString = Base64.encodeToString(str.getBytes(), Base64.DEFAULT);

returnencodedString; }

/** * 字符串进行Base64解码 *@paramencodedString *@return*/publicstaticString Base64ToString(String encodedString){ String decodedString = newString(Base64.decode(encodedString,Base64.DEFAULT));

returndecodedString; }

这里还有一个根据经纬度计算两点间真实距离的,一般都直接使用所集成第三方地图SDK中包含的方法,这里还是给出代码

/** * 补充:计算两点之间真实距离 * *@return米 */publicstaticdoublegetDistance(doublelongitude1, doublelatitude1, doublelongitude2, doublelatitude2){

// 维度doublelat1 = (Math.PI / 180) * latitude1;

doublelat2 = (Math.PI / 180) * latitude2;

// 经度doublelon1 = (Math.PI / 180) * longitude1;

doublelon2 = (Math.PI / 180) * longitude2;

// 地球半径doubleR = 6371;

// 两点间距离 km,如果想要米的话,结果*1000就可以了doubled = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)) * R;

returnd * 1000;

} 常用文件类

文件类的代码较多,这里就只给出读写文件的

/** * 判断SD卡是否可用 *@returnSD卡可用返回true */publicstaticbooleanhasSdcard(){ String status = Environment.getExternalStorageState();

returnEnvironment.MEDIA_MOUNTED.equals(status); }

/** * 读取文件的内容 *
* 默认utf-8编码 *@paramfilePath 文件路径 *@return字符串 *@throwsIOException */publicstaticString readFile(String filePath)throwsIOException{

returnreadFile(filePath, "utf-8"); }

/** * 读取文件的内容 *@paramfilePath 文件目录 *@paramcharsetName 字符编码 *@returnString字符串 */publicstaticString readFile(String filePath, String charsetName)throwsIOException{

if(TextUtils.isEmpty(filePath))

returnnull;

if(TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = newFile(filePath); StringBuilder fileContent = newStringBuilder( "");

if(file == null|| !file.isFile())

returnnull; BufferedReader reader = null;

try{ InputStreamReader is = newInputStreamReader( newFileInputStream( file), charsetName); reader = newBufferedReader(is); String line = null;

while((line = reader.readLine()) != null) {

if(!fileContent.toString().equals( "")) { fileContent.append( ""); } fileContent.append(line); }

returnfileContent.toString(); } finally{

if(reader != null) {

try{ reader.close(); } catch(IOException e) { e.printStackTrace(); } } } }

/** * 读取文本文件到List字符串集合中(默认utf-8编码) *@paramfilePath 文件目录 *@return文件不存在返回null,否则返回字符串集合 *@throwsIOException */publicstaticList readFileToList(String filePath)throwsIOException{

returnreadFileToList(filePath, "utf-8"); }

/** * 读取文本文件到List字符串集合中 *@paramfilePath 文件目录 *@paramcharsetName 字符编码 *@return文件不存在返回null,否则返回字符串集合 */publicstaticList readFileToList(String filePath, String charsetName)throwsIOException{

if(TextUtils.isEmpty(filePath))

returnnull; if(TextUtils.isEmpty(charsetName)) charsetName = "utf-8"; File file = newFile(filePath); List fileContent = newArrayList();

if(file == null|| !file.isFile()) {

returnnull; } BufferedReader reader = null;

try{ InputStreamReader is = newInputStreamReader( newFileInputStream( file), charsetName); reader = newBufferedReader(is); String line = null;

while((line = reader.readLine()) != null) { fileContent.add(line); }

returnfileContent; } finally{

if(reader != null) {

try{ reader.close(); } catch(IOException e) { e.printStackTrace(); } } } }

/** * 向文件中写入数据 *@paramfilePath 文件目录 *@paramcontent 要写入的内容 *@paramappend 如果为 true,则将数据写入文件末尾处,而不是写入文件开始处 *@return写入成功返回true, 写入失败返回false *@throwsIOException */publicstaticbooleanwriteFile(String filePath, String content,

booleanappend)throwsIOException {

if(TextUtils.isEmpty(filePath))

returnfalse;

if(TextUtils.isEmpty(content))

returnfalse; FileWriter fileWriter = null;

try{ createFile(filePath); fileWriter = newFileWriter(filePath, append); fileWriter.write(content); fileWriter.flush();

returntrue; } finally{

if(fileWriter != null) {

try{ fileWriter.close(); } catch(IOException e) { e.printStackTrace(); } } } }

/** * 向文件中写入数据
* 默认在文件开始处重新写入数据 *@paramfilePath 文件目录 *@paramstream 字节输入流 *@return写入成功返回true,否则返回false *@throwsIOException */publicstaticbooleanwriteFile(String filePath, InputStream stream)throwsIOException{

returnwriteFile(filePath, stream, false); }

/** * 向文件中写入数据 *@paramfilePath 文件目录 *@paramstream 字节输入流 *@paramappend 如果为 true,则将数据写入文件末尾处; * 为false时,清空原来的数据,从头开始写 *@return写入成功返回true,否则返回false *@throwsIOException */publicstaticbooleanwriteFile(String filePath, InputStream stream,

booleanappend)throwsIOException {

if(TextUtils.isEmpty(filePath))

thrownewNullPointerException("filePath is Empty");

if(stream == null)

thrownewNullPointerException("InputStream is null");

returnwriteFile(newFile(filePath), stream, append); }

/** * 向文件中写入数据 * 默认在文件开始处重新写入数据 *@paramfile 指定文件 *@paramstream 字节输入流 *@return写入成功返回true,否则返回false *@throwsIOException */publicstaticbooleanwriteFile(File file, InputStream stream)throwsIOException{

returnwriteFile(file, stream, false); }

/** * 向文件中写入数据 *@paramfile 指定文件 *@paramstream 字节输入流 *@paramappend 为true时,在文件开始处重新写入数据; * 为false时,清空原来的数据,从头开始写 *@return写入成功返回true,否则返回false *@throwsIOException */publicstaticbooleanwriteFile(File file, InputStream stream,

booleanappend)throwsIOException {

if(file == null)

thrownewNullPointerException("file = null"); OutputStream out = null;

try{ createFile(file.getAbsolutePath()); out = newFileOutputStream(file, append);

bytedata[] = newbyte[ 1024];

intlength = - 1;

while((length = stream.read(data)) != - 1) { out.write(data, 0, length); } out.flush();

returntrue; } finally{

if(out != null) {

try{ out.close(); stream.close(); } catch(IOException e) { e.printStackTrace(); } } } } 日期工具类

这个可是相当的常用啊

/** * 将long时间转成yyyy-MM-dd HH:mm:ss字符串
*@paramtimeInMillis 时间long值 *@returnyyyy-MM-dd HH:mm:ss */publicstaticString getDateTimeFromMillis(longtimeInMillis){

returngetDateTimeFormat(newDate(timeInMillis)); }

/** * 将date转成yyyy-MM-dd HH:mm:ss字符串 *
*@paramdate Date对象 *@returnyyyy-MM-dd HH:mm:ss */publicstaticString getDateTimeFormat(Date date){

returndateSimpleFormat(date, defaultDateTimeFormat.get()); }

/** * 将年月日的int转成yyyy-MM-dd的字符串 *@paramyear 年 *@parammonth 月 1-12 *@paramday 日 * 注:月表示Calendar的月,比实际小1 * 对输入项未做判断 */publicstaticString getDateFormat(intyear, intmonth, intday){

returngetDateFormat(getDate(year, month, day)); }

/** * 获得HH:mm:ss的时间 *@paramdate *@return*/publicstaticString getTimeFormat(Date date){

returndateSimpleFormat(date, defaultTimeFormat.get()); }

/** * 格式化日期显示格式 *@paramsdate 原始日期格式 "yyyy-MM-dd" *@paramformat 格式化后日期格式 *@return格式化后的日期显示 */publicstaticString dateFormat(String sdate, String format){ SimpleDateFormat formatter = newSimpleDateFormat(format); java.sql.Date date = java.sql.Date.valueOf(sdate);

returndateSimpleFormat(date, formatter); }

/** * 格式化日期显示格式 *@paramdate Date对象 *@paramformat 格式化后日期格式 *@return格式化后的日期显示 */publicstaticString dateFormat(Date date, String format){ SimpleDateFormat formatter = newSimpleDateFormat(format);

returndateSimpleFormat(date, formatter); }

/** * 将date转成字符串 *@paramdate Date *@paramformat SimpleDateFormat *
* 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式 *@returnyyyy-MM-dd HH:mm:ss */publicstaticString dateSimpleFormat(Date date, SimpleDateFormat format){

if(format == null) format = defaultDateTimeFormat.get();

return(date == null? "": format.format(date)); }

/** * 将"yyyy-MM-dd HH:mm:ss" 格式的字符串转成Date *@paramstrDate 时间字符串 *@returnDate */publicstaticDate getDateByDateTimeFormat(String strDate){

returngetDateByFormat(strDate, defaultDateTimeFormat.get()); }

/** * 将"yyyy-MM-dd" 格式的字符串转成Date *@paramstrDate *@returnDate */publicstaticDate getDateByDateFormat(String strDate){

returngetDateByFormat(strDate, defaultDateFormat.get()); }

/** * 将指定格式的时间字符串转成Date对象 *@paramstrDate 时间字符串 *@paramformat 格式化字符串 *@returnDate */publicstaticDate getDateByFormat(String strDate, String format){

returngetDateByFormat(strDate, newSimpleDateFormat(format)); }

/** * 将String字符串按照一定格式转成Date
* 注: SimpleDateFormat为空时,采用默认的yyyy-MM-dd HH:mm:ss格式 *@paramstrDate 时间字符串 *@paramformat SimpleDateFormat对象 *@exceptionParseException 日期格式转换出错 */privatestaticDate getDateByFormat(String strDate, SimpleDateFormat format){

if(format == null) format = defaultDateTimeFormat.get();

try{

returnformat.parse(strDate); } catch(ParseException e) { e.printStackTrace(); } returnnull; }

/** * 将年月日的int转成date *@paramyear 年 *@parammonth 月 1-12 *@paramday 日 * 注:月表示Calendar的月,比实际小1 */publicstaticDate getDate(intyear, intmonth, intday){ Calendar mCalendar = Calendar.getInstance(); mCalendar.set(year, month - 1, day);

returnmCalendar.getTime(); }

/** * 求两个日期相差天数 * *@paramstrat 起始日期,格式yyyy-MM-dd *@paramend 终止日期,格式yyyy-MM-dd *@return两个日期相差天数 */publicstaticlonggetIntervalDays(String strat, String end){

return((java.sql.Date.valueOf(end)).getTime() - (java.sql.Date .valueOf(strat)).getTime()) / ( 3600* 24* 1000); }

/** * 获得当前年份 *@returnyear(int) */publicstaticintgetCurrentYear(){ Calendar mCalendar = Calendar.getInstance();

returnmCalendar.get(Calendar.YEAR); }

/** * 获得当前月份 *@returnmonth(int) 1-12 */publicstaticintgetCurrentMonth(){ Calendar mCalendar = Calendar.getInstance();

returnmCalendar.get(Calendar.MONTH) + 1; }

/** * 获得当月几号 *@returnday(int) */publicstaticintgetDayOfMonth(){ Calendar mCalendar = Calendar.getInstance();

returnmCalendar.get(Calendar.DAY_OF_MONTH); }

/** * 获得今天的日期(格式:yyyy-MM-dd) *@returnyyyy-MM-dd */publicstaticString getToday(){ Calendar mCalendar = Calendar.getInstance();

returngetDateFormat(mCalendar.getTime()); }

/** * 获得昨天的日期(格式:yyyy-MM-dd) *@returnyyyy-MM-dd */publicstaticString getYesterday(){ Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, - 1);

returngetDateFormat(mCalendar.getTime()); }

/** * 获得前天的日期(格式:yyyy-MM-dd) *@returnyyyy-MM-dd */publicstaticString getBeforeYesterday(){ Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, - 2);

returngetDateFormat(mCalendar.getTime()); }

/** * 获得几天之前或者几天之后的日期 *@paramdiff 差值:正的往后推,负的往前推 *@return*/publicstaticString getOtherDay(intdiff){ Calendar mCalendar = Calendar.getInstance(); mCalendar.add(Calendar.DATE, diff);

returngetDateFormat(mCalendar.getTime()); }

/** * 取得给定日期加上一定天数后的日期对象. * *@param//date 给定的日期对象 *@paramamount 需要添加的天数,如果是向前的天数,使用负数就可以. *@returnDate 加上一定天数以后的Date对象. */publicstaticString getCalcDateFormat(String sDate, intamount){ Date date = getCalcDate(getDateByDateFormat(sDate), amount);

returngetDateFormat(date); }

/** * 取得给定日期加上一定天数后的日期对象. * *@paramdate 给定的日期对象 *@paramamount 需要添加的天数,如果是向前的天数,使用负数就可以. *@returnDate 加上一定天数以后的Date对象. */publicstaticDate getCalcDate(Date date, intamount){ Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, amount);

returncal.getTime(); }

基本都是代码,不是我懒(就是懒你咬我),主要是方便新手司机的copy好吧。好了,本篇随笔就到这里。返回搜狐,查看更多

作者: LYing_

地址:http://www.apkbus.com/blog-685845-76823.html

程序员大咖整理发布,转载请联系作者获得授权

责任编辑:

最后

以上就是受伤棉花糖为你收集整理的android 开发工具类,Android开发中常用到的工具类整理的全部内容,希望文章能够帮你解决android 开发工具类,Android开发中常用到的工具类整理所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部