diff --git a/app/src/main/java/com/shunzhi/parent/ui/fragment/consult/ConsultOneLevelFragment.java b/app/src/main/java/com/shunzhi/parent/ui/fragment/consult/ConsultOneLevelFragment.java index 5c9ba9f..47137e8 100644 --- a/app/src/main/java/com/shunzhi/parent/ui/fragment/consult/ConsultOneLevelFragment.java +++ b/app/src/main/java/com/shunzhi/parent/ui/fragment/consult/ConsultOneLevelFragment.java @@ -29,9 +29,8 @@ import com.shunzhi.parent.presenter.consult.consultone.ConsultOnePresenter; import java.util.ArrayList; import java.util.List; -public class ConsultOneLevelFragment extends BaseMVPCompatFragment - implements View.OnClickListener, ConsultOneContract.IConsultOneView { - +public class ConsultOneLevelFragment extends BaseMVPCompatFragment implements View.OnClickListener, ConsultOneContract.IConsultOneView { RecyclerView recyclerViewGrally, recyclerViewConsultOne; @@ -52,15 +51,11 @@ public class ConsultOneLevelFragment extends BaseMVPCompatFragment diff --git a/app/src/main/res/layout/layout_week.xml b/app/src/main/res/layout/layout_week.xml new file mode 100644 index 0000000..7809490 --- /dev/null +++ b/app/src/main/res/layout/layout_week.xml @@ -0,0 +1,15 @@ + + + + + \ No newline at end of file diff --git a/mvpsdk/src/main/java/com/share/mvpsdk/utils/CacheUtils.java b/mvpsdk/src/main/java/com/share/mvpsdk/utils/CacheUtils.java new file mode 100644 index 0000000..de28722 --- /dev/null +++ b/mvpsdk/src/main/java/com/share/mvpsdk/utils/CacheUtils.java @@ -0,0 +1,163 @@ +package com.share.mvpsdk.utils; + +import android.content.Context; +import android.os.Environment; + +import java.io.File; +import java.math.BigDecimal; + +/** + * Created by ToaHanDong on 2018/3/15. + */ + +public class CacheUtils { + + /** * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache) * * @param context */ + public static void cleanInternalCache(Context context) { + deleteFilesByDirectory(context.getCacheDir()); + } + + /** * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases) * * @param context */ + public static void cleanDatabases(Context context) { + deleteFilesByDirectory(new File("/data/data/" + + context.getPackageName() + "/databases")); + } + + /** + * * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param + * context + */ + public static void cleanSharedPreference(Context context) { + deleteFilesByDirectory(new File("/data/data/"+ context.getPackageName() + "/shared_prefs")); + } + + /** * 按名字清除本应用数据库 * * @param context * @param dbName */ + public static void cleanDatabaseByName(Context context, String dbName) { + context.deleteDatabase(dbName); + } + + /** * 清除/data/data/com.xxx.xxx/files下的内容 * * @param context */ + public static void cleanFiles(Context context) { + deleteFilesByDirectory(context.getFilesDir()); + } + + /** + * * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param + * context + */ + public static void cleanExternalCache(Context context) { + if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { + deleteFilesByDirectory(context.getExternalCacheDir()); + } + } + + /** * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除 * * @param filePath */ + public static void cleanCustomCache(String filePath) { + deleteFilesByDirectory1(new File(filePath)); + } + + /** * 清除本应用所有的数据 * * @param context * @param filepath */ + public static void cleanApplicationData(Context context, String filepath) { +// cleanInternalCache(context); +// cleanExternalCache(context); +// cleanDatabases(context); + cleanSharedPreference(context); +// cleanFiles(context); +// cleanCustomCache(filepath); + } + + /** * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理 * * @param directory */ + public static void deleteFilesByDirectory(File directory) { + if (directory != null && directory.exists() && directory.isDirectory()) { + for (File item : directory.listFiles()) { + item.delete(); + } + } + } + private static void deleteFilesByDirectory1(File dir){ + if (dir!=null && dir.isDirectory()) { + String[] children = dir.list(); + //递归删除目录中的子目录下 + for (int i = 0; i < children.length; i++) { + StorageUtils.DeleteDirAndFile(new File(dir, children[i])); + } + } + } + + /** + * 清理缓存 + * @param context + * @param filepath + */ + public static void cleanEboardCache(Context context, String filepath) { + cleanInternalCache(context); + cleanExternalCache(context); + cleanFiles(context); + cleanCustomCache(filepath); + } + + public static String getCacheSize(Context context) throws Exception { + File file=new File("/data/data/"+ context.getPackageName()); + return getFormatSize(getFolderSize(file)); + } + + // 获取文件 + //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录,一般放一些长时间保存的数据 + //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录,一般存放临时缓存数据 + public static long getFolderSize(File file) throws Exception { + long size = 0; + try { + File[] fileList = file.listFiles(); + for (int i = 0; i < fileList.length; i++) { + // 如果下面还有文件 + if (fileList[i].isDirectory()) { + size = size + getFolderSize(fileList[i]); + } else { + size = size + fileList[i].length(); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return size; + } + + + /** + * 格式化单位 + * + * @param size + * @return + */ + public static String getFormatSize(double size) { + double kiloByte = size / 1024; + if (kiloByte < 1) { + return size + "Byte"; + } + + double megaByte = kiloByte / 1024; + if (megaByte < 1) { + BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); + return result1.setScale(2, BigDecimal.ROUND_HALF_UP) + .toPlainString() + "KB"; + } + + double gigaByte = megaByte / 1024; + if (gigaByte < 1) { + BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); + return result2.setScale(2, BigDecimal.ROUND_HALF_UP) + .toPlainString() + "MB"; + } + + double teraBytes = gigaByte / 1024; + if (teraBytes < 1) { + BigDecimal result3 = new BigDecimal(Double.toString(gigaByte)); + return result3.setScale(2, BigDecimal.ROUND_HALF_UP) + .toPlainString() + "GB"; + } + BigDecimal result4 = new BigDecimal(teraBytes); + return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + + "TB"; + } + +} diff --git a/mvpsdk/src/main/java/com/share/mvpsdk/utils/StorageUtils.java b/mvpsdk/src/main/java/com/share/mvpsdk/utils/StorageUtils.java new file mode 100644 index 0000000..2f41973 --- /dev/null +++ b/mvpsdk/src/main/java/com/share/mvpsdk/utils/StorageUtils.java @@ -0,0 +1,857 @@ +package com.share.mvpsdk.utils; + +import android.app.Activity; +import android.content.Context; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.graphics.Canvas; +import android.graphics.Matrix; +import android.graphics.Paint; +import android.net.Uri; +import android.os.Environment; +import android.provider.MediaStore; +import android.util.Log; +import android.view.View; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * Created by ToaHanDong on 2017/7/24. + */ + +public class StorageUtils { + private static final String TAG = "StorageUtils"; + + public static class StorageInfo { + + public final String path; + public final boolean internal; + public final boolean readonly; + public final int display_number; + + StorageInfo(String path, boolean internal, boolean readonly, int display_number) { + this.path = path; + this.internal = internal; + this.readonly = readonly; + this.display_number = display_number; + } + + public String getDisplayName() { + StringBuilder res = new StringBuilder(); + if (internal) { + res.append("Internal SD card"); + } else if (display_number > 1) { + res.append("SD card " + display_number); + } else { + res.append("SD card"); + } + if (readonly) { + res.append(" (Read only)"); + } + return res.toString(); + } + } + + public static List getStorageList() throws Exception { + + List list = new ArrayList(); + String def_path = Environment.getExternalStorageDirectory().getPath(); + boolean def_path_internal = !Environment.isExternalStorageRemovable(); + String def_path_state = Environment.getExternalStorageState(); + boolean def_path_available = def_path_state.equals(Environment.MEDIA_MOUNTED) + || def_path_state.equals(Environment.MEDIA_MOUNTED_READ_ONLY); + boolean def_path_readonly = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY); + BufferedReader buf_reader = null; + try { + HashSet paths = new HashSet(); + buf_reader = new BufferedReader(new FileReader("/proc/mounts")); + String line; + int cur_display_number = 1; + Log.d(TAG, "/proc/mounts"); + while ((line = buf_reader.readLine()) != null) { + Log.d(TAG, line); + if (line.contains("vfat") || line.contains("/mnt")) { + StringTokenizer tokens = new StringTokenizer(line, " "); + String unused = tokens.nextToken(); //device + String mount_point = tokens.nextToken(); //mount point + if (paths.contains(mount_point)) { + continue; + } + unused = tokens.nextToken(); //file system + List flags = Arrays.asList(tokens.nextToken().split(",")); //flags + boolean readonly = flags.contains("ro"); + + if (mount_point.equals(def_path)) { + paths.add(def_path); + list.add(0, new StorageInfo(def_path, def_path_internal, readonly, -1)); + } else if (line.contains("/dev/block/vold")) { + if (!line.contains("/mnt/secure") + && !line.contains("/mnt/asec") + && !line.contains("/mnt/obb") + && !line.contains("/dev/mapper") + && !line.contains("tmpfs")) { + paths.add(mount_point); + list.add(new StorageInfo(mount_point, false, readonly, cur_display_number++)); + } + } + } + } + + if (!paths.contains(def_path) && def_path_available) { + list.add(0, new StorageInfo(def_path, def_path_internal, def_path_readonly, -1)); + } + + } catch (FileNotFoundException ex) { + ex.printStackTrace(); + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (buf_reader != null) { + try { + buf_reader.close(); + } catch (IOException ex) { + } + } + } + return list; + } + + public static boolean DeleteDirAndFile(File file) { + if (file != null && file.isDirectory()) { + String[] children = file.list(); + //递归删除目录中的子目录下 + for (int i = 0; i < children.length; i++) { + boolean success = DeleteDirAndFile(new File(file, children[i])); + if (!success) { + return false; + } + } + } + // 目录此时为空,可以删除 + return file.delete(); + } + + + //通过url获取Bitmap + public static Bitmap getBitmap(String urlPath) throws Exception { + URL url = new URL(urlPath); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setConnectTimeout(5000); + conn.setRequestMethod("GET"); + Bitmap bm = null; + if (conn.getResponseCode() == 200) { + + InputStream inputStream = conn.getInputStream(); + bm = BitmapFactory.decodeStream(inputStream); +// +// if(bm==null){ +// Log.e(TAG, "getBitmap2: 为空"); +// }else{ +// Log.e(TAG, "getBitmap2: 不为空"); +// } + return bm; + } + return null; + + } + + /** + * 通过URL获得网上图片。并设置最大内存如:http://www.xxxxxx.com/xx.jpg + * + * @param url 网络图片地址 + * @param displaypixels 最大图片内存 + * @return + * @throws MalformedURLException + * @throws IOException + */ + public static Bitmap getBitmap(String url, int displaypixels) throws MalformedURLException, IOException { + Bitmap bmp = null; + BitmapFactory.Options opts = new BitmapFactory.Options(); + InputStream stream = new URL(url).openStream(); + byte[] bytes = getBytes(stream); +//这3句是处理图片溢出的begin( 如果不需要处理溢出直接 opts.inSampleSize=1;) + opts.inJustDecodeBounds = true; + BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); + opts.inSampleSize = computeSampleSize(opts, -1, displaypixels); +//end + opts.inJustDecodeBounds = false; + bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); + return bmp; + } + + + /** + * 数据流转成btyle[]数组 + */ + private static byte[] getBytes(InputStream is) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] b = new byte[2048]; + int len = 0; + try { + while ((len = is.read(b, 0, 2048)) != -1) { + baos.write(b, 0, len); + baos.flush(); + } + } catch (IOException e) { + e.printStackTrace(); + } + byte[] bytes = baos.toByteArray(); + return bytes; + } + + /**** + * 处理图片bitmap size exceeds VM budget (Out Of Memory 内存溢出) + */ + private static int computeSampleSize(BitmapFactory.Options options, + int minSideLength, int maxNumOfPixels) { + int initialSize = computeInitialSampleSize(options, minSideLength, + maxNumOfPixels); + int roundedSize; + if (initialSize <= 8) { + roundedSize = 1; + while (roundedSize < initialSize) { + roundedSize <<= 1; + } + } else { + roundedSize = (initialSize + 7) / 8 * 8; + } + return roundedSize; + } + + private static int computeInitialSampleSize(BitmapFactory.Options options, + int minSideLength, int maxNumOfPixels) { + double w = options.outWidth; + double h = options.outHeight; + int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math + .sqrt(w * h / maxNumOfPixels)); + int upperBound = (minSideLength == -1) ? 128 : (int) Math.min( + Math.floor(w / minSideLength), Math.floor(h / minSideLength)); + if (upperBound < lowerBound) { + return lowerBound; + } + if ((maxNumOfPixels == -1) && (minSideLength == -1)) { + return 1; + } else if (minSideLength == -1) { + return lowerBound; + } else { + return upperBound; + } + } + + + public static String getFileName(String pathName) { + int start = pathName.lastIndexOf("/"); + if (start != -1) { + return pathName.substring(start + 1, pathName.length()); + } + return pathName; + + } + + public static String getFileExtName(String pathName) { + int start = pathName.lastIndexOf("."); + if (start != -1) { + return pathName.substring(start + 1, pathName.length()); + } + return pathName; + } + + public static void write1(Bitmap bmp, File file) { + FileOutputStream fos = null; + try { + if (!file.exists()) { + file.createNewFile(); + } + fos = new FileOutputStream(file); + bmp.compress(Bitmap.CompressFormat.PNG, 75, fos); + + fos.flush(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (null != fos) { + try { + + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * 把png或jpg(jpeg)格式图片按指定名称写入指定目录下 + * + * @param bmp + * @param file + */ + public static boolean write(Bitmap bmp, File file) { + + +// try { +// ByteArrayOutputStream baos = new ByteArrayOutputStream(); +// bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 +// bmp.recycle(); +// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); +// baos.reset(); // 把压缩后的数据baos存放到ByteArrayInputStream中 +// BitmapFactory.Options options = new BitmapFactory.Options(); +// options.inJustDecodeBounds = true;//只 +// BitmapFactory.decodeStream(isBm, null,options); // 把ByteArrayInputStream数据生成图片 +// int w = options.outWidth; +// int h = options.outHeight; +// options.inSampleSize = calculateInSampleSize(w, h, 720, 405); +// options.inJustDecodeBounds = false; +// isBm.reset(); +// bmp = BitmapFactory.decodeStream(isBm,null,options); // 把ByteArrayInputStream数据生成图片 +// double bitcount = bmp.getByteCount()/1000; +// //Log.e("StorageUtils", "这里压缩尺寸后的容量:" + bitcount + "---------------"); +// +// bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); +// int compressOptions = 100 ; +// //Log.e("StorageUtils", "这里压缩容量前的容量:" + baos.toByteArray().length / 1024 + "---------------"); +// while (baos.toByteArray().length / 1024 > 500 ) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩 +// baos.reset(); // 重置baos即清空baos +// bmp.compress(Bitmap.CompressFormat.JPEG, compressOptions, baos); // 这里压缩options%,把压缩后的数据存放到baos中 +// compressOptions -= 10 ; // 每次都减少10 +// } +// ByteArrayInputStream isCompress = new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中 +// bmp = BitmapFactory.decodeStream(isCompress, null , null ); // 把ByteArrayInputStream数据生成图片 +// bitcount = bmp.getByteCount()/1000; +// //Log.e("StorageUtils", "这里压缩容量后的容量:" + bitcount + "---------------"); +// } catch (Exception e) { +// e.printStackTrace(); +// return false; +// } +// //write +// FileOutputStream fos = null; +// try { +// if (!file.exists()) { +// file.createNewFile(); +// } +// fos = new FileOutputStream(file); +// bmp.compress(Bitmap.CompressFormat.PNG, 100, fos); +// +// fos.flush(); +// } catch (FileNotFoundException e) { +// e.printStackTrace(); +// return false; +// } catch (IOException e) { +// e.printStackTrace(); +// return false; +// } finally { +// if (null != fos) { +// try { +// fos.close(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } +// return true; + + + try { + FileOutputStream fos = new FileOutputStream(file); + bmp.compress(Bitmap.CompressFormat.JPEG, 90, fos); + return true; + } catch (FileNotFoundException e) { + e.printStackTrace(); + return false; + } + } + + + /** + * 质量压缩到固定的容量 + * + * @param image + * @param imagesize 压缩的大小限制 k + * @return + */ + public static Bitmap compressImage(Bitmap image, int imagesize) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 + int options = 100; + while (baos.toByteArray().length / 1024 > imagesize) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 + baos.reset(); // 重置baos即清空baos + options -= 10; // 每次都减少10 + image.compress(Bitmap.CompressFormat.JPEG, options, baos); // 这里压缩options%,把压缩后的数据存放到baos中 + } + ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中 + Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); // 把ByteArrayInputStream数据生成图片 + return bitmap; + } + + /** + * 质量压缩到固定的容量 到指定路径下 + * + * @param image + * @param maxSize 压缩的大小限制 k + * @return + */ + public static void compressAndGenImage(Bitmap image, File file, int maxSize) throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + // scale + int options = 100; + // Store the bitmap into output stream(no compress) +// image.compress(Bitmap.CompressFormat.JPEG, options, os); + image.compress(Bitmap.CompressFormat.PNG, options, os); + // Compress by loop + /* while (os.toByteArray().length / 1024 > maxSize) { + // Clean up os + os.reset(); + // interval 10 + options -= 10; + image.compress(Bitmap.CompressFormat.PNG, options, os); + }*/ + + // Generate compressed image file + FileOutputStream fos = new FileOutputStream(file); + fos.write(os.toByteArray()); + fos.flush(); + fos.close(); + } + + /** + * 压缩图片到固定的尺寸 + */ + public static Bitmap revitionImageSize(Bitmap bitmap, int oldwidth, int oldheight, int reqWidth, int reqHeight) throws IOException { + +// // 生成压缩的图片 +// int i = 0; +// BitmapFactory.Options options = new BitmapFactory.Options(); +// // 这个参数代表,不为bitmap分配内存空间,只记录一些该图片的信息(例如图片大小),说白了就是为了内存优化 +// options.inSampleSize = calculateInSampleSize(oldwidth,oldheight,reqWidth,reqHeight); +// options.inJustDecodeBounds = false; +// ByteArrayOutputStream baos = new ByteArrayOutputStream(); +// bitmap.compress(Bitmap.CompressFormat.JPEG, 80 , baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 +// +// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中 +// bitmap = BitmapFactory.decodeStream(isBm, null , options ); // 把ByteArrayInputStream数据生成图片 +// double bitcount =bitmap.getByteCount()/1000; +// Log.e("StorageUtils", "这里压缩尺寸后的容量:" + bitcount + "---------------"); +// return bitmap; + //上面这段代码在搞笑吧? + + if (oldwidth <= reqWidth && oldheight <= reqHeight) + return bitmap; + Bitmap ret = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false); + bitmap.recycle(); + return ret; + } + + /** + * 压缩bitmap到指定的尺寸 + * + * @param image + * @param pixelW + * @param pixelH + * @return + */ + public static Bitmap ratio(Bitmap image, float pixelW, float pixelH) { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + image.compress(Bitmap.CompressFormat.PNG, 100, os); + if (os.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 + os.reset();//重置baos即清空baos + image.compress(Bitmap.CompressFormat.PNG, 100, os);//这里压缩50%,把压缩后的数据存放到baos中 + } + ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); + BitmapFactory.Options newOpts = new BitmapFactory.Options(); + //开始读入图片,此时把options.inJustDecodeBounds 设回true了 + newOpts.inJustDecodeBounds = true; + newOpts.inPreferredConfig = Bitmap.Config.ARGB_8888; + Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts); + newOpts.inJustDecodeBounds = false; + int w = newOpts.outWidth; + int h = newOpts.outHeight; + float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了 + float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了 + //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 + int be = 1;//be=1表示不缩放 + if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放 + be = (int) (newOpts.outWidth / ww); + } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放 + be = (int) (newOpts.outHeight / hh); + } + if (be <= 0) be = 1; + newOpts.inSampleSize = be;//设置缩放比例 + //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 + is = new ByteArrayInputStream(os.toByteArray()); + bitmap = BitmapFactory.decodeStream(is, null, newOpts); + //压缩好比例大小后再进行质量压缩 +// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 + return bitmap; + } + + + /** + * 计算图片的缩放值 + */ + public static int calculateInSampleSize(final int width, final int height, int reqWidth, int reqHeight) { + // Raw height and width of image + + int inSampleSize = 1; + + if (height > reqHeight || width > reqWidth) {//图片本身分辨率大于 + + // Calculate ratios of height and width to requested height and + // width + final int heightRatio = Math.round((float) height / (float) reqHeight); + final int widthRatio = Math.round((float) width / (float) reqWidth); + + // Choose the smallest ratio as inSampleSize value, this will + // guarantee + // a final image with both dimensions larger than or equal to the + // requested height and width. + inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; + } + + return inSampleSize; + } + + + /** + * 旋转图片角度 + * + * @param bm + * @param orientationDegree + * @return + */ + public static Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) { + + Matrix m = new Matrix(); + m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2); + float targetX, targetY; + if (orientationDegree == 90) { + targetX = bm.getHeight(); + targetY = 0; + } else { + targetX = bm.getHeight(); + targetY = bm.getWidth(); + } + + final float[] values = new float[9]; + m.getValues(values); + + float x1 = values[Matrix.MTRANS_X]; + float y1 = values[Matrix.MTRANS_Y]; + + m.postTranslate(targetX - x1, targetY - y1); + + Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888); + Paint paint = new Paint(); + Canvas canvas = new Canvas(bm1); + canvas.drawBitmap(bm, m, paint); + + return bm1; + } + + + /** + * 查找视频文件对应于MediaStore的Uri + * + * @param file 视频文件 + * @return + */ + + public static Uri queryUriForVideo(Context context, File file) { + int id = getId(context, file); + if (id == -1) { + return null; + } + + return Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, String.valueOf(id)); + } + + /** + * 获得 指定视频文件F在MediaStore中对应的ID + * + * @param f 视频文件 + * @return 对应ID + */ + + private static int getId(Context context, File f) { + int id = -1; + // MediaStore.Video.Media.DATA:视频文件路径; + // MediaStore.Video.Media.DISPLAY_NAME : 视频文件名,如 testVideo.mp4 + // MediaStore.Video.Media.TITLE: 视频标题 : testVideo + String[] mediaColumns = {MediaStore.Video.Media._ID, + MediaStore.Video.Media.DATA, MediaStore.Video.Media.TITLE, + MediaStore.Video.Media.MIME_TYPE, + MediaStore.Video.Media.DISPLAY_NAME}; + + final String where = MediaStore.Video.Media.DATA + "=" + "?"; + + Cursor cursor = ((Activity) context).managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, + mediaColumns, where, new String[]{f.getAbsolutePath()}, null); + if (cursor == null) { + //Toast.makeText(this, "没有找到可播放视频文件", 1).show(); + return -1; + } + if (cursor.moveToFirst()) { + do { + id = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media._ID)); + //sysVideoList.add(info); + } while (cursor.moveToNext()); + } + return id; + } + + + private final static String LINEND = "\r\n"; + private final static String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线 + private final static String PREFIX = "--"; + + /** + * 封装表单文本数据 + * + * @param paramText + * @return + */ + static String bulidFormText(Map paramText) { + if (paramText == null || paramText.isEmpty()) return ""; + StringBuffer sb = new StringBuffer(""); + for (Map.Entry entry : paramText.entrySet()) { + sb.append(PREFIX).append(BOUNDARY).append(LINEND); + sb.append("Content-Disposition:form-data;name=\"" + + entry.getKey() + "\"" + LINEND); + //sb.append("Content-Type:text/plain;charset=" + CHARSET + LINEND); + sb.append(LINEND); + sb.append(entry.getValue()); + sb.append(LINEND); + } + return sb.toString(); + } + + private static final int TIME_OUT = 10 * 1000; // 超时时间 + private static final String CHARSET = "UTF-8"; // 设置编码 + + /** + * 上传文件到服务器 + * + * @param file 需要上传的文件 + * @param RequestURL 请求的rul + * @return 返回响应的内容 + */ + public static int uploadFile(File file, String RequestURL, Map params) { + int res = 0; + String result = null; + //String BOUNDARY = "-xst--image--upload-"; // 边界标识 随机生成 + //String PREFIX = "--", LINE_END = "\r\n"; + String CONTENT_TYPE = "multipart/form-data"; // 内容类型 + + try { + URL url = new URL(RequestURL); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setReadTimeout(TIME_OUT); + conn.setConnectTimeout(TIME_OUT); + conn.setDoInput(true); // 允许输入流 + conn.setDoOutput(true); // 允许输出流 + conn.setUseCaches(false); // 不允许使用缓存 + conn.setRequestMethod("POST"); // 请求方式 + conn.setRequestProperty("Charset", CHARSET); // 设置编码 + conn.setRequestProperty("connection", "keep-alive"); + conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); + + if (file != null) { + /** + * 当文件不为空时执行上传 + */ + DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); + //构建表单数据 + String entryText = bulidFormText(params); + //Log.e("-描述信息-", entryText); + dos.write(entryText.getBytes()); + + StringBuffer sb = new StringBuffer(); + sb.append(PREFIX); + sb.append(BOUNDARY); + sb.append(LINEND); + /** + * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 + * filename是文件的名字,包含后缀名 + */ + + sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + + file.getName() + "\"" + LINEND); + sb.append("Content-Type: application/octet-stream; charset=" + + CHARSET + LINEND); + sb.append(LINEND); + dos.write(sb.toString().getBytes()); + InputStream is = new FileInputStream(file); + byte[] bytes = new byte[1024]; + int len = 0; + while ((len = is.read(bytes)) != -1) { + dos.write(bytes, 0, len); + } + is.close(); + dos.write(LINEND.getBytes()); + byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); + dos.write(end_data); + dos.flush(); + /** + * 获取响应码 200=成功 当响应成功,获取响应的流 + */ + res = conn.getResponseCode(); + Log.e(TAG, "response code:" + res); + if (res == 200) { + InputStream input = conn.getInputStream(); + StringBuffer sb1 = new StringBuffer(); + String line = ""; + BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));//UTF-8,utf-8,GBK,gbk + while ((line = br.readLine()) != null) { + sb1.append(line); + } + Log.e(TAG, "--result : " + sb1.toString()); + + } else { + Log.e(TAG, "--request error"); + } + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return res; + } + + + public static void zip(String src, String dest) throws IOException { + //提供了一个数据项压缩成一个ZIP归档输出流 + ZipOutputStream out = null; + try { + File outFile = new File(dest);//源文件或者目录 + File fileOrDirectory = new File(src);//压缩文件路径 + out = new ZipOutputStream(new FileOutputStream(outFile)); + //如果此文件是一个文件,否则为false。 + if (fileOrDirectory.isFile()) { + zipFileOrDirectory(out, fileOrDirectory, ""); + } else { + //返回一个文件或空阵列。 + File[] entries = fileOrDirectory.listFiles(); + for (int i = 0; i < entries.length; i++) { + // 递归压缩,更新curPaths + zipFileOrDirectory(out, entries[i], ""); + } + } + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + //关闭输出流 + if (out != null) { + try { + out.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + } + + private static void zipFileOrDirectory(ZipOutputStream out, File fileOrDirectory, String curPath) throws IOException { + //从文件中读取字节的输入流 + FileInputStream in = null; + try { + //如果此文件是一个目录,否则返回false。 + if (!fileOrDirectory.isDirectory()) { + // 压缩文件 + byte[] buffer = new byte[4096]; + int bytes_read; + in = new FileInputStream(fileOrDirectory); + //实例代表一个条目内的ZIP归档 + ZipEntry entry = new ZipEntry(curPath + fileOrDirectory.getName()); + //条目的信息写入底层流 + out.putNextEntry(entry); + while ((bytes_read = in.read(buffer)) != -1) { + out.write(buffer, 0, bytes_read); + } + out.closeEntry(); + } else { + // 压缩目录 + File[] entries = fileOrDirectory.listFiles(); + for (int i = 0; i < entries.length; i++) { + // 递归压缩,更新curPaths + zipFileOrDirectory(out, entries[i], curPath + fileOrDirectory.getName() + "/"); + } + } + } catch (IOException ex) { + ex.printStackTrace(); + Log.e("dhj", "zipFileOrDirectory: 出错"); + // throw ex; + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + } + + private void getScreenHot(View v, String filePath) { + try { + Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); + Canvas canvas = new Canvas(); + canvas.setBitmap(bitmap); + v.draw(canvas); + FileOutputStream fos = new FileOutputStream(filePath); + bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); + + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 保存日志到指定文件夹下 + * + * @param filename 日志文件名字 AppConfig.DEFAULT_SAVE_LOG_PATH + DateUtils.getDateFormat(new Date(), "yyyyMMdd") + "_"+filename+".txt"; + * @param text 日志内容 + */ + /* public static void fileLog(String filename, String text) { + File logPath = new File(AppConfig.DEFAULT_SAVE_LOG_PATH); + if (!logPath.exists()) { + logPath.mkdirs(); + } + String logfilePath = AppConfig.DEFAULT_SAVE_LOG_PATH + DateUtils.getDateFormat(new Date(), "yyyyMMdd") + "_" + filename + ".txt"; + File logFile = new File(logfilePath); + try { + if (!logFile.exists()) logFile.createNewFile(); + String log = String.format("[%s][%s][%s]: %s\r\n", filename, SystemUtils.getDeviceIdLite(AppContext.getInstance()), DateUtils.getDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"), text); + RandomAccessFile raf = new RandomAccessFile(logFile, "rwd"); + raf.seek(logFile.length()); + raf.write(log.getBytes()); + raf.close(); + } catch (IOException e) { + e.printStackTrace(); + } + }*/ +} -- libgit2 0.21.0