Android common tools source code collection

Android common tools source code collection

[[121410]]

This article mainly introduces and summarizes the commonly used tool classes in Android development, most of which are also applicable to Java. Currently, they include HttpUtils, DownloadManagerPro, ShellUtils, PackageUtils, PreferencesUtils, JSONUtils, FileUtils, ResourceUtils, StringUtils, ParcelUtils, RandomUtils, ArrayUtils, ImageUtils, ListUtils, MapUtils, ObjectUtils, SerializeUtils, SystemUtils, and TimeUtils. The English version of this article see: Android Common Utils All codes are in TrineaAndroidCommon@Github, welcome to Star or Fork^_*, in addition to these tool classes, this project also includes cache, drop-down ListView, etc. Detailed interface introduction can be seen in TrineaAndroidCommon API Guide. Specific use: You can directly introduce TrineaAndroidCommon as the library of your project (how to pull code and add public libraries), or extract some of them for use.

1. HttpUtils

Http network tool class, mainly including httpGet, httpPost and http parameter related methods, taking httpGet as an example:

static HttpResponse httpGet(HttpRequest request)

static HttpResponse httpGet(java.lang.String httpUrl)

static String httpGetString(String httpUrl)

Contains the above three methods, uses gzip compression by default, and uses bufferedReader to increase reading speed.

In HttpRequest, you can set other http parameters such as url, timeout, userAgent, etc.

HttpResponse can obtain the return content, http response code, http expiration time (max-age and expires of Cache-Control), etc.

The first two methods can perform advanced parameter settings and return rich content, and the third method can simply pass in a URL to get the return content, which is similar to httpPost. For more detailed settings, you can directly use HttpURLConnection or Apache's HttpClient.

The source code can be found in HttpUtils.java. For more methods and detailed parameter descriptions, see HttpUtils Api Guide.

2. DownloadManagerPro

Android system download manager DownloadManager enhanced method can be used to obtain download related information, such as:

getStatusById(long) Get download status

getDownloadBytes(long) Get download progress information

getBytesAndStatus(long) Get download progress information and status

getFileName(long) Get the download file path

getUri(long) Get download uri

getReason(long) Get the reason why the download failed or was paused

getPausedReason(long) Get the reason why the download was paused

getErrorCode(long) Get the download error code

For the source code, see DownloadManagerPro.java. For more methods and detailed parameter descriptions, see DownloadManagerPro Api Guide. For the use of Android DownManager, see DownManager Demo.

3. ShellUtils

Android Shell tool class, which can be used to check the system root permissions and execute shell commands under the shell or root user. For example:

checkRootPermission() Check root permission

execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) Executes commands in the shell environment. The second parameter indicates whether it is executed with root privileges.

execCommand(String command, boolean isRoot) executes commands in shell environment

The source code can be found in ShellUtils.java. For more methods and detailed parameter descriptions, see ShellUtils Api Guide. For silent installation, see apk-root permission silent installation.

4. PackageUtils

Android package related tool class, which can be used to install applications (root), uninstall applications (root), determine whether it is a system application, etc., such as:

install(Context, String) Install the application. If it is a system application or rooted, it will be installed silently, otherwise it will be installed normally.

uninstall(Context, String) Uninstall the application. If it is a system application or rooted, it will be uninstalled silently, otherwise it will be uninstalled normally.

isSystemApplication(Context, String) Determines whether the application is a system application

For source code, see PackageUtils.java. For more methods and detailed parameter descriptions, see ShellUtils Api Guide. For silent installation, see apk-root permission silent installation.

5. PreferencesUtils

Android SharedPreferences related tool classes can be used to easily read and write related types of data to SharedPreferences, such as:

putString(Context, String, String) saves string type data

putInt(Context, String, int) saves int type data

getString(Context, String) Get string type data

getInt(Context, String) Get int type data

You can modify the preference name by modifying the PREFERENCE_NAME variable

The source code can be found in PreferencesUtils.java. For more methods and detailed parameter descriptions, see PreferencesUtils Api Guide.

6. JSONUtils

The JSONUtils tool class can be used to easily read and write related types of data to Json, such as:

String getString(JSONObject jsonObject, String key, String defaultValue) gets string type value

String getString(String jsonData, String key, String defaultValue) Get string type value

Indicates reading the value of a String type key from json

getMap(JSONObject jsonObject, String key) get map

getMap(String jsonData, String key) get map

Indicates reading the value of a Map type key from json

The source code can be found in JSONUtils.java. For more methods and detailed parameter descriptions, see JSONUtils Api Guide.

7. FileUtils

File tool class, which can be used to read and write files and operate on files. For example:

readFile(String filePath) Read file

writeFile(String filePath, String content, boolean append) write file

getFileSize(String path) Get the file size

deleteFile(String path) Delete file

The source code can be found in FileUtils.java. For more methods and detailed parameter descriptions, see FileUtils Api Guide.

8. ResourceUtils

Android Resource tool class can be used to read content from the raw and assets directories of the Android resource directory, such as:

geFileFromAssets(Context context, String fileName) Get the contents of a file in the assets directory

geFileFromRaw(Context context, int resId) Get the content of a file in the raw directory

The source code can be found in ResourceUtils.java. For more methods and detailed parameter descriptions, see ResourceUtils Api Guide.

9. StringUtils

String tool class, which can be used for common string operations, such as:

isEmpty(String str) Determines whether the string is empty or has a length of 0

isBlank(String str) Determines whether the string is empty or has a length of 0 or consists of spaces

