Commit 3dbab070 by gao.chao

工具类

时间-
尺寸转换-
log-
下载图片-
文件-
本地参数存储-
算术运算(加减乘除)-
二维码生成与解码-
toast-
下载安装APK
验证(手机号,中文,邮箱)-
图片--

第三方集成
加载网络图片(picasso)-
统一web内核 X5Webview-
网络访问(okhttp)-
Logger-
bugly-
fastgson,recyclerview-
parent 3bc7daa0
......@@ -3,6 +3,7 @@
package="com.mayi.demo">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
......@@ -17,7 +18,13 @@
</intent-filter>
</activity>
<activity android:name=".TsetActviity"/>
<activity android:name=".TsetActviity" />
<activity android:name=".QRActivity" />
</application>
<!-- 配置APP ID -->
<meta-data
android:name="BUGLY_APPID"
android:value="cb8018da1b" />
</manifest>
\ No newline at end of file
......@@ -10,6 +10,8 @@ import android.view.ViewGroup;
import android.widget.Button;
import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.util.LogUtils;
import com.mayi.fastdevelop.util.SpUtil;
import java.util.ArrayList;
import java.util.List;
......@@ -26,7 +28,17 @@ public class MainActivity extends BaseActivity {
list.add(new ItemBean("BaseActivity", new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoActivity(TsetActviity.class);
LogUtils.postCatchedException(new Exception("11"));
SpUtil.set("ss",System.currentTimeMillis());
LogUtils.i("ss="+ SpUtil.get("ss",-1L));
// gotoActivity(TsetActviity.class);
}
}));
list.add(new ItemBean("二维码", new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoActivity(QRActivity.class);
}
}));
listView.setAdapter(new RecyclerView.Adapter<MyViewHolder>() {
......
package com.mayi.demo;
import android.app.Application;
import com.mayi.fastdevelop.base.BaseApplication;
public class MyApplication extends BaseApplication{
@Override
public void onCreate() {
super.onCreate();
initBugly("cb8018da1b",true);
}
@Override
public Application getChildApplication() {
return this;
}
@Override
public boolean isShowLog() {
return BuildConfig.DEBUG;
}
}
package com.mayi.demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.util.BitmapUtil;
import com.mayi.fastdevelop.util.QrUtil;
public class QRActivity extends BaseActivity {
private ImageView img1, img2, img0;
private Button bt, bt0;
private EditText et, et0;
private TextView tv;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qr_layout);
bt0 = findViewById(R.id.bt0);
et0 = findViewById(R.id.et0);
tv = findViewById(R.id.tv);
img0 = findViewById(R.id.img0);
img1 = findViewById(R.id.img1);
img2 = findViewById(R.id.img2);
bt = findViewById(R.id.bt);
et = findViewById(R.id.et);
bt0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
img0.setImageBitmap(QrUtil.createBitmap(et0.getText().toString()));
}
});
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
img1.setImageBitmap(QrUtil.createBitmap(QRActivity.this, et.getText().toString(), R.mipmap.ic_launcher));
}
});
img2.setBackgroundResource(R.mipmap.qr_icon);
tv.setText("图片中二维码文字:"+QrUtil.recogQRcode(BitmapUtil.getBitmap(this,R.mipmap.qr_icon)));
}
}
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et0"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文字转二维码" />
<ImageView
android:id="@+id/img0"
android:layout_width="200dp"
android:layout_height="200dp" />
<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="文字转二维码并且中间添加图片" />
<ImageView
android:id="@+id/img1"
android:layout_width="200dp"
android:layout_height="200dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="二维码转文字" />
<ImageView
android:id="@+id/img2"
android:layout_width="200dp"
android:layout_height="200dp" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
\ No newline at end of file
......@@ -3,16 +3,16 @@ apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
// 设置支持的SO库架构
abiFilters 'armeabi', 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
}
}
buildTypes {
......@@ -25,10 +25,20 @@ android {
}
dependencies {
api fileTree(dir: 'libs', include: ['*.jar'])
api fileTree(include: ['*.jar'], dir: 'libs')
api "com.tencent.bugly:crashreport_upgrade:1.3.4"
api 'com.tencent.bugly:nativecrashreport:3.6.0.1'
api 'com.squareup.okhttp3:okhttp:3.10.0'
api 'com.squareup.picasso:picasso:2.5.2'
api 'com.tencent.bugly:crashreport_upgrade:1.3.4'
api 'com.tencent.bugly:nativecrashreport:3.6.0.1'
api 'com.orhanobut:logger:2.2.0'
api 'com.alibaba:fastjson:1.2.12'
api 'com.android.support:recyclerview-v7:28.0.0'
api 'com.android.support:appcompat-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
api files('libs/zixing-core-3.2.0.jar')
implementation files('libs/tbs_sdk_thirdapp_v3.6.0.1371_43624_sharewithdownload_withoutGame_obfs_20181106_121046.jar')
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mayi.fastdevelop" />
xmlns:tools="http://schemas.android.com/tools"
package="com.mayi.fastdevelop">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.READ_LOGS"
tools:ignore="ProtectedPermissions" />
</manifest>
package com.mayi.fastdevelop.base;
import android.app.Application;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import com.mayi.fastdevelop.util.DateUtil;
import com.mayi.fastdevelop.util.FileUtil;
import com.mayi.fastdevelop.util.LogUtils;
import com.mayi.fastdevelop.util.WriteHandler;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.CsvFormatStrategy;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.DiskLogStrategy;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebStorage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public abstract class BaseApplication extends Application {
private static BaseApplication mInstance;
private int logSize = 5 * 1024 * 1024;//默认记录Log文件大小--5M
@Override
public void onCreate() {
mInstance = this;
super.onCreate();
initLog();
initX5Webview();
}
public void initBugly(String key,boolean isDebug){
CrashReport.initCrashReport(getApplicationContext(), key, isDebug);
}
private void initX5Webview() {
//清空所有Cookie
CookieSyncManager.createInstance(getApplicationContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookies(null);
cookieManager.removeAllCookie();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
} else {
CookieSyncManager.getInstance().sync();
}
WebStorage.getInstance().deleteAllData();
//搜集本地tbs内核信息并上报服务器,服务器返回结果决定使用哪个内核。
QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
@Override
public void onViewInitFinished(boolean arg0) {
//x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
LogUtils.i("X5内核加载完成:" + arg0);
}
@Override
public void onCoreInitFinished() {
}
};
//x5内核初始化接口
QbSdk.initX5Environment(getApplicationContext(), cb);
}
/**
* 设置日志文件大小
*
* @param logSize
*/
public void setLogSize(int logSize) {
this.logSize = logSize;
}
private void initLog() {
LogUtils.TAG=getPackageName();
if (isWriteLog()) {
String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getPackageName() + "/logger/";
String folder = diskPath + DateUtil.getCurrentDate();
HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder);
ht.start();
Handler handler = new WriteHandler(ht.getLooper(), folder, logSize);
DiskLogStrategy logStrategy = new DiskLogStrategy(handler);
Logger.addLogAdapter(new DiskLogAdapter(CsvFormatStrategy.newBuilder().tag(getPackageName()).logStrategy(logStrategy).build()));
//删除3天前的日志文件
int logSaveDay = getLogSaveDay();
if (logSaveDay < 1) {
logSaveDay = 3;
}
for (int i = 0; i < 10; i++) {
Date date = new Date(System.currentTimeMillis() - (logSaveDay + i) * 24 * 60 * 60 * 1000);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String time = format.format(date);
FileUtil.deleteFile(diskPath + time);
}
}
Logger.addLogAdapter(new AndroidLogAdapter() {
@Override
public boolean isLoggable(int priority, String tag) {
return isShowLog();
}
});
}
//flie:要删除的文件夹的所在位置
// private void deleteFile(File file) {
// if (file.isDirectory()) {
// File[] files = file.listFiles();
// for (int i = 0; i < files.length; i++) {
// File f = files[i];
// deleteFile(f);
// }
// file.delete();//如要保留文件夹,只删除文件,请注释这行
// }
// }
public static BaseApplication getInstance() {
return mInstance;
}
......@@ -21,4 +133,28 @@ public abstract class BaseApplication extends Application {
*/
public abstract Application getChildApplication();
/**
* 是否显示log
*
* @return
*/
public abstract boolean isShowLog();
/**
* 是否需要记录日志到本地,默认开启
*
* @return
*/
public boolean isWriteLog() {
return true;
}
/**
* 获取日志保留时间不能小于1,默认保留3天
*
* @return
*/
public int getLogSaveDay() {
return 3;
}
}
package com.mayi.fastdevelop.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
public abstract class BaseFragment extends Fragment{
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().finish();
}
}
package com.mayi.fastdevelop.util;
import java.math.BigDecimal;
public class ArithUtil {
/**
* 提供精确的加法运算。
*
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
public static double addScale(double v1, double v2, int scale) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的减法运算。
*
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
*
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
*
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, 0);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
*
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
*
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
package com.mayi.fastdevelop.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 图片帮助工具
*/
public class BitmapUtil {
/**
* 压缩图片文件大小
*
* @param in 需要压缩的图片绝对路径
* @param out 压缩后保存的文件绝对路径
* @param format 输出格式(默认JEPG):Bitmap.CompressFormat.JEPG,Bitmap.CompressFormat.PNG,Bitmap.CompressFormat.WEBP
* @param quality 压缩质量 0-100,越高图片质量越好
* @return 成功true, 不成功false
*/
public static boolean compressImageFile(String in, String out, Bitmap.CompressFormat format, int quality) {
if (!new File(in).exists()) {
return false;
}
if (format == null) {
format = Bitmap.CompressFormat.JPEG;
}
if (quality < 0) {
quality = 0;
} else if (quality > 100) {
quality = 100;
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inJustDecodeBounds = false;
Bitmap inBitmap = BitmapFactory.decodeFile(in, options);
File of = new File(out);
FileOutputStream fos = null;
try {
if (!of.exists()) {
boolean created = of.createNewFile();
if (!created) {
return false;
}
}
fos = new FileOutputStream(of);
inBitmap.compress(format, quality, fos);
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inBitmap != null) {
inBitmap.recycle();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 根据宽高加载图片
*
* @param path 图片本地地址
* @param dstWidth 宽
* @param dstHeight 高
* @return
*/
public static Bitmap loadBitmapFromFile(String path, int dstWidth, int dstHeight) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888;
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calcSampleSize(options, dstWidth, dstHeight);
options.inJustDecodeBounds = false;
options.inPurgeable = true;
options.inInputShareable = true;
Bitmap bm = BitmapFactory.decodeFile(path, options);
return bm;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据宽高加载图片
*
* @param path 图片本地地址
* @param dstWidth 宽
* @param dstHeight 高
* @param minSize 做下特殊处理,小于多少的图片,就整张加载,避免失真
* @return
*/
public static Bitmap loadBitmapFromFile(String path, int dstWidth, int dstHeight, int minSize) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Config.ARGB_8888;
BitmapFactory.decodeFile(path, options);
if (options.outWidth <= minSize && options.outHeight <= minSize) { // 做下特殊处理,小于多少的图片,就整张加载,避免失真
options.inSampleSize = 1;
} else {
options.inSampleSize = calcSampleSize(options, dstWidth, dstHeight);
}
options.inJustDecodeBounds = false;
options.inPurgeable = true;
options.inInputShareable = true;
Bitmap bm = BitmapFactory.decodeFile(path, options);
return bm;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据宽,按比例拿到图片高度
*
* @param path 本地文件路径
* @param dstWidth 宽
* @return
*/
public static int getScaleHeight(String path, int dstWidth) {
int dstHeight = 0;
try {
if (!TextUtils.isEmpty(path) && dstWidth > 0) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
dstHeight = options.outHeight * dstWidth / options.outWidth;
}
} catch (Exception e) {
e.printStackTrace();
}
return dstHeight;
}
/**
* 根据文件路径加载图片
*
* @param path 本地路径
* @return bitmap
*/
public static Bitmap loadBitmapFromFile(String path) {
return BitmapFactory.decodeFile(path);
}
/**
* 按比例加载图片,大于最大宽度的图片,等比例压缩
*
* @param path 本地路径
* @param maxWidth 最大宽度
* @return
*/
public static Bitmap loadBitmapFromFile(String path, int maxWidth) {
int degree = readPictureDegree(path);
Bitmap bm;
if (maxWidth > 0) {
int dstHeight = BitmapUtil.getScaleHeight(path, maxWidth);
bm = loadBitmapFromFile(path, maxWidth, dstHeight);
} else {
bm = loadBitmapFromFile(path);
}
bm = rotaingImageView(degree, bm);
return bm;
}
/**
* 根据资源ID,获取图片的Bitmap对象
*
* @param context 上下文
* @param id 图片资源ID
* @return
*/
public static Bitmap getBitmap(Context context, int id) {
try {
InputStream is = context.getResources().openRawResource(id);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.RGB_565;
options.inJustDecodeBounds = false;
Bitmap btp = BitmapFactory.decodeStream(is, null, options);
is.close();
return btp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 计算inSampleSize
*
* @param options BitmapFactory.Options
* @param dstWidth 缩放宽度
* @param dstHeight 缩放高度
* @return
*/
public static int calcSampleSize(BitmapFactory.Options options, int dstWidth, int dstHeight) {
int height = options.outHeight;
int width = options.outWidth;
int inSampleSize = 1;
if (height > dstHeight || width > dstWidth) {
int samplesize = Math.round((float) height / (float) dstHeight);
inSampleSize = Math.round((float) width / (float) dstWidth);
inSampleSize = Math.max(samplesize, inSampleSize);
}
return inSampleSize;
}
/**
* 根据图片格式保存图片
*
* @param bitmap 图片的Bitmap对象
* @param path 图片的绝对路径
* @param format 图片格式,比如Bitmap.CompressFormat.JPEG
* @return 图片的所在绝对路径
*/
public static String saveBitmapToFormat(Bitmap bitmap, String path, Bitmap.CompressFormat format) {
return saveBitmapToFormat(bitmap, path, format, 100);
}
/**
* 根据图片格式保存图片
*
* @param bitmap 图片的Bitmap对象
* @param path 图片的绝对路径
* @param format 图片格式,比如Bitmap.CompressFormat.JPEG
* @param quality 压缩资料
* @return 图片的所在绝对路径
*/
public static String saveBitmapToFormat(Bitmap bitmap, String path, Bitmap.CompressFormat format, int quality) {
if (path == null || bitmap == null)
return null;
try {
FileOutputStream out = new FileOutputStream(new File(path));
if (bitmap.compress(format, quality, out)) {
out.flush();
out.getFD().sync();
out.close();
}
return path;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param bitmap
* @param path 绝对路径
* @return 图片的所在绝对路径
*/
public static String saveBitmapToFormat(Bitmap bitmap, String path) {
return saveBitmapToFormat(bitmap, path, Bitmap.CompressFormat.JPEG);
}
/**
* 放大缩小图片
*
* @param bitmap
* @param dstWidth
* @param dstHeight
* @return
*/
public static Bitmap scaledBitmap(Bitmap bitmap, int dstWidth, int dstHeight) {
if (bitmap == null)
return null;
int h = bitmap.getHeight();
int w = bitmap.getWidth();
if (w > h) {
if (w > dstWidth || h > dstHeight) {
float scaleWidth = ((float) dstWidth) / w;
float scaleHeight = ((float) dstHeight) / h;
float scale = Math.min(scaleWidth, scaleHeight);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
if (bitmap != newBitmap) {
bitmap.recycle();
}
return newBitmap;
} else {
return bitmap;
}
} else {
if (w > dstWidth || h > dstHeight) {
float scaleWidth = ((float) dstHeight) / w;
float scaleHeight = ((float) dstWidth) / h;
float scale = Math.min(scaleWidth, scaleHeight);
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
if (bitmap != newBitmap) {
bitmap.recycle();
}
return newBitmap;
} else {
return bitmap;
}
}
}
/**
* 根据图片Url 获取图片
*
* @param url 图片URl
* @return bitmap
*/
public static Bitmap getBitmapFromUrl(String url) {
InputStream is = null;
try {
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
conn.disconnect();
return bitmap;
} else {
conn.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}
/**
* 缩放网络图片
*
* @param url 图片Url
* @param width 宽
* @param height 高
* @return bitmap
*/
public static Bitmap getBitmapFromUrl(String url, int width, int height) {
Bitmap bitmap = getBitmapFromUrl(url);
return scaledBitmap(bitmap, width, height);
}
/**
* 获取图片InputStream
*
* @param urlPath 网络Url
* @return
* @throws Exception
*/
public static InputStream getRequest(String urlPath) throws Exception {
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
return conn.getInputStream();
}
return null;
}
/**
* 根据网络Url 获取Drawable
*
* @param url 网络Url
* @return Drawable
* @throws Exception
*/
public static Drawable getDrawableFromUrl(String url) throws Exception {
return Drawable.createFromStream(getRequest(url), null);
}
/**
* 旋转图片
*
* @param b 图片对象
* @param degrees 旋转角度
* @return
*/
public static Bitmap rotateBitmap(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2, (float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {
ex.printStackTrace();
}
}
return b;
}
/**
* 获取Bitmap宽高
*
* @param context 上下文
* @param resourceID 图片资源文件
* @return
*/
public static int[] getBitmapSize(Context context, int resourceID) {
int[] ret = new int[2];
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inDensity = Bitmap.DENSITY_NONE;
BitmapFactory.decodeResource(context.getResources(), resourceID, opts);
ret[0] = opts.outWidth;
ret[1] = opts.outHeight;
return ret;
}
/**
* 获取Bitmap宽高
*
* @param path 图片文件
* @return
*/
public static int[] getBitmapSize(String path) {
try {
BitmapFactory.Options op = new BitmapFactory.Options();
op.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, op);
int h = op.outHeight;
int w = op.outWidth;
return new int[]{w, h};
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* byte数据转Bitmap
*
* @param byteArray 图片的byte数据
* @return
*/
public static Bitmap byteToBitmap(byte[] byteArray) {
if (byteArray.length != 0) {
return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
} else {
return null;
}
}
/**
* byte数据转Drawable
*
* @param byteArray 图片的byte数据
* @return
*/
public static Drawable byteToDrawable(byte[] byteArray) {
ByteArrayInputStream ins = new ByteArrayInputStream(byteArray);
return Drawable.createFromStream(ins, null);
}
/**
* bitmap 转 byte
*
* @param bm 图片bitmap
* @return
*/
public static byte[] bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 将Drawable转化为Bitmap
*
* @param drawable
* @return
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888 : Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* 转灰度图
*
* @param bmpOriginal
* @return
*/
public static Bitmap toGrayscale(Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
/**
* 灰度的圆角图片
*
* @param bmpOriginal
* @return
*/
public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
return toRoundCorner(toGrayscale(bmpOriginal), pixels);
}
/**
* 获得圆角图片的方法
*
* @param bitmap
* @param pixels 一般设成14
* @return
*/
public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 获得带倒影的图片方法
*
* @param bitmap
* @return
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
final int reflectionGap = 4;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
return bitmapWithReflection;
}
/**
* (缩放)重绘图片
*
* @param context Activity
* @param bitmap
* @return
*/
public static Bitmap reDrawBitMap(Activity context, Bitmap bitmap) {
DisplayMetrics dm = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(dm);
int rHeight = dm.heightPixels;
int rWidth = dm.widthPixels;
// float rHeight=dm.heightPixels/dm.density+0.5f;
// float rWidth=dm.widthPixels/dm.density+0.5f;
// int height=bitmap.getScaledHeight(dm);
// int width = bitmap.getScaledWidth(dm);
int height = bitmap.getHeight();
int width = bitmap.getWidth();
float zoomScale;
/** 方式1 **/
// if(rWidth/rHeight>width/height){//以高为准
// zoomScale=((float) rHeight) / height;
// }else{
// //if(rWidth/rHeight<width/height)//以宽为准
// zoomScale=((float) rWidth) / width;
// }
/** 方式2 **/
// if(width*1.5 >= height) {//以宽为准
// if(width >= rWidth)
// zoomScale = ((float) rWidth) / width;
// else
// zoomScale = 1.0f;
// }else {//以高为准
// if(height >= rHeight)
// zoomScale = ((float) rHeight) / height;
// else
// zoomScale = 1.0f;
// }
/** 方式3 **/
if (width >= rWidth)
zoomScale = ((float) rWidth) / width;
else
zoomScale = 1.0f;
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 缩放图片动作
matrix.postScale(zoomScale, zoomScale);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* InputStrean 转 byte数组
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
if (inStream == null) {
return null;
}
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
/**
* 获取图片类型
*
* @param file
* @return
*/
public static String getImageType(File file) {
if (file == null || !file.exists()) {
return null;
}
InputStream in = null;
try {
in = new FileInputStream(file);
String type = getImageType(in);
return type;
} catch (IOException e) {
return null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
}
/**
* 获取图片类型
*
* @param in
* @return
* @see #getImageType(byte[])
*/
public static String getImageType(InputStream in) {
if (in == null) {
return null;
}
try {
byte[] bytes = new byte[8];
in.read(bytes);
return getImageType(bytes);
} catch (IOException e) {
return null;
}
}
/**
* 获取图片类型
*
* @param bytes 2~8 byte at beginning of the image file
* @return image mimetype or null if the file is not image
*/
public static String getImageType(byte[] bytes) {
if (isJPEG(bytes)) {
return "image/jpeg";
}
if (isGIF(bytes)) {
return "image/gif";
}
if (isPNG(bytes)) {
return "image/png";
}
if (isBMP(bytes)) {
return "application/x-bmp";
}
return null;
}
/**
* 是否是JPEG格式
*
* @param b
* @return
*/
private static boolean isJPEG(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
}
/**
* 是否是GIF图片
*
* @param b
* @return
*/
private static boolean isGIF(byte[] b) {
if (b.length < 6) {
return false;
}
return b[0] == 'G' && b[1] == 'I' && b[2] == 'F' && b[3] == '8' && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
}
/**
* 是否是PNG图片
*
* @param b
* @return
*/
private static boolean isPNG(byte[] b) {
if (b.length < 8) {
return false;
}
return (b[0] == (byte) 137 && b[1] == (byte) 80 && b[2] == (byte) 78 && b[3] == (byte) 71 && b[4] == (byte) 13
&& b[5] == (byte) 10 && b[6] == (byte) 26 && b[7] == (byte) 10);
}
/**
* 是否是BMP图片
*
* @param b
* @return
*/
private static boolean isBMP(byte[] b) {
if (b.length < 2) {
return false;
}
return (b[0] == 0x42) && (b[1] == 0x4d);
}
/**
* 读取图片属性:旋转的角度
*
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 旋转图片
*
* @param angle
* @param bitmap
* @return Bitmap
*/
public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
if (bitmap == null) {
return null;
}
//旋转图片 动作
Matrix matrix = new Matrix();
matrix.postRotate(angle);
System.out.println("angle2=" + angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
}
package com.mayi.fastdevelop.util;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* 日期工具
*/
public class DateUtil {
public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String MONTH_DATE_HOUR_MINS_FROMAT = "M月dd日 HH:mm";
public static final String CHINA_MONTH_DATE_FORMAT = "MM月dd日";
public static final String HYPHEN_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String CHINA_FORMAT_YYYY_MM_DD = "yyyy年MM月dd日";
public static final String CHINA_FORMAT_YYYY_MM_DD_HH_MM = "yyyy年MM月dd日 HH点mm分";
public static final String CHINA_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy年MM月dd日 HH点mm分ss秒";
/**
* 获取当前时间
*/
public static String getCurrentTime() {
SimpleDateFormat formatter = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
return formatter.format(new Date());
}
/**
* 获取当前时间
*/
public static String getCurrentTimeShort() {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
return formatter.format(new Date());
}
/**
* 获取当前时间的月日,时分
*
* @return
*/
public static String getCurrentMonthDateHourMin() {
SimpleDateFormat formatter = new SimpleDateFormat(MONTH_DATE_HOUR_MINS_FROMAT, Locale.getDefault());
return formatter.format(new Date());
}
/**
* 获取当前日期
*/
public static String getCurrentDate() {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
return formatter.format(new Date());
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
*
* @param strDate
* @return
*/
public static Date strToDateLong(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将时间格式字符串转换为时间Date
*
* @param strDate
* @return
*/
public static Date strToDate(String strDate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
Date date = null;
try {
date = formatter.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
*
* @param strDate
* @return
*/
public static Date strToDateLong(String strDate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
*
* @param dateDate
* @return
*/
public static String dateToStrLong(java.util.Date dateDate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
*
* @param dateDate
* @return
*/
public static String dateToStrLong2(java.util.Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
String dateString = formatter.format(dateDate);
return dateString;
}
/**
* 两个时间进行比较
*
* @param currentTime 当前时间
* @param nextTime 下个时间
* @return 0 刚好是今天 1超过范围 -1 范围之内
*/
public static long compareTime(String currentTime, String nextTime) {
SimpleDateFormat formatter = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
try {
Date dt1 = formatter.parse(currentTime);
Date dt2 = formatter.parse(nextTime);
return dt2.getTime() - dt1.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 判断两个日期是否同一天
*
* @param currentTime 当前时间
* @param nextTime 下个时间
* @return true 是今天 不是今天
*/
public static boolean isSameDate(String currentTime, String nextTime) {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
try {
Date date1 = formatter.parse(currentTime);
Date date2 = formatter.parse(nextTime);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
boolean isSameYear = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
boolean isSameMonth = isSameYear && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
boolean isSameDate = isSameMonth && cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
return isSameDate;
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
/**
* 两个日期进行比较
*
* @param currentDate 当前日期
* @param nextDate 下个日期
*/
public static boolean compareDate(String currentDate, String nextDate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
Date d1 = sdf.parse(currentDate);
Date d2 = sdf.parse(nextDate);
return d1.before(d2);
} catch (ParseException e) {
e.printStackTrace();
}
return false;
}
/**
* 获取当月的 天数
*/
public static int getCurrentMonthDays() {
Calendar a = Calendar.getInstance();
a.set(Calendar.DATE, 1);
a.roll(Calendar.DATE, -1);
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
/**
* 获取上个月的 天数
*/
public static int getMonthDaysAgo() {
//获取当前时间
Calendar cal = Calendar.getInstance();
//调到上个月
cal.add(Calendar.MONTH, -1);
//得到一个月最最后一天日期(31/30/29/28)
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获取今天是本月第几天
*/
public static int getCurrentMonthDayIndex() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* 获取本月数字
*/
public static int getCurrentMonthIndex() {
return Calendar.getInstance().get(Calendar.MONTH);
}
/**
* 获取本年数字
*/
public static int getCurrentYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
* 获取当月第一天 是星期几
*
* @return 周日 1 周一 2 ...
*/
public static int getMonthFirstDayIndexForWeek() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
return calendar.get(Calendar.DAY_OF_WEEK);//这个结果是以星期天为第一天算出来的,如果要换成星期一开始,减1就行了
}
/**
* 获取今天 是星期几
*
* @return 周日 1 周一 2 ...
*/
public static int getDayIndexForWeek() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DAY_OF_WEEK);//这个结果是以星期天为第一天算出来的,如果要换成星期一开始,减1就行了
}
/**
* 获取今天 是星期几
*
* @return 周日 1 周一 2 ...
*/
public static String getDayIndexForWeekString() {
Calendar calendar = Calendar.getInstance();
int week = calendar.get(Calendar.DAY_OF_WEEK);//这个结果是以星期天为第一天算出来的,如果要换成星期一开始,减1就行了
String weekString = "";
switch (week) {
case 1:
weekString = "日";
break;
case 2:
weekString = "一";
break;
case 3:
weekString = "二";
break;
case 4:
weekString = "三";
break;
case 5:
weekString = "四";
break;
case 6:
weekString = "五";
break;
case 7:
weekString = "六";
break;
}
return weekString;
}
public static String dataToZhDate(String str) {
try {
// 1、将String转换成date
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = fmt.parse(str);
SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日 HH:mm", Locale.getDefault());
String dateString = formatter.format(date);
return dateString;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String dataToZhDate(String str, String format) {
try {
// 1、将String转换成date
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm", Locale.getDefault());
Date date = fmt.parse(str);
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
String dateString = formatter.format(date);
return dateString;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 将inputFormat格式的日期dateString转换为outputFormat格式
*
* @param dateString
* @param inputFormat
* @param outputFormat
* @return outputFormat格式的日期String
*/
public static String dateStringFormatChange(String dateString, String inputFormat, String outputFormat) {
try {
SimpleDateFormat fmt = new SimpleDateFormat(inputFormat, Locale.getDefault());
Date date = fmt.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat(outputFormat, Locale.getDefault());
return formatter.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String dataToZhDate2(String str, String format) {
try {
// 1、将String转换成date
SimpleDateFormat fmt = new SimpleDateFormat(TIME_FORMAT, Locale.getDefault());
Date date = fmt.parse(str);
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
String dateString = formatter.format(date);
return dateString;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String dataToZhDate3(String str, String format, int dec) {
try {
// 1、将String转换成date
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, 0 - dec);
Date date = c.getTime();
return formatter.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringDate(Date d) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = df.format(d);
return str;
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringDateLong(Date d) {
SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
String str = df.format(d);
return str;
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringDateLongTicket(Date d) {
SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
String str = df.format(d);
return str;
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringDateShort(Date d) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
String dateString = formatter.format(d);
return dateString;
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getMessageStringDate(Date d) {
SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日 HH:mm");
String dateString = formatter.format(d);
return dateString;
}
/**
* 获取时间
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String getStringDateYYMMDDhhmm(Date d) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String dateString = formatter.format(d);
return dateString;
}
public static boolean isServiceHours() {
boolean isServiceHours = false;
Date startDate = new Date();
startDate.setHours(7);
startDate.setMinutes(30);
Date endDate = new Date();
endDate.setHours(20);
endDate.setMinutes(00);
Date curDate = new Date();
if (curDate.after(startDate) && curDate.before(endDate)) {
isServiceHours = true;
}
return isServiceHours;
}
public static long timeIntervalOfMinutes(Date sDate1, Date sDate2) {
long minutes = 0;
if (sDate1 != null && sDate2 != null) {
long temp = sDate1.getTime() - sDate2.getTime();
// long hours = temp / 1000 / 3600; // 相差小时数
long mins = temp / 1000 / 60;
minutes = mins;
}
return minutes;
}
public static long timeIntervalOfMinutes(String sDate1, String sDate2) {
long minutes = 0;
if (!TextUtils.isEmpty(sDate1) && !TextUtils.isEmpty(sDate2)) {
String formatStr = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat format = new SimpleDateFormat(formatStr, Locale.getDefault());
try {
Date date1 = format.parse(sDate1);
Date date2 = format.parse(sDate2);
long temp = date1.getTime() - date2.getTime();
// long hours = temp / 1000 / 3600; // 相差小时数
long mins = temp / 1000 / 60;
minutes = mins;
} catch (ParseException e) {
e.printStackTrace();
}
}
return minutes;
}
/**
* 获得时间标签
*
* @param time
* @return
*/
public static String getTimeLabel(String time) {
String timeLabel = "";
if (TextUtils.isEmpty(time)) {
return timeLabel;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
long publishedTime = 0;
try {
Date date = format.parse(time);
publishedTime = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
if (publishedTime > 0) {
Date Pubdate = new Date(publishedTime);
Date nowDate = new Date();
long temp = Math.abs(nowDate.getTime() - Pubdate.getTime());
long years = temp / 1000 / 3600 / 24 / 365;
long months = temp / 1000 / 3600 / 24 / 30;
long days = temp / 1000 / 3600 / 24;
long hours = temp / 1000 / 3600; // 相差小时数
long mins = temp / 1000 / 60;
if (mins < 5) {
timeLabel = "刚刚";
} else if (mins >= 5 && mins < 60) {
timeLabel = mins + "分钟前";
} else if (mins >= 60 && hours < 24) {
timeLabel = hours + "小时前";
} else if (hours >= 24 && days < 30) {
timeLabel = days + "天前";
} else if (days >= 30 && years < 1) {
timeLabel = months + "个月前";
} else if (years >= 1) {
timeLabel = years + "年前";
}
}
return timeLabel;
}
/**
* 获得时间标签 兼容未来时间
*
* @param time
* @return
*/
public static String getTimeTips(String time) {
String timeLabel = "";
if (TextUtils.isEmpty(time)) {
return timeLabel;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
long publishedTime = 0;
try {
Date date = format.parse(time);
publishedTime = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
if (publishedTime > 0) {
Date Pubdate = new Date(publishedTime);
Date nowDate = new Date();
long temp = nowDate.getTime() - Pubdate.getTime();
boolean isBefore = temp > 0;
temp = Math.abs(temp);
long years = temp / 1000 / 3600 / 24 / 365;
long months = temp / 1000 / 3600 / 24 / 30;
long days = temp / 1000 / 3600 / 24;
long hours = temp / 1000 / 3600; // 相差小时数
long mins = temp / 1000 / 60;
/// >0 发布时间 在当前时间之前 < 0 发布时间为未来时间
if (isBefore) {
if (mins < 3) {
timeLabel = "刚刚";
} else if (mins >= 3 && mins < 60) {
timeLabel = mins + "分钟前";
} else if (mins >= 60 && hours < 24) {
timeLabel = hours + "小时前";
} else if (hours >= 24 && days < 30) {
timeLabel = days + "天前";
} else if (days >= 30 && years < 1) {
timeLabel = months + "个月前";
} else if (years >= 1) {
timeLabel = years + "年前";
}
} else {
if (mins < 3) {
timeLabel = "马上到";
} else if (mins >= 3 && mins < 60) {
timeLabel = mins + "分钟后";
} else if (mins >= 60 && hours < 24) {
timeLabel = hours + "小时后";
} else if (hours >= 24 && days < 30) {
timeLabel = days + "天后";
} else if (days >= 30 && years < 1) {
timeLabel = months + "个月后";
} else if (years >= 1) {
timeLabel = years + "年后";
}
}
}
return timeLabel;
}
public static int compareDate(String date1, String date2, String formatStr) {
int i = -2;
if (!TextUtils.isEmpty(date1) && !TextUtils.isEmpty(date2)) {
if (!TextUtils.isEmpty(formatStr)) {
SimpleDateFormat format = new SimpleDateFormat(formatStr, Locale.getDefault());
try {
Date d1 = format.parse(date1);
Date d2 = format.parse(date2);
if (d1.before(d2)) {
i = -1;
} else if (d1.after(d2)) {
i = 1;
} else if (d1.equals(d2)) {
i = 0;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
return i;
}
public static int compareDate(String date1, String date2, int addMinutes) {
int i = -2;
String formatStr = "yyyy-MM-dd HH:mm:ss";
if (!TextUtils.isEmpty(date1) && !TextUtils.isEmpty(date2)) {
SimpleDateFormat format = new SimpleDateFormat(formatStr, Locale.getDefault());
try {
Date d1 = format.parse(date1);
d1.setMinutes(d1.getMinutes() + addMinutes);
Date d2 = format.parse(date2);
if (d1.before(d2)) {
i = -1;
} else if (d1.after(d2)) {
i = 1;
} else if (d1.equals(d2)) {
i = 0;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return i;
}
public static int getBetweenDayOfYear(String strDate1, String strDate2,
String formatStr) {
int betweenDays = 0;
if (!TextUtils.isEmpty(strDate1) && !TextUtils.isEmpty(strDate2)) {
if (!TextUtils.isEmpty(formatStr)) {
SimpleDateFormat format = new SimpleDateFormat(formatStr, Locale.getDefault());
try {
Date date1 = format.parse(strDate1);
Date date2 = format.parse(strDate2);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
betweenDays = calendar1.get(Calendar.DAY_OF_YEAR)
- calendar2.get(Calendar.DAY_OF_YEAR);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
return betweenDays;
}
/**
* 获取当月当天 所在周的7个日期
*
* @return 周日 1 周一 2 3...6
*/
public static List<Date> dateToWeek() {
SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
Date mdate = new Date();
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
// fdate.setTime(fTime + (a * 24*3600000)); //一周从周日开始算,则使用此方式
// fdate.setTime(fTime + ((a-1) * 24*3600000)); //一周从周一开始算,则使用此方式
fdate.setTime(fTime + ((a - 1) * 24 * 3600000));
list.add(a - 1, fdate);
}
return list;
}
/**
* 获取当月当天前7个日期的字符串
*
* @param format 时间格式
* @param count 当天多少天前的整形值
* @return 当天前count个日期的字符串
*/
public static List<String> getRecentSevenDate(String format, int count) {
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
Calendar c = Calendar.getInstance();
c.setTime(new Date());
List<String> result = new ArrayList<>(count);
for (int a = count; a <= count; a--) {
c.add(Calendar.DATE, 0 - a);
Date date = c.getTime();
String s = formatter.format(date);
result.add(s);
}
return result;
}
public static String getYesterdayDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();
String date = format.format(d);
return date;
}
/**
* 获取昨日短字符串(无时分秒)
*
* @return 昨天的字符串(只包含年-月-日)
*/
public static String getYesterdayDateShort() {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();
String date = format.format(d);
return date;
}
public static String getRecentSevenDayDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, -7);
Date d = c.getTime();
String date = format.format(d);
return date;
}
public static String getRecentSevenDayDateShort() {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
Calendar c = Calendar.getInstance();
//过去七天
c.setTime(new Date());
c.add(Calendar.DATE, -7);
Date d = c.getTime();
String date = format.format(d);
return date;
}
public static String getRecentMonthDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String date = format.format(m);
return date;
}
public static String getRecentMonthDateShort() {
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String date = format.format(m);
return date;
}
public static String dateStringToFormat(String dataString, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
Date date = null;
try {
date = formatter.parse(dataString);
} catch (ParseException e) {
e.printStackTrace();
}
return formatter.format(date);
}
}
package com.mayi.fastdevelop.util;
import android.content.Context;
/**
* @Description dp、sp转化为px的工具类
*/
public class DisplayUtil {
/**
* 将px值转换为dip或dp值,保证尺寸大小不变
*
* @param pxValue
* @return
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* 将dip或dp值转换为px值,保证尺寸大小不变
*
* @param dipValue
* @return
*/
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 将px值转换为sp值,保证文字大小不变
*
* @param pxValue
* @return
*/
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 将sp值转换为px值,保证文字大小不变
*
* @param spValue
* @return
*/
public static int sp2px(Context context, float spValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
}
package com.mayi.fastdevelop.util;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.text.TextUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 文件管理工具
*/
public final class FileUtil {
/**
* 删除一个文件
*/
public static void deleteFile(String filePath) {
if (TextUtils.isEmpty(filePath))
return;
File file = new File(filePath);
deleteFile(file);
}
/**
* 删除文件
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void deleteFile(File file) {
if (file == null) {
return;
}
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
if (files != null) {
for (File subFile : files) {
deleteFile(subFile);
}
}
}
file.delete();
}
}
/**
* 删除文件并刷新媒体库
*/
public static void deleteFile(File file, Context context) {
try {
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // delete()方法 你应该知道 是删除的意思;
Uri localUri = Uri.fromFile(file);
String where = MediaStore.MediaColumns.DATA + "='" + file + "'";
context.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, where, null);
Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri);
context.sendBroadcast(localIntent);
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
if (files != null) {
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
deleteFile(files[i], context); // 把每个文件 用这个方法进行迭代
}
}
}
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取SdCard路径
*/
public static String getExternalStoragePath() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) && Environment.getExternalStorageDirectory().canWrite()) {
return Environment.getExternalStorageDirectory().getPath();
}
return null;
}
/**
* 复制文件
*
* @param oldPath 源文件路径
* @param newPath 目标文件路径
*/
public static boolean copyFile(String oldPath, String newPath) {
boolean isSuccess;
InputStream is = null; // 输入原文件
OutputStream os = null; // 输出目标文件文件
try {
File oldFile = new File(oldPath);
if (oldFile.exists()) { // 文件存在时
is = new BufferedInputStream(new FileInputStream(oldPath));
os = new BufferedOutputStream(new FileOutputStream(newPath));
final byte[] buffer = new byte[4096];
int readLen;
while ((readLen = is.read(buffer)) != -1) {
os.write(buffer, 0, readLen);
}
isSuccess = true;
} else {
isSuccess = false;
}
} catch (Exception e) {
e.printStackTrace();
isSuccess = false;
} finally {
closeQuietly(is, os);
}
return isSuccess;
}
/**
* 关闭IO
*/
public static boolean closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
/**
* 关闭多个IO
*/
public static void closeQuietly(Closeable... closeables) {
for (Closeable closeable : closeables) {
closeQuietly(closeable);
}
}
/**
* 根据系统当前ms值生成文件名
*
* @param prefix 前缀缀名(例 b_)
* @param suffix 后缀名(例 .jpg)
*/
public static String getRandomFileName(String prefix, String suffix) {
return prefix + System.currentTimeMillis() + suffix;
}
/**
* 判断文件夹是否存在,不存在则创建
*/
public static void isExistsDirFile(String filePath) {
File dirFile = new File(filePath);
if (!dirFile.exists()) {
// 文件夹不存在直接创建
dirFile.mkdirs();
}
}
/**
* 判断文件是否存在
*/
public static boolean isExistsFile(String filePath) {
if (TextUtils.isEmpty(filePath))
return false;
File file = new File(filePath);
return file.exists();
}
public static boolean hasExtentsion(String filename) {
final String extName = getExtensionName(filename);
return !extName.isEmpty();
}
/**
* 获取文件扩展名
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return "";
}
/**
* 获取文件名
*/
public static String getFileNameFromPath(String filepath) {
if ((filepath != null) && (filepath.length() > 0)) {
int sep = filepath.lastIndexOf('/');
if ((sep > -1) && (sep < filepath.length() - 1)) {
return filepath.substring(sep + 1);
}
}
return filepath;
}
/**
* 获取sd卡剩余空间
**/
public static long getSDCardFreeSpaceSize() {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return 0;
}
File path = Environment.getExternalStorageDirectory();
StatFs sf = new StatFs(path.getPath());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return sf.getAvailableBytes();
} else {
long singleBlockSize = sf.getBlockSize();
long freeBlockCount = sf.getAvailableBlocks();
return freeBlockCount * singleBlockSize;
}
}
public static boolean makeDir(String dirPath) {
File file = new File(dirPath);
if (!file.exists()) {
return file.mkdirs();
} else {
return true;
}
}
public enum FileType {
WORD,
EXCEL,
JPG,
MP4,
PPT,
PDF,
OTHER,
TYPE_FOLDER,
GIF
}
public static FileType getFileType(String name) {
String exName = getExtensionName(name);
exName = exName.toLowerCase();
if (exName.equals("jpg") || exName.equals("png") || exName.equals("jpeg") || exName.equals("bmp")) {
return FileType.JPG;
} else if (exName.equals("mp4") || exName.equals("avi") || exName.equals("rmvb") || exName.equals("mov")) {
return FileType.MP4;
} else if (exName.equals("pptx") || exName.equals("ppt")) {
return FileType.PPT;
} else if (exName.equals("doc") || exName.equals("docx")) {
return FileType.WORD;
} else if (exName.equals("pdf")) {
return FileType.PDF;
} else if (exName.equals("xls") || exName.equals("xlsx")) {
return FileType.EXCEL;
} else if (exName.equals("gif")) {
return FileType.GIF;
}
return FileType.OTHER;
}
/**
* 根据byte数组,生成文件
*/
public static File getFile(byte[] bfile, String filePath) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return file;
}
/**
* 使用系统当前日期加以调整作为照片的名称
*
* @param Prefix 前缀缀名(例 b_)
* @param Suffix 后缀名(例 .jpg)
*/
public static String getPhotoFileName(String Prefix, String Suffix) {
return Prefix + System.currentTimeMillis() + Suffix;
}
public static boolean createFile(File file) {
if (file != null && !file.exists()) {
String absolutePath = file.getAbsolutePath();
if (absolutePath.endsWith(File.separator)) {
//创建文件夹
if (!file.exists()) {//文件夹不存在
return file.mkdirs();
}
} else {
//创建文件
if (!file.exists()) {//文件不存在
if (!file.getParentFile().exists()) {
return file.getParentFile().mkdirs();
}
}
}
}
return false;
}
/**
* 判断是否手机插入Sd卡
*/
public static boolean hasSdcard() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
public static File getDCIMFile(String filePath, String imageName) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 文件可用
File dirs = new File(Environment.getExternalStorageDirectory(), "DCIM" + filePath);
if (!dirs.exists()) dirs.mkdirs();
File file = new File(Environment.getExternalStorageDirectory(), "DCIM" + filePath + imageName);
if (!file.exists()) {
try { //在指定的文件夹中创建文件
file.createNewFile();
} catch (Exception e) {
}
}
return file;
} else {
return null;
}
}
}
package com.mayi.fastdevelop.util;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import com.mayi.fastdevelop.R;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
public class ImageUtil {
/**
* 保存网络图片
*
* @param context
* @param url
*/
public static void saveBitmap(Context context, String url) {
final WeakReference<Context> weakReference = new WeakReference<>(context);
if (TextUtils.isEmpty(url)) {
ToastUtil.show(context, context.getString(R.string.save_img_failed_2));
return;
}
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Context c = weakReference.get();
if (c != null) {
saveBitmap(bitmap, Environment.getExternalStorageDirectory().toString() + "/" + c.getPackageName() + "/picture/" + System.currentTimeMillis() + ".jpg");
//刷新相册
c.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString() + "/" + c.getPackageName()))));
ToastUtil.show(c, c.getString(R.string.save_img_success));
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
Context c = weakReference.get();
if (c != null) {
ToastUtil.show(c, c.getString(R.string.save_img_failed));
}
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(context).load(url).into(target);
}
/**
* 保存图片
*
* @param mBitmap 目标图片
* @param fileName 目标文件
*/
public static void saveBitmap(Bitmap mBitmap, String fileName) {
try {
File file = new File(fileName);
FileOutputStream out = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取某个view的截图
*
* @param view 目标view
*/
public static Bitmap getViewImage(View view) {
Bitmap image = null;
try {
view.setDrawingCacheEnabled(true); //获取view缓存
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
// 拷贝图片,否则在setDrawingCacheEnabled(false)以后该图片会被释放掉
Bitmap cacheBitmap = view.getDrawingCache();
//方案1 (图片显示模糊)
// image = Bitmap.createBitmap(cacheBitmap);
//方案2 (图片显示模糊)
// float scale = 320f / cacheBitmap.getWidth();
// int height = (int) (cacheBitmap.getHeight() * scale);
// image = Bitmap.createScaledBitmap(cacheBitmap, 320, height, true);
//方案3
// image = scaleImageCavans(cacheBitmap, DensityUtil.dip2px(view.getContext(), 320), DensityUtil.dip2px(view.getContext(), 240));
// image = scaleImageCavans(cacheBitmap, 320, 240);
//方案4
// Matrix类进行图片处理(缩放)
Matrix matrix = new Matrix();
// 缩小
matrix.setScale(320f / cacheBitmap.getWidth(), 320f / cacheBitmap.getWidth());
// 生成新的图片
image = Bitmap.createBitmap(cacheBitmap, 0, 0, cacheBitmap.getWidth(), cacheBitmap.getHeight(), matrix, true);
} catch (Exception e) {
e.printStackTrace();
} finally {
view.setDrawingCacheEnabled(false);//释放缓存
}
return image;
}
private static PaintFlagsDrawFilter pfd = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
public static Bitmap scaleImageCavans(Bitmap bm, int newWidth, int newHeight) {
//应用图标缩放
if (bm == null) {
return null;
}
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Bitmap newbm = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(newbm);
Paint mPaint = new Paint();
mPaint.setXfermode(null);
mPaint.setAntiAlias(true);
mCanvas.save();
mCanvas.scale(scaleWidth, scaleHeight);
//保证图标不失真
mCanvas.setDrawFilter(pfd);
mCanvas.drawBitmap(bm, 0, 0, null);
mCanvas.restore();
if (!bm.isRecycled()) {
bm.recycle();
}
return newbm;
}
}
package com.mayi.fastdevelop.util;
import android.text.TextUtils;
import com.alibaba.fastjson.JSON;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
/**
* 日志记录工具类
*/
public class LogUtils {
public static String TAG;
/**
* 错误信息上传bugly,已自定义错误的方式
*
* @param e
*/
public static void postCatchedException(Exception e) {
StringBuffer msg = new StringBuffer();
if (!TextUtils.isEmpty(TAG)){
msg.append(TAG);
msg.append("--");
}
msg.append(e.toString());
Throwable throwable = new Throwable(msg.toString());
throwable.setStackTrace(e.getStackTrace());
CrashReport.postCatchedException(throwable);
}
/**
* Logger为第三方jar,不要直接使用,防止以后需要替换
*
* @param msg
*/
public static void i(String msg) {
Logger.i(msg);
}
public static void d(String msg) {
Logger.d(msg);
}
public static void v(String msg) {
Logger.v(msg);
}
public static void w(String msg) {
Logger.w(msg);
}
public static void e(String msg) {
Logger.e(msg);
}
/**
* 网络请求记录日志-网络请求成功,接口返回成功就算网络请求成功
*
* @param tag 发起请求的位置,要求定位到方法
* @param url
* @param parameter
* @param result
*/
public static void netWorkSuccess(String tag, String url, Object parameter, Object result) {
Logger.i(tag + " netWork Success url=" + url + " parameter=" +
JSON.toJSONString(parameter) + " result=" + JSON.toJSONString(result));
}
/**
* 网络请求记录日志-网络请求失败,并上传bugly
*
* @param tag 发起请求的位置,要求定位到方法
* @param url
* @param parameter
* @param e
*/
public static void netWorkFail(String tag, String url, Object parameter, Exception e) {
postCatchedException(e);
Logger.i(tag + " netWork Fail url=" + url + " parameter=" +
JSON.toJSONString(parameter) + " Exception=" + e.toString());
}
}
package com.mayi.fastdevelop.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.EncodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.util.Hashtable;
/**
* 二维码工具
*/
public class QrUtil {
private static int width = 400; // 二维码图片显示宽度
private static final int IMAGE_HALFWIDTH = 45; // 二维码中间图片显示宽度
private static int FOREGROUND_COLOR = 0xff000000; // 前景色
private static int BACKGROUND_COLOR = 0xffffffff; // 背景色
/**
* 生成二维码
*
* @param str 内容
* @return Bitmap
*/
public static Bitmap createBitmap(String str) {
Bitmap bitmap = null;
try {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1); // 二维码边界空白大小 ,如:1、2、3、4 默认好像是4
// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
MultiFormatWriter mutiWriter = new MultiFormatWriter();
BitMatrix matrix = mutiWriter.encode(str, BarcodeFormat.QR_CODE, width, width, hints);
int width = matrix.getWidth();
int height = matrix.getHeight();
// 二维矩阵转为一维像素数组,也就是一直横着排了
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = FOREGROUND_COLOR;
} else { // 无信息设置像素点为白色
pixels[y * width + x] = BACKGROUND_COLOR;
}
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);// 通过像素数组生成bitmap
} catch (Throwable ex) {
ex.printStackTrace();
}
return bitmap;
}
/**
* 生成二维码 中间插入小图片
*
* @param str 内容
* @return Bitmap
*/
public static Bitmap createBitmap(Context context, String str, int centerBmpResId) {
Bitmap iconBigger = null;
Bitmap iconSmaller = null;
Bitmap bitmap = null;
try {
iconBigger = BitmapFactory.decodeResource(context.getResources(), centerBmpResId);
iconSmaller = zoomBitmap(iconBigger, IMAGE_HALFWIDTH);// 缩放一个50*50的图片
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1); // 二维码边界空白大小 ,如:1、2、3、4 默认好像是4
// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
MultiFormatWriter mutiWriter = new MultiFormatWriter();
BitMatrix matrix = mutiWriter.encode(str, BarcodeFormat.QR_CODE, width, width, hints);
int width = matrix.getWidth();
int height = matrix.getHeight();
// 二维矩阵转为一维像素数组,也就是一直横着排了
int halfW = width / 2;
int halfH = height / 2;
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x + 10 > halfW - IMAGE_HALFWIDTH && x - 10 < halfW + IMAGE_HALFWIDTH && y + 10 > halfH - IMAGE_HALFWIDTH && y - 10 < halfH
+ IMAGE_HALFWIDTH) {
if (x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH && y < halfH +
IMAGE_HALFWIDTH) {
pixels[y * width + x] = iconSmaller.getPixel(x - halfW + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH);
} else {
pixels[y * width + x] = BACKGROUND_COLOR;
}
} else {
if (matrix.get(x, y)) {
pixels[y * width + x] = FOREGROUND_COLOR;
} else { // 无信息设置像素点为白色
pixels[y * width + x] = BACKGROUND_COLOR;
}
}
}
}
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);// 通过像素数组生成bitmap
} catch (Throwable ex) {
ex.printStackTrace();
} finally {
recycle(iconBigger);
recycle(iconSmaller);
}
return bitmap;
}
public static Bitmap recycle(Bitmap bmp) {
if (bmp != null && !bmp.isRecycled()) {
bmp.recycle();
bmp = null;
}
return bmp;
}
/**
* 缩放图片
*
* @param icon 源图片
* @param h 高度
* @return
*/
public static Bitmap zoomBitmap(Bitmap icon, int h) {
// 缩放图片
Matrix m = new Matrix();
float sx = (float) 2 * h / icon.getWidth();
float sy = (float) 2 * h / icon.getHeight();
m.setScale(sx, sy);
// 重新构造一个2h*2h的图片
return Bitmap.createBitmap(icon, 0, 0, icon.getWidth(), icon.getHeight(), m, false);
}
//识别二维码的函数
public static String recogQRcode(Bitmap QRbmp) {
int width = QRbmp.getWidth();
int height = QRbmp.getHeight();
int[] data = new int[width * height];
QRbmp.getPixels(data, 0, width, 0, 0, width, height); //得到像素
int bitmapPixels[];
bitmapPixels = new int[QRbmp.getWidth() * QRbmp.getHeight()];
QRbmp.getPixels(data, 0, QRbmp.getWidth(), 0, 0, QRbmp.getWidth(), QRbmp.getHeight());
// 将int数组转换为byte数组,也就是取像素值中蓝色值部分作为辨析内容
for (int i = 0; i < data.length; i++) {
bitmapPixels[i] = (byte) data[i];
}
RGBLuminanceSource source = new RGBLuminanceSource(QRbmp.getWidth(), QRbmp.getHeight(), bitmapPixels); //RGBLuminanceSource对象
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result re = null;
try {
//得到结果
re = reader.decode(bitmap1);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
//Toast出内容
return re.getText();
}
}
package com.mayi.fastdevelop.util;
import android.text.TextUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegUtil {
/**
* 验证密码 6-20位 必须数字字母组合
*/
public static boolean isPwd(String pwd) {
if (TextUtils.isEmpty(pwd))
return false;
Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$");
Matcher m = p.matcher(pwd);
return m.matches();
}
/**
* 验证邮箱
*/
public static boolean isEmail(String strEmail) {
if (TextUtils.isEmpty(strEmail))
return false;
Pattern p = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
Matcher m = p.matcher(strEmail);
return m.matches();
}
/**
* 验证手机格式
*
* @param mobiles
* @return
*/
public static boolean isPhone(String mobiles) {
if (TextUtils.isEmpty(mobiles)) {
return false;
}
return mobiles.matches("[1]\\d{10}");
}
/**
* 判断是否中文
*
* @param str
* @return
*/
public static boolean isChinese(String str) {
boolean temp = false;
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
temp = true;
}
return temp;
}
}
package com.mayi.fastdevelop.util;
import android.content.Context;
import android.content.SharedPreferences;
import com.mayi.fastdevelop.base.BaseApplication;
/**
* 本地存储操作类
*/
public class SpUtil {
private static SharedPreferences sp;
public static synchronized SharedPreferences getSp() {
if (sp == null) {
Context context = BaseApplication.getInstance().getChildApplication();
sp = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
}
return sp;
}
/**
* 清空所有数据
*/
public static void clear() {
getSp().edit().clear().apply();
}
/**
* 写入.
*
* @param key 键.
* @param value 值(boolean).
*/
public static void set(String key, boolean value) {
getSp().edit().putBoolean(key, value).apply();
}
/**
* 写入.
*
* @param key 键.
* @param value 值(float).
*/
public static void set(String key, float value) {
getSp().edit().putFloat(key, value).apply();
}
/**
* 写入.
*
* @param key 键.
* @param value 值(int).
*/
public static void set(String key, int value) {
getSp().edit().putInt(key, value).apply();
}
/**
* 写入.
*
* @param key 键.
* @param value 值(long).
*/
public static void set(String key, long value) {
getSp().edit().putLong(key, value).apply();
}
/**
* 写入.
*
* @param key 键.
* @param value 值(String).
*/
public static void set(String key, String value) {
getSp().edit().putString(key, value).apply();
}
/**
* 移除指定键的值.
*
* @param key 键.
*/
public static void remove(String key) {
getSp().edit().remove(key).apply();
}
/**
* 读取.
*
* @param key 键.
* @param defValue 默认值(boolean).
* @return 获取相应键的值, 若不存在此键则返回默认值.
*/
public static boolean get(String key, boolean defValue) {
return getSp().getBoolean(key, defValue);
}
/**
* 读取.
*
* @param key 键.
* @param defValue 默认值(float).
* @return 获取相应键的值, 若不存在此键则返回默认值.
*/
public static float get(String key, float defValue) {
return getSp().getFloat(key, defValue);
}
/**
* 读取.
*
* @param key 键.
* @param defValue 默认值(int).
* @return 获取相应键的值, 若不存在此键则返回默认值.
*/
public static int get(String key, int defValue) {
return getSp().getInt(key, defValue);
}
/**
* 读取.
*
* @param key 键.
* @param defValue 默认值(long).
* @return 获取相应键的值, 若不存在此键则返回默认值.
*/
public static long get(String key, long defValue) {
return getSp().getLong(key, defValue);
}
/**
* 读取.
*
* @param key 键.
* @param defValue 默认值(String).
* @return 获取相应键的值, 若不存在此键则返回默认值.
*/
public static String get(String key, String defValue) {
return getSp().getString(key, defValue);
}
}
\ No newline at end of file
package com.mayi.fastdevelop.util;
import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;
/**
* 公共的Toast
*/
public class ToastUtil {
private static Toast sToast = null;
public static Toast show(Context context, String msg) {
return show(context, msg, Toast.LENGTH_SHORT);
}
public static Toast show(Context context, String msg, int duration) {
if (TextUtils.isEmpty(msg) || context == null) {
return null;
}
if (duration < Toast.LENGTH_SHORT) {
duration = Toast.LENGTH_SHORT;
}
if (sToast == null) {
sToast = Toast.makeText(context, msg, duration);
} else {
sToast.setDuration(duration);
sToast.setText(msg);
}
sToast.show();
return sToast;
}
}
\ No newline at end of file
package com.mayi.fastdevelop.util;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
//记录log
public class WriteHandler extends Handler {
private final String folder;
private final int maxFileSize;
public WriteHandler(Looper looper, String folder, int maxFileSize) {
super(looper);
this.folder = folder;
this.maxFileSize = maxFileSize;
}
@SuppressWarnings("checkstyle:emptyblock")
@Override
public void handleMessage(Message msg) {
String content = (String) msg.obj;
FileWriter fileWriter = null;
File logFile = getLogFile(folder, "logs");
try {
fileWriter = new FileWriter(logFile, true);
writeLog(fileWriter, content);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
if (fileWriter != null) {
try {
fileWriter.flush();
fileWriter.close();
} catch (IOException e1) { /* fail silently */ }
}
}
}
private void writeLog(FileWriter fileWriter, String content) throws IOException {
fileWriter.append(content);
}
private File getLogFile(String folderName, String fileName) {
File folder = new File(folderName);
if (!folder.exists()) {
folder.mkdirs();
}
int newFileCount = 0;
File newFile;
File existingFile = null;
newFile = new File(folder, String.format("%s_%s.txt", fileName, newFileCount));
while (newFile.exists()) {
existingFile = newFile;
newFileCount++;
newFile = new File(folder, String.format("%s_%s.txt", fileName, newFileCount));
}
if (existingFile != null) {
if (existingFile.length() >= maxFileSize) {
return newFile;
}
return existingFile;
}
return newFile;
}
}
\ No newline at end of file
package com.mayi.fastdevelop.view;
import android.view.View;
public abstract class OnMultiClickListener implements View.OnClickListener {
// 两次点击按钮之间的点击间隔不能少于500毫秒
private static final int MIN_CLICK_DELAY_TIME = 500;
private static long lastClickTime;
public abstract void onMultiClick(View v);
@Override
public void onClick(View v) {
long curClickTime = System.currentTimeMillis();
if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
lastClickTime = curClickTime;
onMultiClick(v);
}
}
}
<resources>
<string name="app_name">fastDevelop</string>
<string name="save_img_failed_2">图片地址异常,保存图片失败!</string>
<string name="save_img_success">保存图片成功!</string>
<string name="save_img_failed">保存图片失败!</string>
</resources>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment