一、activity任务栈管理
AppManager管理activity的任务栈,activity跳转的进入退出动画:
public class AppManager {
private static Stack<Activity> mActivityStack;
private static AppManager mAppManager;
private AppManager() {}
public static AppManager getInstance() {
if (mAppManager == null)
mAppManager = new AppManager();
return mAppManager;
}
/**
* 添加Activity到堆
*/
public void addActivity(Activity activity) {
if (mActivityStack == null)
mActivityStack = new Stack<>();
mActivityStack.add(activity);
}
/**
* 获取栈顶Activity
*/
public Activity getTopActivity() {
Activity activity = mActivityStack.lastElement();
return activity;
}
/**
* 结束栈顶Activity
*/
public void killTopActivity() {
Activity activity = mActivityStack.lastElement();
killActivity(activity);
}
/**
* 结束指定的Activity
*/
public void killActivity(Activity activity) {
if (activity != null) {
boolean res = mActivityStack.remove(activity);
activity.finish();
}
}
/**
* 结束指定类名的Activity
*/
public void killActivity(Class<?> cls) {
try {
for (Activity activity : mActivityStack) {
if (activity.getClass().equals(cls)) {
killActivity(activity);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 结束所有Activity
*/
public void killAllActivity() {
for (int i = 0, size = mActivityStack.size(); i < size; i++) {
if (null != mActivityStack.get(i)) {
mActivityStack.get(i).finish();
}
}
mActivityStack.clear();
}
/**
* 退出应用程序
*/
public void AppExit(Context context) {
try {
killAllActivity();
System.exit(0);
} catch (Exception e) {
}
}
/**
* activity的进入动画
* @param context
* @param intent
*/
public static void enterActivity(Activity context, Intent intent) {
context.startActivity(intent);
context.overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
}
public static void enterActivity(Activity context, Intent intent, int requestCode) {
context.startActivityForResult(intent, requestCode);
context.overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
}
/**
* activity的退出动画
*/
public static void exitActivity(Activity context) {
context.finish();
context.overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
}
/**
* APP是否处于前台唤醒状态
* @return
*/
public boolean isAppOnForeground() {
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String packageName = getApplicationContext().getPackageName();
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
CameraUtils简单的调用相机和相册和选择图片方法,由于andoid的机型适配比较坑,如果需要裁剪建议使用ucrop(giutihub地址:https://github.com/Yalantis/uCrop),基本上能解决机型问题带来的各类问题
二、px与dp转换
DensityUtils物理像素单位与android的虚拟单位的换算工具类
public class DensityUtil {
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* 获取屏幕宽度
*/
public static int getWindowWidth(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
/**
* 获取屏幕高度
*/
public static int getwindowHeight(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
return dm.heightPixels;
}
}
三、设备唯一 标识
DeviceUtils获取android设备唯一标识
public class DeviceUtils {
private UUID uuid;
public UUID getUuid() {
return uuid;
}
public DeviceUtils(Context context) {
if (uuid == null) {
synchronized (DeviceUtils.class) {
if (uuid == null) {
if (context.getSharedPreferences("device_id.xml", 0).getString("device_id",null)!= null) {
uuid = UUID.fromString(context.getSharedPreferences("device_id.xml", 0).getString("device_id",null));
} else {
try {
if (!"9774d56d682e549c".equals(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID))) {
uuid = UUID.nameUUIDFromBytes(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf8"));
} else {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
uuid = telephony.getDeviceId() != null ?
UUID.nameUUIDFromBytes(telephony.getDeviceId().getBytes("utf8")) :
UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
public static String getUniqueId(Context context){
String androidID = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
String id = androidID + Build.SERIAL;
return MD5Util.getMD5Str(id);
}
}
Glide加载图片,配置缓存
1、glide加载方形、圆角、圆形图片
public class GlideUtils {
private static GlideUtils mInstance;
private GlideUtils(){};
public static GlideUtils getInstance(){
if (mInstance!=null)
mInstance=new GlideUtils();
return mInstance;
};
private class GlideCircleTransform extends BitmapTransformation {
private GlideCircleTransform(Context context) {
super(context);
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return circleCrop(pool, toTransform);
}
private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
return result;
}
@Override
public String getId() {
return getClass().getName();
}
}
private class GlideRoundTransform extends BitmapTransformation {
private float radius = 0f;
private GlideRoundTransform(Context context) {
this(context, 4);
}
private GlideRoundTransform(Context context, int dp) {
super(context);
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
return roundCrop(pool, toTransform);
}
private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
@Override
public String getId() {
return getClass().getName() + Math.round(radius);
}
}
//加载普通图片
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public void loadRectImg(Fragment fragment, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(fragment.getActivity()).load(rid).error(rid).placeholder(rid).into(imageView);
}else{
if (!path.startsWith("http"))
path=Constants.BASE_IMG+path;
Glide.with(fragment.getActivity()).load(path).error(rid).placeholder(rid).into(imageView);
}
}
/**
* @param context
* @param path 图片路径
* @param rid 本地资源图图片
* @param imageView 需要加载图片的image
*/
public void loadRectImg(Context context, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(context.getApplicationContext()).load(rid).error(rid).placeholder(rid).into(imageView);
}else{
if (!path.startsWith("http")) //如果服务器配置了负载均衡,返回的必然是全路径,不要判断是否是半路径
path=Constants.BASE_IMG+path;
Glide.with(context.getApplicationContext()).load(path).error(rid).placeholder(rid).into(imageView);
}
}
// 加载圆形图片
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public void loadCircleImg(Fragment fragment, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(fragment.getActivity()).load(rid).error(rid).placeholder(rid).transform(new GlideCircleTransform(fragment.getActivity())).into(imageView);
}else{
if (!path.startsWith("http"))
path=Constants.BASE_IMG+path;
Glide.with(fragment.getActivity()).load(path).error(rid).transform(new GlideCircleTransform(fragment.getActivity())).placeholder(rid).into(imageView);
}
}
public void loadCircleImg(Context context, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(context.getApplicationContext()).load(rid).error(rid).placeholder(rid).transform(new GlideCircleTransform(context.getApplicationContext())).into(imageView);
}else{
if (!path.startsWith("http"))
path=Constants.BASE_IMG+path;
Glide.with(context.getApplicationContext()).load(path).error(rid).transform(new GlideCircleTransform(context.getApplicationContext())).placeholder(rid).into(imageView);
}
}
//圆角图片
@RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
public void loadRoundImg(Fragment fragment, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(fragment.getActivity()).load(rid).error(rid).placeholder(rid).transform(new GlideRoundTransform(fragment.getActivity())).into(imageView);
}else{
if (!path.startsWith("http"))
path=Constants.BASE_IMG+path;
Glide.with(fragment.getActivity()).load(path).error(rid).transform(new GlideRoundTransform(fragment.getActivity())).placeholder(rid).into(imageView);
}
}
public void loadRoundImg(Context context, String path, int rid, ImageView imageView){
if (TextUtils.isEmpty(path)){
Glide.with(context.getApplicationContext()).load(rid).error(rid).placeholder(rid).transform(new GlideRoundTransform(context.getApplicationContext())).into(imageView);
}else{
if (!path.startsWith("http"))
path=Constants.BASE_IMG+path;
Glide.with(context.getApplicationContext()).load(path).error(rid).transform(new GlideRoundTransform(context.getApplicationContext())).placeholder(rid).into(imageView);
}
}
}
四、Glide缓存配置
glide配置缓存,在配置文件中加入meta标签,注册缓存类
<meta-data
android:name="应用包名.GlideConfiguration"
android:value="GlideModule" />
public class GlideConfiguration implements GlideModule {
@Override
public void applyOptions(Context context, GlideBuilder glideBuilder) {
glideBuilder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888);
glideBuilder.setDiskCache(new DiskLruCacheFactory(Constants.CACHE_PATH, calculateMemoryCacheSize(context.getApplicationContext())));
}
@Override
public void registerComponents(Context context, Glide glide) {
}
private static int calculateMemoryCacheSize(Context context) {
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
boolean largeHeap = (context.getApplicationInfo().flags & 1048576) != 0;
int memoryClass = am.getMemoryClass();
if(largeHeap && Build.VERSION.SDK_INT >= 11) {
memoryClass = am.getLargeMemoryClass();
}
return 1048576 * memoryClass / 7;
}
}
五、SharedPreferences存储
SharedPreferences简易封装,简化本地轻量级数据存储
public class SpUtils {
/**
* Preferences记录名称
*/
private static final String NAME ="CN_FCW_SP";
static {
}
public static SharedPreferences getInstance(Context context) {
return context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
}
public static void setUserInfo(Context context,String user) {//此处可将用户信息存储为json字符串吗使用是可将使用json解析工具,将json字符串转换成user对象便于调用
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("user_info", user);
editor.apply();
}
public static String getUserInfo(Context context){
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getString("user_info", "");
}
public static void setStr(Context context, String key, String value) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
public static String getStr(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getString(key, "");
}
public static void setInt(Context context, String key, int value) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();
}
public static int getInt(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getInt(key, 0);
}
public static void setFloat(Context context, String key, Float value) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putFloat(key, value);
editor.apply();
}
public static Float getFloat(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getFloat(key, 0);
}
public static void setLong(Context context, String key, long value) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putLong(key, value);
editor.apply();
}
public static long getLong(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getLong(key, 0L);
}
public static void setBool(Context context, String key, boolean value) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.apply();
}
public static boolean getBool(Context context, String key) {
SharedPreferences preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
}
六、复合文本SpannableString
StringUtils基本数据类型与string相互转换,andorid复合文本SpannableString 配置
public class StringUtills {
public static long string2Long(String str){
return Long.parseLong(TextUtils.isEmpty(str)?"0":str);
}
public static int string2Int(String str){
return Integer.parseInt(TextUtils.isEmpty(str)?"0":str);
}
public static double string2Double(String str){
return Double.parseDouble(TextUtils.isEmpty(str)?"0.00":str);
}
public static float string2Float(String str){
return Float.parseFloat(TextUtils.isEmpty(str)?"0.00":str);
}
public static String priceFormat(double d) {
DecimalFormat df = new DecimalFormat("######0.00");
return df.format(d);
}
public static String priceFormat(float d) {
DecimalFormat df = new DecimalFormat("######0.00");
return df.format(d);
}
//ForegroundColorSpan 文本颜色
public static SpannableString setForegroundColorSpan(String str, int color,int s,int e) {
SpannableString spanString = new SpannableString(str);
ForegroundColorSpan span = new ForegroundColorSpan(color);
spanString.setSpan(span, s,e,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// BackgroundColorSpan 文本背景色
public static SpannableString setBackgroundColorSpan(String str, int color,int s,int e) {
SpannableString spanString = new SpannableString(str);
BackgroundColorSpan span = new BackgroundColorSpan(color);
spanString.setSpan(span, s,e,Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// StyleSpan 字体样式:粗体、斜体等
public static SpannableString setStyleSpan(String str, int color,int s,int e) {
SpannableString spanString = new SpannableString(str);
StyleSpan span = new StyleSpan(Typeface.BOLD);
spanString.setSpan(span, s,e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// RelativeSizeSpan 相对大小
public static void setRelativeFontSpan(String str, int color,int s,int e,float fontSize) {
SpannableString spanString = new SpannableString(str);
spanString.setSpan(new RelativeSizeSpan(fontSize),s, e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
// TypefaceSpan 文本字体
public static SpannableString setTypefaceSpan(String str, String typefaceSpan,int color,int s,int e) {
SpannableString spanString = new SpannableString(str);
spanString.setSpan(new TypefaceSpan(typefaceSpan), s, e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// URLSpan 文本超链接
public static SpannableString addUrlSpan(String str,String url,int s,int e) {
SpannableString spanString = new SpannableString(str);
URLSpan span = new URLSpan(url);
spanString.setSpan(span, s ,e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// ImageSpan 图片
public static SpannableString addImageSpan(String str, Drawable drawable,int s,int e) {
SpannableString spanString = new SpannableString(str);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
spanString.setSpan(span, s, e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// UnderlineSpan 下划线
public static SpannableString addUnderLineSpan(TextView tv, String str) {
SpannableString spanString = new SpannableString(str);
UnderlineSpan span = new UnderlineSpan();
spanString.setSpan(span, 0, str.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// StrikethroughSpan 删除线
public static SpannableString addStrikeSpan(String str,int s,int e) {
SpannableString spanString = new SpannableString(str);
StrikethroughSpan span = new StrikethroughSpan();
spanString.setSpan(span, s, e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
// TextAppearanceSpan 文本外貌(包括字体、大小、样式和颜色)
public static SpannableString setTextAppearanceSpan(String str, TextAppearanceSpan textAppearanceSpan,int s,int e) {
SpannableString spanString = new SpannableString(str);
spanString.setSpan(textAppearanceSpan, s, e, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return spanString;
}
}