当前位置: 首页 > 编程日记 > 正文

Android 常见工具类封装

1,MD5工具类:

复制代码
public class MD5Util {public final static String MD5(String s) {char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };try {byte[] btInput = s.getBytes();// 获得MD5摘要算法的 MessageDigest 对象MessageDigest mdInst = MessageDigest.getInstance("MD5");// 使用指定的字节更新摘要
            mdInst.update(btInput);// 获得密文byte[] md = mdInst.digest();// 把密文转换成十六进制的字符串形式int j = md.length;char str[] = new char[j * 2];int k = 0;for (int i = 0; i < j; i++) {byte byte0 = md[i];str[k++] = hexDigits[byte0 >>> 4 & 0xf];str[k++] = hexDigits[byte0 & 0xf];}return new String(str);} catch (Exception e) {return null;}}public static void main(String[] args) {System.out.print(MD5Util.MD5("password"));}
}
复制代码

2,线程睡眠

复制代码
public class CSleep {public static final long DEFAULT_SLEEP_TIME = 500;private boolean          isRuning           = false;public boolean isRuning() {return isRuning;}public void runWithTime(final long defaultSleepTime) {isRuning = true;new Thread() {@Overridepublic void run() {try {sleep(defaultSleepTime, 0);} catch (InterruptedException e) {e.printStackTrace();}isRuning = false;super.run();}}.start();}
}
复制代码

3,检查网络是否连通

复制代码
 /*** 检查网络是否连通* * @return boolean* @since V1.0*/public boolean isNetworkAvailable(Context context) {// 创建并初始化连接对象ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);// 判断初始化是否成功并作出相应处理if (connMan != null) {// 调用getActiveNetworkInfo方法创建对象,如果不为空则表明网络连通,否则没连通NetworkInfo info = connMan.getActiveNetworkInfo();if (info != null) {return info.isAvailable();}}return false;}
复制代码

4,异常类捕捉

复制代码
/*** UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告. 需要在Application中注册,为了要在程序启动器就监控整个程序。*/
public class CrashHandler implements UncaughtExceptionHandler {/** TAG */public static final String              TAG       = "CrashHandler";/** 系统默认的UncaughtException处理类 */private Thread.UncaughtExceptionHandler mDefaultHandler;/** CrashHandler实例 */private static CrashHandler             mCrashHandler;/** 程序的Context对象 */private Context                         mContext;/** 用来存储设备信息和异常信息 */private Map<String, String>             infos     = new HashMap<String, String>();/** 用于格式化日期,作为日志文件名的一部分 */private DateFormat                      formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");/*** 私有构造函数*/private CrashHandler() {}/*** 获取CrashHandler实例 ,单例模式* * @return* @since V1.0*/public static CrashHandler getInstance() {if (mCrashHandler == null)mCrashHandler = new CrashHandler();return mCrashHandler;}/*** 初始化* * @param context* @since V1.0*/public void init(Context context) {mContext = context;// 获取系统默认的UncaughtException处理器mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 设置该CrashHandler为程序的默认处理器Thread.setDefaultUncaughtExceptionHandler(this);}/*** 当UncaughtException发生时会转入该函数来处理*/@Overridepublic void uncaughtException(Thread thread, Throwable ex) {if (!handleException(ex) && mDefaultHandler != null) {// 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);} else {try {Thread.sleep(3000);} catch (InterruptedException e) {CLog.e(TAG, "uncaughtException() InterruptedException:" + e);}// 退出程序
            android.os.Process.killProcess(android.os.Process.myPid());System.exit(1);}}/*** 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.* * @param ex* @return true:如果处理了该异常信息;否则返回false.* @since V1.0*/private boolean handleException(Throwable ex) {if (ex == null) {return false;}// 收集设备参数信息
        collectDeviceInfo(mContext);// 使用Toast来显示异常信息new Thread() {@Overridepublic void run() {Looper.prepare();Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show();Looper.loop();}}.start();// 保存日志文件
        saveCatchInfo2File(ex);return true;}/*** 收集设备参数信息* * @param ctx* @since V1.0*/public void collectDeviceInfo(Context ctx) {try {PackageManager pm = ctx.getPackageManager();PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);if (pi != null) {String versionName = pi.versionName == null ? "null" : pi.versionName;String versionCode = pi.versionCode + "";infos.put("versionName", versionName);infos.put("versionCode", versionCode);}} catch (NameNotFoundException e) {CLog.e(TAG, "collectDeviceInfo() an error occured when collect package info NameNotFoundException:", e);}Field[] fields = Build.class.getDeclaredFields();for (Field field : fields) {try {field.setAccessible(true);infos.put(field.getName(), field.get(null).toString());CLog.d(TAG, field.getName() + " : " + field.get(null));} catch (Exception e) {CLog.e(TAG, "collectDeviceInfo() an error occured when collect crash info Exception:", e);}}}/*** 保存错误信息到文件中* * @param ex* @return 返回文件名称,便于将文件传送到服务器*/private String saveCatchInfo2File(Throwable ex) {StringBuffer sb = new StringBuffer();for (Map.Entry<String, String> entry : infos.entrySet()) {String key = entry.getKey();String value = entry.getValue();sb.append(key + "=" + value + "\n");}Writer writer = new StringWriter();PrintWriter printWriter = new PrintWriter(writer);ex.printStackTrace(printWriter);Throwable cause = ex.getCause();while (cause != null) {cause.printStackTrace(printWriter);cause = cause.getCause();}printWriter.close();String result = writer.toString();sb.append(result);try {long timestamp = System.currentTimeMillis();String time = formatter.format(new Date());String fileName = "crash-" + time + "-" + timestamp + ".log";if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {String path = FilePathUtil.getiVMSDirPath() + "/crash/";File dir = new File(path);if (!dir.exists()) {dir.mkdirs();}FileOutputStream fos = new FileOutputStream(path + fileName);fos.write(sb.toString().getBytes());// 发送给开发人员sendCrashLog2PM(path + fileName);fos.close();}return fileName;} catch (Exception e) {CLog.e(TAG, "saveCatchInfo2File() an error occured while writing file... Exception:", e);}return null;}/*** 将捕获的导致崩溃的错误信息发送给开发人员 目前只将log日志保存在sdcard 和输出到LogCat中,并未发送给后台。* * @param fileName* @since V1.0*/private void sendCrashLog2PM(String fileName) {if (!new File(fileName).exists()) {CLog.e(TAG, "sendCrashLog2PM() 日志文件不存在");return;}FileInputStream fis = null;BufferedReader reader = null;String s = null;try {fis = new FileInputStream(fileName);reader = new BufferedReader(new InputStreamReader(fis, "GBK"));while (true) {s = reader.readLine();if (s == null)break;// 由于目前尚未确定以何种方式发送,所以先打出log日志。
                CLog.e(TAG, s);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally { // 关闭流try {reader.close();fis.close();} catch (IOException e) {e.printStackTrace();}}}
}
复制代码

5,弹出框提醒

 public static Dialog showDialog(Context ctx, int layViewID, int ThemeType) {Dialog res = new Dialog(ctx, ThemeType);res.setContentView(layViewID);return res;}

6,图片API类

复制代码
public class ImageAPI {public static Bitmap getImageByFilePath(String filePath, int scale) {Bitmap res = null;BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;BitmapFactory.decodeFile(filePath, options);options.inJustDecodeBounds = false;options.inSampleSize = scale;options.inPreferredConfig = Bitmap.Config.ARGB_4444;return res;}public static Bitmap getImageByFilePath(String filePath, int Towidth, int ToHeight) {Bitmap res = null;BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true;if (!new File(filePath).exists())return res;BitmapFactory.decodeFile(filePath, options);int origionalWidth = options.outHeight;int origionalHeight = options.outWidth;options.inJustDecodeBounds = false;int scale = Math.max(origionalWidth / Towidth, origionalHeight / ToHeight);options.inSampleSize = scale;options.inPreferredConfig = Bitmap.Config.ARGB_4444;try {res = BitmapFactory.decodeFile(filePath, options);} catch (Exception e) {e.printStackTrace();return null;} catch (OutOfMemoryError e) {e.printStackTrace();return null;}return res;}}
复制代码

10,提醒封装类

复制代码
public static void showToast(Context ctx, int id, String str) {if (str == null) {return;}Toast toast = Toast.makeText(ctx, ctx.getString(id) + str, Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER, 0, 0);toast.show();}public static void showToast(Context ctx, String errInfo) {if (errInfo == null) {return;}Toast toast = Toast.makeText(ctx, errInfo, Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER, 0, 0);toast.show();}
复制代码

相关文章:

keras系列︱图像多分类训练与利用bottleneck features进行微调(三)

引自&#xff1a;http://blog.csdn.net/sinat_26917383/article/details/72861152 中文文档&#xff1a;http://keras-cn.readthedocs.io/en/latest/ 官方文档&#xff1a;https://keras.io/ 文档主要是以keras2.0。 训练、训练主要就”练“嘛&#xff0c;所以堆几个案例就知…

LIKE 操作符

LIKE 操作符LIKE 操作符用于在 WHERE 子句中搜索列中的指定模式。SQL LIKE 操作符语法SELECT column_name(s)FROM table_nameWHERE column_name LIKE pattern原始的表 (用在例子中的)&#xff1a;Persons 表:IdLastNameFirstNameAddressCity1AdamsJohnOxford StreetLondon2Bush…

服务器云ide_语言服务器协议如何影响IDE的未来

服务器云ideThe release of Visual Studio Code single-handedly impacted the developer ecosystem in such a way that theres no going back now. Its open source, free, and most importantly, a super powerful tool. Visual Studio Code的发布以一种无可匹敌的方式对开发…

仅需6步,教你轻易撕掉app开发框架的神秘面纱(6):各种公共方法及工具类的封装

为什么要封装公共方法 封装公共方法有2方面的原因&#xff1a; 一是功能方面的原因&#xff1a;有些方法很多地方都会用&#xff0c;而且它输入输出明确&#xff0c;并且跟业务逻辑无关。比如检查用户是否登录&#xff0c;检查某串数字是否为合法的手机号。像这种方法就应该封…

MySQL优化配置之query_cache_size

原理MySQL查询缓存保存查询返回的完整结果。当查询命中该缓存&#xff0c;会立刻返回结果&#xff0c;跳过了解析&#xff0c;优化和执行阶段。 查询缓存会跟踪查询中涉及的每个表&#xff0c;如果这写表发生变化&#xff0c;那么和这个表相关的所有缓存都将失效。 但是随着服…

request.getSession()

request.getSession(); 与request.getSession(false);区别 服务器把session信息发送给浏览器 浏览器会将session信息存入本地cookie中 服务器本地内存中也会留一个此session信息 以后用户发送请求时 浏览器都会把session信息发送给服务器 服务器会依照浏览器发送过来的se…

alpine 交互sh_在这个免费的交互式教程中学习Alpine JS

alpine 交互shAlpine.js is a rugged, minimal framework for composing Javascript behavior in your markup. Thats right, in your markup! Alpine.js是一个坚固的最小框架&#xff0c;用于在标记中构成Javascript行为。 是的&#xff0c;在您的标记中&#xff01; It allo…

浅谈 MVP in Android

一、概述 对于MVP&#xff08;Model View Presenter&#xff09;&#xff0c;大多数人都能说出一二&#xff1a;“MVC的演化版本”&#xff0c;“让Model和View完全解耦”等等。本篇博文仅是为了做下记录&#xff0c;提出一些自己的看法&#xff0c;和帮助大家如何针对一个Acti…

test markdown

test test public void main(String[] args){System.out.println("test"); } 转载于:https://www.cnblogs.com/cozybz/p/5427053.html

java开发工具对比eclipse·myeclipse·idea

eclipse:不说了&#xff0c;习惯了 myeclipse&#xff1a;MyEclipse更适合企业开发者&#xff0c;更团队开发 idea:idea更适合个人开发者,细节优化更好转载于:https://www.cnblogs.com/gjack/p/8136964.html

软件测试质量过程检测文档_如何编写实际上有效的质量检查文档

软件测试质量过程检测文档A software product is like an airplane: it must undergo a technical check before launch.软件产品就像飞机&#xff1a;必须在发射前经过技术检查。 Quality Assurance is a necessary step towards launching a successful software product. I…

Android深度探索--HAL与驱动开发----第一章读书笔记

1.1 Android拥有非常完善的系统构架可以分为四层&#xff1a; 第一层&#xff1a;Linux内核。主要包括驱动程序以及管理内存、进程、电源等资源的程序 第二层&#xff1a;C/C代码库。主要包括Linux的.so文件以及嵌入到APK程序中的NDK代码 第三层&#xff1a;android SDK API …

[NOI2011]Noi嘉年华

题解:我们设计状态方程如下: num[i][j]表示从时间i到j中有多少个 pre[i][j]表示时间1~i中,A选了j个时的B能选的数量的最大值. nex[i][j]表示时间i~cnt中,A选了j个时的B能选的数量的最大值. mus[i][j]表示从时间i到j的保证选时,A和B选的数量中的较小值的最大值. ①对于num数组直…

只有20%的iOS程序员能看懂:详解intrinsicContentSize 及 约束优先级/content Hugging/content Compression Resistance

在了解intrinsicContentSize之前&#xff0c;我们需要先了解2个概念&#xff1a; AutoLayout在做什么约束优先级是什么意思。 如果不了解这两个概念&#xff0c;看intinsic content size没有任何意义。 注&#xff1a;由于上面这几个概念都是针对UIView或其子类(UILabel&…

redux rxjs_可观察的RxJS和Redux入门指南

redux rxjsRedux-Observable is an RxJS-based middleware for Redux that allows developers to work with async actions. Its an alternative to redux-thunk and redux-saga.Redux-Observable是Redux的基于RxJS的中间件&#xff0c;允许开发人员使用异步操作。 它是redux-t…

javascript数组排序和prototype详解

原型的概念:&#xff1a;原型对象里的所有属性和方法 被所有构造函数实例化出来的对象所共享&#xff0c;类似于java中的 static 正因为共享所以单一的操作 就会影响了全局&#xff0c;因此使用时需注意 基于prototype&#xff1a;为数组扩展方法 //获取数组最大值function get…

Qt 在Label上面绘制罗盘

自己写的一个小小的电子罗盘的一个小程序&#xff0c;不过是项目的一部分&#xff0c;只可以贴绘制部分代码 效果如下图 首先开始自己写的时候&#xff0c;虽然知道Qt 的坐标系是从左上角开始的&#xff0c;所以&#xff0c;使用了算法&#xff0c;在绘制后&#xff0c;在移动回…

终极方案!解决正确设置LaunchImage后仍然不显示的问题

对于如何设置LaunchImage&#xff0c;网络上有各种各样的教程。 主要分2点&#xff1a; 1. 正确设置图片尺寸 2. 取消LaunchScreen.xib 但是经过上述步骤之后&#xff0c;你觉得完全没有问题了&#xff0c;但是仍然无法显示LaunchImage。 或者&#xff0c;你在多个模拟器上…

c# 持续集成 单元测试_如何在不进行单元测试的情况下设置持续集成

c# 持续集成 单元测试Do you think continuous integration is not for you because you have no automated tests? Or no unit tests at all? Not true. Tests are important. But there are many more aspects to continuous integration than just testing. Lets see what…

Handlebars模板引擎

介绍 Handlebars 是 JavaScript 一个语义模板库&#xff0c;通过对view和data的分离来快速构建Web模板。它采用"Logic-less template"&#xff08;无逻辑模版&#xff09;的思路&#xff0c;在加载时被预编译&#xff0c;而不是到了客户端执行到代码时再去编译&#…

字符集图标制作

字符集图标&#xff1a; 将网页上常见的icon做成font&#xff08;字符集&#xff09;&#xff0c;以字体的方式插入到网页上&#xff0c;作用是减轻服务器负担&#xff0c;减少宽带。 我最常在这两个网站上下载字体图标&#xff1a; https://icomoon.io/app/#/select https://w…

Adobe源码泄漏?3行代码搞定,Flash动画无缝导入Android/iOS/cocos2dx(一)

[注] iOS代码已重构&#xff0c;效率提升90%&#xff0c;200层动画不卡。[2016.10.27] 项目介绍 项目名称&#xff1a;FlashAnimationToMobile 源码。 使用方法点这里。 这是一个把flash中的关键帧动画(不是序列帧)导出&#xff0c;然后在iOS&#xff0f;Android原生应用中解…

背景图像位置css_CSS背景图像大小教程–如何对整页背景图像进行编码

背景图像位置cssThis tutorial will show you a simple way to code a full page background image using CSS. And youll also learn how to make that image responsive to your users screen size.本教程将向您展示一种使用CSS编写整页背景图像的简单方法。 您还将学习如何使…

复习es6-解构赋值+字符串的扩展

1. 数组的解构赋值 从数组中获得变量的值&#xff0c;给对应的声明变量赋值,&#xff0c;有次序和对应位置赋值 解构赋值的时候右边必须可以遍历 解构赋值可以使用默认值 惰性求值&#xff0c;当赋值时候为undefined时候&#xff0c;默认是个函数就会执行函数 2.对象解构赋值 与…

Adobe源码泄漏?3行代码搞定,Flash动画无缝导入Android/iOS/cocos2dx(二)

[注] iOS代码已重构&#xff0c;效率提升90%&#xff0c;200层动画不卡。[2016.10.27] 上一篇 点此阅读 简要介绍了FlashToAnimation的功能&#xff0c;也就是将flash动画无缝导入到Android/iOS及cocos2dx中运行, 这一篇介绍这个库的使用方法。点此查看源码。 准备工作 首先…

the user operation is waiting for building workspace to complete解决办法

如果你在开发android应用程序中总是出现一个提示&#xff0c;显示“the user operation is waiting for "building workspace" to complete”&#xff0c;解决办法如下&#xff1a; 1.选择菜单栏的“Project”,然后把菜单栏中“Build Automatically”前面的对钩去掉。…

ios开发趋势_2020年将成为iOS应用开发的主要趋势

ios开发趋势Technology has always brought something new with time. And with these ever-changing technologies, you need to stay updated to get all the benefits from whats new. 随着时间的流逝&#xff0c;技术总是带来新的东西。 借助这些不断变化的技术&#xff0c…

http 权威指南 目录

第一部分 HTTP&#xff1a;Web的基础 第1章 HTTP概述 1.1 HTTP——因特网的多媒体信使 1.2 Web客户端和服务器 1.3 资源 1.3.1 媒体类型 1.3.2 URI 1.3.3 URL 1.3.4 URN 1.4 事务 1.4.1 方法 1.4.2 状态码 1.4.3 Web页面中可以包含多个对象 1.5 报文 1.6 连接 1.6.1 TCP/IP 1.6…

java初学者笔记总结day9

异常的概念throwable&#xff1a;异常&#xff0c;程序非正常执行的情况error&#xff1a;错误&#xff0c;程序非正常执行的情况&#xff0c;这种问题不能处理&#xff0c;或不应该处理exception&#xff1a;例外&#xff0c;程序非正常执行的情况&#xff0c;这种问题可以通过…

1小时学会:最简单的iOS直播推流(一)介绍

最简单的iOS 推流代码&#xff0c;视频捕获&#xff0c;软编码(faac&#xff0c;x264)&#xff0c;硬编码&#xff08;aac&#xff0c;h264&#xff09;&#xff0c;美颜&#xff0c;flv编码&#xff0c;rtmp协议&#xff0c;陆续更新代码解析&#xff0c;你想学的知识这里都有…