Android-開発常用ツール類Utils
54212 ワード
転載は出典を明記してください.https://blog.csdn.net/mythmayor/article/details/72843153
1.ToastUtil.Class(Toastを示すツールクラス)
2.PrefUtil.Class(SharedPreferencesを管理するツールクラス)
3.IntentUtil.class(Activityジャンプのツールクラス)
4.FileUtil.class(ファイル管理ツールクラス)
5.DensityUtil.class(単位変換と画面幅の高さを取得するツールクラス)
6.ResourceUtil.class(リソースファイルを取得するツールクラス)
7.DateUtil.class(日付時間変換のツールクラス)
8.GlideCacheUtil.class(Glideによって生成されたキャッシュを管理するツールクラス)
9.JsonUtil.class(Jsonデータを管理するツールクラス)
10.MyCountDownTimer.class(検証コードカウントダウンおよび検証コードを再送信するツールクラス)
11.ProgressDlgUtil.Class(ProgressDialogで使用されるツールクラス)
1.ToastUtil.Class(Toastを示すツールクラス)
import android.content.Context;
import android.widget.Toast;
/**
* Created by mythmayor on 2016/12/14.
*/
public class ToastUtil {
private static String oldMsg;
protected static Toast toast = null;
private static long oneTime = 0;
private static long twoTime = 0;
public static void showToast(Context context, String s) {
if (toast == null) {
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
toast.show();
oneTime = System.currentTimeMillis();
} else {
twoTime = System.currentTimeMillis();
if (s.equals(oldMsg)) {
if (twoTime - oneTime > Toast.LENGTH_SHORT) {
toast.show();
}
} else {
oldMsg = s;
toast.setText(s);
toast.show();
}
}
oneTime = twoTime;
}
public static void showToast(Context context, int resId) {
showToast(context, context.getString(resId));
}
}
2.PrefUtil.Class(SharedPreferencesを管理するツールクラス)
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mythmayor on 2016/12/14.
*
* SharePreference ,
*/
public class PrefUtil {
private static final String SHARE_PREFS_NAME = "mythmayor";
public static void putBoolean(Context ctx, String key, boolean value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putBoolean(key, value).commit();
}
public static boolean getBoolean(Context ctx, String key,
boolean defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getBoolean(key, defaultValue);
}
public static void putString(Context ctx, String key, String value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putString(key, value).commit();
}
public static String getString(Context ctx, String key, String defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getString(key, defaultValue);
}
public static void putInt(Context ctx, String key, int value) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().putInt(key, value).commit();
}
public static int getInt(Context ctx, String key, int defaultValue) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
return pref.getInt(key, defaultValue);
}
public static void clear(Context ctx) {
SharedPreferences pref = ctx.getSharedPreferences(SHARE_PREFS_NAME,
Context.MODE_PRIVATE);
pref.edit().clear().commit();
}
}
3.IntentUtil.class(Activityジャンプのツールクラス)
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by mythmayor on 2016/12/14.
*/
public class IntentUtil {
public static void startActivity(Context context, Class> cls) {
Intent intent = new Intent();
intent.setClass(context, cls);
context.startActivity(intent);
}
public static void startActivityWithExtra(Context context, Bundle bundle, Class> cls) {
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(context, cls);
context.startActivity(intent);
}
public static void startActivityClearTask(Context context, Class> cls) {
Intent intent = new Intent();
intent.setClass(context, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static void startActivityClearTaskWithExtra(Context context, Bundle bundle, Class> cls) {
Intent intent = new Intent();
intent.putExtras(bundle);
intent.setClass(context, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public static void startIntentActivity(Context context, String mTitle, String url, Class> cls) {
Intent intent = new Intent();
intent.setClass(context, cls);
intent.putExtra(MyConstant.INTENT_EXTRA_TITLE, mTitle);
intent.putExtra(MyConstant.INTENT_EXTRA_URL, url);
context.startActivity(intent);
}
}
4.FileUtil.class(ファイル管理ツールクラス)
import java.io.File;
import java.text.DecimalFormat;
/**
* Created by mythmayor on 2016/12/26.
*/
public class FileUtil {
/**
*
*
* @param f
* @return
* @throws Exception
*/
public static long getFileSize(File f) throws Exception {
long size = 0;
File[] flist = f.listFiles();
for (int i = 0; i < flist.length; i++) {
if (flist[i].isDirectory()) {
size = size + getFileSize(flist[i]);
} else {
size = size + flist[i].length();
}
}
return size;
}
/**
*
*
* @param fileS , b
* @return
*/
public static String FormetFileSize(long fileS) {
DecimalFormat df = new DecimalFormat("0.00");
String fileSizeString;
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "K";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "M";
} else {
fileSizeString = df.format((double) fileS / 1073741824) + "G";
}
return fileSizeString;
}
}
5.DensityUtil.class(単位変換と画面幅の高さを取得するツールクラス)
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
/**
* Created by mythmayor on 2016/12/14.
*/
public class DensityUtil {
/**
* px dip dp ,
*
* @param pxValue
* @param context Context
* @return dp
*/
public static int px2dip(float pxValue, Context context) {
float scale = getDensity(context);
return (int) (pxValue / scale + 0.5f);
}
/**
* dip dp px ,
*
* @param dipValue dip
* @param context Context
* @return
*/
public static int dip2px(float dipValue, Context context) {
float scale = getDensity(context);
return (int) (dipValue * scale + 0.5f);
}
/**
* px sp ,
*
* @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 jsonToMap(String jsonString) {
Map map = new HashMap();
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
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);
}
}
11.ProgressDlgUtil.Class(ProgressDialogで使用されるツールクラス)
import android.app.ProgressDialog;
import android.content.Context;
/**
* Created by mythmayor on 2017/3/29.
*/
public class ProgressDlgUtil {
private static ProgressDialog progressDlg = null;
/**
*
* @param ctx activity
* @param content
*/
public static void show(Context ctx, String content) {
if (null == progressDlg) {
progressDlg = new ProgressDialog(ctx);
progressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);//
//progressDlg.setTitle(" ");//
progressDlg.setMessage(content);//
progressDlg.setIndeterminate(false);
progressDlg.setCancelable(false);
//progressDlg.setIcon(R.drawable.ic_launcher_scale);
progressDlg.show();
}
}
/**
*
*/
public static void dismiss() {
if (null != progressDlg) {
progressDlg.dismiss();
progressDlg = null;
}
}
}