utf8Encode(String str) Encode in utf-8 format

capitalizeFirstLetter(String str) capitalize the first letter

The source code can be found in StringUtils.java. For more methods and detailed parameter descriptions, see StringUtils Api Guide.

10. ParcelUtils

Android Parcel utility class, which can be used to read or write special types of data from parcel, such as:

readBoolean(Parcel in) Reads Boolean data from parcel

readHashMap(Parcel in, ClassLoader loader) Reads map type data from pacel

writeBoolean(boolean b, Parcel out) Writes boolean data to parcel

writeHashMap(Map<K, V> map, Parcel out, int flags) Writes map type data to parcel

The source code can be found in ParcelUtils.java. For more methods and detailed parameter descriptions, see ParcelUtils Api Guide.

11. RandomUtils

Random number tool class, which can be used to obtain random numbers within fixed size and fixed characters, such as:

getRandom(char[] sourceChar, int length) Generates a random string, all characters are within a string

getRandomNumbers(int length) Generates random numbers

The source code can be found in RandomUtils.java. For more methods and detailed parameter descriptions, see RandomUtils Api Guide.

12. ArrayUtils

Array tool class, which can be used for common array operations, such as:

isEmpty(V[] sourceArray) Determines whether the array is empty or has a length of 0

getLast(V[] sourceArray, V value, V defaultValue, boolean isCircle) Gets the previous element of an element in the array. isCircle indicates whether it is circular.

getNext(V[] sourceArray, V value, V defaultValue, boolean isCircle) Gets the next element of an element in the array. isCircle indicates whether it is circular.

The source code can be found in ArrayUtils.java. For more methods and detailed parameter descriptions, see ArrayUtils Api Guide.

13. ImageUtils

Image tool class, which can be used to convert between Bitmap, byte array, Drawable and scale images. Currently, its functions are weak and will be enhanced later. For example:

bitmapToDrawable(Bitmap b) bimap converted to drawable

drawableToBitmap(Drawable d) Converts a drawable to a bitmap

drawableToByte(Drawable d) Drawable converted to byte

scaleImage(Bitmap org, float scaleWidth, float scaleHeight) Scale image

The source code can be found in ImageUtils.java. For more methods and detailed parameter descriptions, see ImageUtils Api Guide.

14. ListUtils

List tool class, which can be used for common List operations, such as:

isEmpty(List<V> sourceList) Determines whether the List is empty or has a length of 0

join(List<String> list, String separator) List is converted to a string and split by a fixed separator

addDistinctEntry(List<V> sourceList, V entry) Adds unique elements to the list

The source code can be found in ListUtils.java. For more methods and detailed parameter descriptions, see ListUtils Api Guide.

15. MapUtils

Map tool class, which can be used for common Map operations, such as:

isEmpty(Map<K, V> sourceMap) Determines whether the map is empty or has a length of 0

parseKeyAndValueToMap(String source, String keyAndValueSeparator, String keyAndValuePairSeparator, boolean ignoreSpace) String is parsed into map

toJson(Map<String, String> map) map is converted to json format

The source code can be found in MapUtils.java. For more methods and detailed parameter descriptions, see MapUtils Api Guide.

16. ObjectUtils

Object tool class, which can be used for common operations on Object, such as:

isEquals(Object actual, Object expected) Compares whether two objects are equal

compare(V v1, V v2) compares the size of two objects

transformIntArray(int[] source) Integer array converted to int array

The source code can be found in ObjectUtils.java. For more methods and detailed parameter descriptions, see ObjectUtils Api Guide.

17. SerializeUtils

Serialization tool class, which can be used to serialize objects to files or deserialize objects from files, such as:

deserialization(String filePath) Deserialize an object from a file

serialization(String filePath, Object obj) Serializes the object to a file

The source code can be found in SerializeUtils.java. For more methods and detailed parameter descriptions, see SerializeUtils Api Guide.

18. SystemUtils

System information tool class, which can be used to get the appropriate size of the thread pool. It is weak at present and will be enhanced later. For example:

getDefaultThreadPoolSize() Gets the thread pool size that matches the system configuration

The source code can be found in SystemUtils.java. For more methods and detailed parameter descriptions, see SystemUtils Api Guide.

19. TimeUtils

Time tool class, which can be used for time-related operations, such as:

getCurrentTimeInLong() Get the current time

getTime(long timeInMillis, SimpleDateFormat dateFormat) Converts long to a fixed-format time string

The source code can be found in TimeUtils.java. For more methods and detailed parameter descriptions, see TimeUtils Api Guide.

<<:  Mail Master Pro is coming to iOS for free this week

>>:  Creating a Material Design Android App: Creating Lists and Cards

Recommend

Why do you always want to jump down when you are standing on a high place?

This article was reviewed by Zhao Wei, MD, associ...

117-year-old man dies! Is longevity determined by genes or intestinal flora?

BEIJING, Aug. 21 (Xinhua) -- Maria Branyas Moreir...

Package visibility in Android 11

In Android 10 and earlier versions, apps can get ...

iOS/iPadOS 14.4.1 released: fixes WebKit security vulnerability

Apple today released iOS and iPadOS 14.4.1, a sma...

English Speaking: Breaking through American Oral Thinking

English Speaking: Breaking through American Oral ...

Methods for attracting new users through event operations!

In recent years, I have seen many user operations...

Why is the iPhone 6 malfunctioning?

According to foreign media reports, some iPhone 6...

Do you really know how to leverage brand marketing?

Many brands are accustomed to using the marketing...