主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java。
目前包括HttpUtils、DownloadManagerPro、ShellUtils、PackageUtils、PreferencesUtils、JSONUtils、FileUtils、ResourceUtils、StringUtils、ParcelUtils、RandomUtils、ArrayUtils、ImageUtils、ListUtils、MapUtils、ObjectUtils、SerializeUtils、SystemUtils、TimeUtils。
The English version of this article see:Android Common Utils
所有代码都在TrineaAndroidCommon@Github中,欢迎Star或Fork^_*,除这些工具类外此项目还包括缓存、下拉ListView等。详细接口介绍可见TrineaAndroidCommon API Guide。
具体使用:可直接引入TrineaAndroidCommon作为你项目的library(如何拉取代码及添加公共库),或是自己抽取其中的部分使用。
1、HttpUtils
Http网络工具类,主要包括httpGet、httpPost以及http参数相关方法,以httpGet为例:
static HttpResponse httpGet(HttpRequest request)
static HttpResponse httpGet(java.lang.String httpUrl)
static String httpGetString(String httpUrl)
包含以上三个方法,默认使用gzip压缩,使用bufferedReader提高读取速度。
HttpRequest中可以设置url、timeout、userAgent等其他http参数
HttpResponse中可以获取返回内容、http响应码、http过期时间(Cache-Control的max-age和expires)等
前两个方法可以进行高级参数设置及丰富内容返回,第三个方法可以简单的传入url获取返回内容,httpPost类似。更详细的设置可以直接使用HttpURLConnection或apache的HttpClient。
源码可见HttpUtils.java,更多方法及更详细参数介绍可见HttpUtils Api Guide。
2、DownloadManagerPro
Android系统下载管理DownloadManager增强方法,可用于包括获取下载相关信息,如:
getStatusById(long) 得到下载状态
getDownloadBytes(long) 得到下载进度信息
getBytesAndStatus(long) 得到下载进度信息和状态
getFileName(long) 得到下载文件路径
getUri(long) 得到下载uri
getReason(long) 得到下载失败或暂停原因
getPausedReason(long) 得到下载暂停原因
getErrorCode(long) 得到下载错误码
源码可见DownloadManagerPro.java,更多方法及更详细参数介绍可见DownloadManagerPro Api Guide。关于Android DownManager使用可见DownManager Demo。
3、ShellUtils
Android Shell工具类,可用于检查系统root权限,并在shell或root用户下执行shell命令。如:
checkRootPermission() 检查root权限
execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) shell环境执行命令,第二个参数表示是否root权限执行
execCommand(String command, boolean isRoot) shell环境执行命令
源码可见ShellUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。
4、PackageUtils
Android包相关工具类,可用于(root)安装应用、(root)卸载应用、判断是否系统应用等,如:
install(Context, String) 安装应用,如果是系统应用或已经root,则静默安装,否则一般安装
uninstall(Context, String) 卸载应用,如果是系统应用或已经root,则静默卸载,否则一般卸载
isSystemApplication(Context, String) 判断应用是否为系统应用
源码可见PackageUtils.java,更多方法及更详细参数介绍可见ShellUtils Api Guide。关于静默安装可见apk-root权限静默安装。
5、PreferencesUtils
Android SharedPreferences相关工具类,可用于方便的向SharedPreferences中读取和写入相关类型数据,如:
putString(Context, String, String) 保存string类型数据
putInt(Context, String, int) 保存int类型数据
getString(Context, String) 获取string类型数据
getInt(Context, String) 获取int类型数据
可通过修改PREFERENCE_NAME变量修改preference name
源码可见PreferencesUtils.java,更多方法及更详细参数介绍可见PreferencesUtils Api Guide。
6、JSONUtils
JSONUtils工具类,可用于方便的向Json中读取和写入相关类型数据,如:
String getString(JSONObject jsonObject, String key, String defaultValue) 得到string类型value
String getString(String jsonData, String key, String defaultValue) 得到string类型value
表示从json中读取某个String类型key的值
getMap(JSONObject jsonObject, String key) 得到map
getMap(String jsonData, String key) 得到map
表示从json中读取某个Map类型key的值
源码可见JSONUtils.java,更多方法及更详细参数介绍可见JSONUtils Api Guide。
7、FileUtils
文件工具类,可用于读写文件及对文件进行操作。如:
readFile(String filePath) 读文件
writeFile(String filePath, String content, boolean append) 写文件
getFileSize(String path) 得到文件大小
deleteFile(String path) 删除文件
源码可见FileUtils.java,更多方法及更详细参数介绍可见FileUtils Api Guide。
8、ResourceUtils
Android Resource工具类,可用于从android资源目录的raw和assets目录读取内容,如:
geFileFromAssets(Context context, String fileName) 得到assets目录下某个文件内容
geFileFromRaw(Context context, int resId) 得到raw目录下某个文件内容
源码可见ResourceUtils.java,更多方法及更详细参数介绍可见ResourceUtils Api Guide。
9、StringUtils
String工具类,可用于常见字符串操作,如:
isEmpty(String str) 判断字符串是否为空或长度为0
isBlank(String str) 判断字符串是否为空或长度为0 或由空格组成
utf8Encode(String str) 以utf-8格式编码
capitalizeFirstLetter(String str) 首字母大写
源码可见StringUtils.java,更多方法及更详细参数介绍可见StringUtils Api Guide。
10、ParcelUtils
Android Parcel工具类,可用于从parcel读取或写入特殊类型数据,如:
readBoolean(Parcel in) 从pacel中读取boolean类型数据
readHashMap(Parcel in, ClassLoader loader) 从pacel中读取map类型数据
writeBoolean(boolean b, Parcel out) 向parcel中写入boolean类型数据
writeHashMap(Map
源码可见ParcelUtils.java,更多方法及更详细参数介绍可见ParcelUtils Api Guide。
11、RandomUtils
随机数工具类,可用于获取固定大小固定字符内的随机数,如:
getRandom(char[] sourceChar, int length) 生成随机字符串,所有字符均在某个字符串内
getRandomNumbers(int length) 生成随机数字
源码可见RandomUtils.java,更多方法及更详细参数介绍可见RandomUtils Api Guide。
12、ArrayUtils
数组工具类,可用于数组常用操作,如:
isEmpty(V[] sourceArray) 判断数组是否为空或长度为0
getLast(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素前一个元素,isCircle表示是否循环
getNext(V[] sourceArray, V value, V defaultValue, boolean isCircle) 得到数组中某个元素下一个元素,isCircle表示是否循环
源码可见ArrayUtils.java,更多方法及更详细参数介绍可见ArrayUtils Api Guide。
13、ImageUtils
图片工具类,可用于Bitmap, byte array, Drawable之间进行转换以及图片缩放,目前功能薄弱,后面会进行增强。如:
bitmapToDrawable(Bitmap b) bimap转换为drawable
drawableToBitmap(Drawable d) drawable转换为bitmap
drawableToByte(Drawable d) drawable转换为byte
scaleImage(Bitmap org, float scaleWidth, float scaleHeight) 缩放图片
源码可见ImageUtils.java,更多方法及更详细参数介绍可见ImageUtils Api Guide。
14、ListUtils
List工具类,可用于List常用操作,如:
isEmpty(List
join(List
addDistinctEntry(List
源码可见ListUtils.java,更多方法及更详细参数介绍可见ListUtils Api Guide。
15、MapUtils
Map工具类,可用于Map常用操作,如:
isEmpty(Map
parseKeyAndValueToMap(String source, String keyAndValueSeparator, String keyAndValuePairSeparator, boolean ignoreSpace) 字符串解析为map
toJson(Map
源码可见MapUtils.java,更多方法及更详细参数介绍可见MapUtils Api Guide。
16、ObjectUtils
Object工具类,可用于Object常用操作,如:
isEquals(Object actual, Object expected) 比较两个对象是否相等
compare(V v1, V v2) 比较两个对象大小
transformIntArray(int[] source) Integer 数组转换为int数组
源码可见ObjectUtils.java,更多方法及更详细参数介绍可见ObjectUtils Api Guide。
17、SerializeUtils
序列化工具类,可用于序列化对象到文件或从文件反序列化对象,如:
deserialization(String filePath) 从文件反序列化对象
serialization(String filePath, Object obj) 序列化对象到文件
源码可见SerializeUtils.java,更多方法及更详细参数介绍可见SerializeUtils Api Guide。
18、SystemUtils
系统信息工具类,可用于得到线程池合适的大小,目前功能薄弱,后面会进行增强。如:
getDefaultThreadPoolSize() 得到跟系统配置相符的线程池大小
源码可见SystemUtils.java,更多方法及更详细参数介绍可见SystemUtils Api Guide。
19、TimeUtils
时间工具类,可用于时间相关操作,如:
getCurrentTimeInLong() 得到当前时间
getTime(long timeInMillis, SimpleDateFormat dateFormat) 将long转换为固定格式时间字符串
源码可见TimeUtils.java,更多方法及更详细参数介绍可见TimeUtils Api Guide。

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

HTTPS significantly improves the security of sessions by encrypting data transmission, preventing man-in-the-middle attacks and providing authentication. 1) Encrypted data transmission: HTTPS uses SSL/TLS protocol to encrypt data to ensure that the data is not stolen or tampered during transmission. 2) Prevent man-in-the-middle attacks: Through the SSL/TLS handshake process, the client verifies the server certificate to ensure the connection legitimacy. 3) Provide authentication: HTTPS ensures that the connection is a legitimate server and protects data integrity and confidentiality.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor