Android - 开发常用工具类Utils

  • @param pxValue 像素值

  • @param context Context 对象

  • @return 返回sp数值

*/

public static int px2sp(float pxValue, Context context) {

float scale = getDensity(context);

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

}

/**

  • 将sp值转换为px值,保证文字大小不变

  • @param spValue sp数值

  • @param context Context 对象

  • @return 返回像素值

*/

public static int sp2px(float spValue, Context context) {

float scale = getDensity(context);

return (int) (spValue * scale + 0.5f);

}

/**

  • 取得手机屏幕的密度

  • @param context 上下文

  • @return 手机屏幕的密度

*/

public static float getDensity(Context context) {

float scale = context.getResources().getDisplayMetrics().density;

return scale;

}

/**

  • 获取屏幕高

  • @param activity

  • @return 手机屏幕的高度

*/

public static int getScreenHeight(Activity activity) {

DisplayMetrics dm = new DisplayMetrics();

activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

return dm.heightPixels;

}

/**

  • 获取屏幕宽

  • @param activity

  • @return 手机屏幕的宽度

*/

public static int getScreenWidth(Activity activity) {

DisplayMetrics dm = new DisplayMetrics();

activity.getWindowManager().getDefaultDisplay().getMetrics(dm);

return dm.widthPixels;

}

}

6.ResourceUtil.class(获取资源文件的工具类)

import android.app.Activity;

import android.content.Context;

import android.content.res.Resources;

import android.graphics.drawable.Drawable;

import android.util.DisplayMetrics;

public class CommonUtil {

/**

  • 获取Resource对象

*/

public static Resources getResources() {

return MainApplication.getContext().getResources();

}

/**

  • 获取Drawable资源

*/

public static Drawable getDrawable(int resId) {

return getResources().getDrawable(resId);

}

/**

  • 获取字符串资源

*/

public static String getString(int resId) {

return getResources().getString(resId);

}

/**

  • 获取color资源

*/

public static int getColor(int resId) {

return getResources().getColor(resId);

}

/**

  • 获取dimens资源

*/

public static float getDimens(int resId) {

return getResources().getDimension(resId);

}

/**

  • 获取字符串数组资源

*/

public static String[] getStringArray(int resId) {

return getResources().getStringArray(resId);

}

7.DateUtil.class(日期时间转换的工具类)

import android.annotation.SuppressLint;

import android.text.format.Time;

import java.text.SimpleDateFormat;

import java.util.Date;

/**

  • 时间、日期转换工具

  • Created by mythmayor on 2016/9/14.

*/

public class DateUtils {

/**

  • 获取当前时间

  • @return 年月日时分秒字符串

*/

public static String getCurrentTime() {

Time time = new Time(“GMT+8”);

time.setToNow();

String year = “” + time.year;

int imonth = time.month + 1;

String month = imonth > 9 ? “” + imonth : “0” + imonth;

String day = time.monthDay > 9 ? “” + time.monthDay : “0”

  • time.monthDay;

String hour = (time.hour + 8) > 9 ? “” + (time.hour + 8) : “0”

  • (time.hour + 8);

String minute = time.minute > 9 ? “” + time.minute : “0” + time.minute;

String sec = time.second > 9 ? “” + time.second : “0” + time.second;

String currentTime = year + month + day + hour + minute + sec;

return currentTime;

}

//获取 日期/时/分/秒

@SuppressLint(“SimpleDateFormat”)

public static String getDateTime(long time) {

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

String date = sdf.format(new Date(time));

return date;

}

//获取 日期/时/分

@SuppressLint(“SimpleDateFormat”)

public static String getHourMinute(long time) {

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分”);

String date = sdf.format(new Date(time));

return date;

}

//获取 日期年月日

@SuppressLint(“SimpleDateFormat”)

public static String getYearMonthDay(long time) {

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月dd日”);

String date = sdf.format(new Date(time));

return date;

}

//获取日期年月

public static String getYearMonth(long time){

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年MM月”);

String date = sdf.format(new Date(time));

return date;

}

//获取日期年月

public static String getYearMonth2(long time){

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM”);

String date = sdf.format(new Date(time));

return date;

}

//获取日期年

public static String getYear(long time){

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy年”);

String date = sdf.format(new Date(time));

return date;

}

//获取 时/分

public static String getTime(long time) {

SimpleDateFormat sdf = new SimpleDateFormat(“HH:mm”);

String date = sdf.format(new Date(time));

return date;

}

}

8.GlideCacheUtil.class(管理Glide产生的缓存的工具类)

/**

  • Created by mythmayor on 2017/2/22.

*/

import android.content.Context;

import android.os.Looper;

import android.text.TextUtils;

import com.bumptech.glide.Glide;

import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;

import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;

import java.io.File;

import java.math.BigDecimal;

/**Glide缓存工具类

  • Created by mythmayor on 2016/10/10.

*/

public class GlideCacheUtil {

private static GlideCacheUtil inst;

public static GlideCacheUtil getInstance() {

if (inst == null) {

inst = new GlideCacheUtil();

}

return inst;

}

/**

  • 清除图片磁盘缓存

*/

public void clearImageDiskCache(final Context context) {

try {

if (Looper.myLooper() == Looper.getMainLooper()) {

new Thread(new Runnable() {

@Override

public void run() {

Glide.get(context).clearDiskCache();

// BusUtil.getBus().post(new GlideCacheClearSuccessEvent());

}

}).start();

} else {

Glide.get(context).clearDiskCache();

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

  • 清除图片内存缓存

*/

public void clearImageMemoryCache(Context context) {

try {

if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行

Glide.get(context).clearMemory();

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

  • 清除图片所有缓存

*/

public void clearImageAllCache(Context context) {

clearImageDiskCache(context);

clearImageMemoryCache(context);

String ImageExternalCatchDir=context.getExternalCacheDir()+ ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;

deleteFolderFile(ImageExternalCatchDir, true);

}

/**

  • 获取Glide造成的缓存大小

  • @return CacheSize

*/

public String getCacheSize(Context context) {

try {

return getFormatSize(getFolderSize(new File(context.getCacheDir() + “/”+ InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));

} catch (Exception e) {

e.printStackTrace();

}

return “”;

}

/**

  • 获取指定文件夹内所有文件大小的和

  • @param file file

  • @return size

  • @throws Exception

*/

private long getFolderSize(File file) throws Exception {

long size = 0;

try {

File[] fileList = file.listFiles();

for (File aFileList : fileList) {

if (aFileList.isDirectory()) {

size = size + getFolderSize(aFileList);

} else {

size = size + aFileList.length();

}

}

} catch (Exception e) {

e.printStackTrace();

}

return size;

}

/**

  • 删除指定目录下的文件,这里用于缓存的删除

  • @param filePath filePath

  • @param deleteThisPath deleteThisPath

*/

private void deleteFolderFile(String filePath, boolean deleteThisPath) {

if (!TextUtils.isEmpty(filePath)) {

try {

File file = new File(filePath);

if (file.isDirectory()) {

File files[] = file.listFiles();

for (File file1 : files) {

deleteFolderFile(file1.getAbsolutePath(), true);

}

}

if (deleteThisPath) {

if (!file.isDirectory()) {

file.delete();

} else {

if (file.listFiles().length == 0) {

file.delete();

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

  • 格式化单位

  • @param size size

  • @return size

*/

private static String getFormatSize(double size) {

double kiloByte = size / 1024;

if (kiloByte < 1) {

return size + “B”;

}

double megaByte = kiloByte / 1024;

if (megaByte < 1) {

BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));

return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + “KB”;

}

double gigaByte = megaByte / 1024;

if (gigaByte < 1) {

BigDecimal result2 = new BigDecimal(Double.toString(megaByte));

return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + “MB”;

}

double teraBytes = gigaByte / 1024;

if (teraBytes < 1) {

BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));

return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + “GB”;

}

BigDecimal result4 = new BigDecimal(teraBytes);

return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + “TB”;

}

}

9.JsonUtil.class(管理Json数据的工具类)

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

public class JsonUtils {

public static Map<String, Object> jsonToMap(String jsonString) {

Map<String, Object> map = new HashMap<String, Object>();

try {

JSONObject json = new JSONObject(jsonString);

Iterator<?> it = json.keys();

String key = null;

Object value = null;

while (it.hasNext()) {

key = it.next().toString();

value = json.get(key);

if (value.toString().equals(“null”) || value.toString().equals(“”)) {

value = “”;

}

map.put(key, value);

}

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

return map;

}

public static JSONObject mapToJson(@SuppressWarnings(“rawtypes”) Map map) {

JSONObject json = null;

json = new JSONObject(map);

return json;

}

public static List<Map<String, Object>> jsonToList(String jsonArrayString) {

List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

try {

JSONArray array = new JSONArray(jsonArrayString);

for (int i = 0; i < array.length(); i++) {

JSONObject json = array.getJSONObject(i);

Map<String, Object> map = jsonToMap(json.toString());

list.add(map);

}

} catch (JSONException e) {

e.printStackTrace();

return null;

}

return list;

}

/**

  • @param json

  • @return

*/

public static Map<String, Object> jsonToMap(JSONObject json) {

Map<String, Object> map = new HashMap<String, Object>();

try {

Iterator<?> it = json.keys();

String key = null;

Object value = null;

while (it.hasNext()) {

key = it.next().toString();

value = json.get(key);

if (value.toString().equals(“null”) || value.toString().equals(“”)) {

value = “”;

}

map.put(key, value);

}

} catch (JSONException e) {

e.printStackTrace();

return null;

}

return map;

}

/**

  • @param array

  • @return

*/

public static List<Map<String, Object>> jsonToList(JSONArray array) {

List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

try {

for (int i = 0; i < array.length(); i++) {

JSONObject json = array.getJSONObject(i);

Map<String, Object> map = jsonToMap(json.toString());

list.add(map);

}

} catch (JSONException e) {

e.printStackTrace();

return null;

}

return list;

}

/**

  • @param json

  • @param name

  • @return

*/

public static int getInt(JSONObject json, String name) {

if (json.has(name)) {

try {

if (!json.getString(name).equals(“null”) & json.getString(name) != “”)

return json.getInt(name);

return -100;

} catch (JSONException e) {

e.printStackTrace();

}

}

return 0;

}

/**

  • @param array

  • @param index

  • @return

*/

public static int getInt(JSONArray array, int index) {

try {

return array.getInt(index);

} catch (JSONException e) {

e.printStackTrace();

}

return 0;

}

/**

  • @param json

  • @param name

  • @return

*/

public static String getString(JSONObject json, String name) {

if (json.has(name)) {

try {

if (json.has(name) && !json.getString(name).equals(“null”) && json.getString(name) != “”)

return json.getString(name);

return “”;

} catch (JSONException e) {

e.printStackTrace();

}

}

return “”;

}

/**

  • @param array

  • @param index

  • @return

*/

public static String getString(JSONArray array, int index) {

String s = “”;

try {

s = array.getString(index);

} catch (JSONException e) {

e.printStackTrace();

}

return s;

}

/**

  • @param json

  • @param arrayName

  • @return

*/

public static JSONArray getJSONArray(JSONObject json, String arrayName) {

JSONArray array = new JSONArray();

try {

if (json.has(arrayName))

array = json.getJSONArray(arrayName);

} catch (JSONException e) {

e.printStackTrace();

}

return array;

}

/**

  • @param array

  • @param index

  • @return

*/

public static JSONObject getJSONObject(JSONArray array, int index) {

JSONObject json = new JSONObject();

try {

json = array.getJSONObject(index);

} catch (JSONException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return json;

}

/**

  • @param json

  • @param name

  • @return

*/

public static JSONObject getJSONObject(JSONObject json, String name) {

JSONObject json2 = new JSONObject();

try {

if (json.has(name))

json2 = json.getJSONObject(name);

} catch (JSONException e) {

e.printStackTrace();

}

return json2;

}

// public static String resolveUri(String uri){

// return Constants.URI+uri;

// }

}

10.MyCountDownTimer.class(验证码倒计时及重新发送验证码的工具类)

import android.os.CountDownTimer;

import android.widget.Button;

/**

  • Created by mythmayor on 2017/4/17.

*/

public class MyCountDownTimer extends CountDownTimer {

private Button mBtn;

private int mEnable;

private int mDisable;

/**

  • @param millisInFuture The number of millis in the future from the call

  •                      to {@link #start()} until the countdown is done and {@link #onFinish()}
    
  •                      is called.
    
  • @param countDownInterval The interval along the way to receive

  •                      {@link #onTick(long)} callbacks.
    

*/

public MyCountDownTimer(long millisInFuture, long countDownInterval, Button btn, int enable, int disable) {

super(millisInFuture, countDownInterval);

mBtn = btn;

mEnable = enable;

mDisable = disable;

}

//计时过程

@Override

public void onTick(long l) {

//防止计时过程中重复点击

mBtn.setClickable(false);

mBtn.setText(l / 1000 + “s”);

//设置按钮背景色

mBtn.setBackgroundResource(mDisable);

}

//计时完毕的方法

@Override

public void onFinish() {

//重新给Button设置文字

mBtn.setText(“重新获取验证码”);

//设置可点击

mBtn.setClickable(true);

//设置按钮背景色

mBtn.setBackgroundResource(mEnable);

}

学习分享,共勉

Android高级架构师进阶之路

题外话,我在阿里工作多年,深知技术改革和创新的方向,Android开发以其美观、快速、高效、开放等优势迅速俘获人心,但很多Android兴趣爱好者所需的进阶学习资料确实不太系统,完整。今天我把我搜集和整理的这份学习资料分享给有需要的人

  • Android进阶知识体系学习脑图

  • Android进阶高级工程师学习全套手册

  • 对标Android阿里P7,年薪50w+学习视频

  • 大厂内部Android高频面试题,以及面试经历


《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
is called.

  • @param countDownInterval The interval along the way to receive

  •                      {@link #onTick(long)} callbacks.
    

*/

public MyCountDownTimer(long millisInFuture, long countDownInterval, Button btn, int enable, int disable) {

super(millisInFuture, countDownInterval);

mBtn = btn;

mEnable = enable;

mDisable = disable;

}

//计时过程

@Override

public void onTick(long l) {

//防止计时过程中重复点击

mBtn.setClickable(false);

mBtn.setText(l / 1000 + “s”);

//设置按钮背景色

mBtn.setBackgroundResource(mDisable);

}

//计时完毕的方法

@Override

public void onFinish() {

//重新给Button设置文字

mBtn.setText(“重新获取验证码”);

//设置可点击

mBtn.setClickable(true);

//设置按钮背景色

mBtn.setBackgroundResource(mEnable);

}

学习分享,共勉

Android高级架构师进阶之路

题外话,我在阿里工作多年,深知技术改革和创新的方向,Android开发以其美观、快速、高效、开放等优势迅速俘获人心,但很多Android兴趣爱好者所需的进阶学习资料确实不太系统,完整。今天我把我搜集和整理的这份学习资料分享给有需要的人

  • Android进阶知识体系学习脑图

[外链图片转存中…(img-1EyrysIr-1714480547676)]

  • Android进阶高级工程师学习全套手册

[外链图片转存中…(img-zLlIYbt7-1714480547677)]

  • 对标Android阿里P7,年薪50w+学习视频

[外链图片转存中…(img-VBfgKGXU-1714480547677)]

  • 大厂内部Android高频面试题,以及面试经历

[外链图片转存中…(img-zRfuLkNV-1714480547677)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 15
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值