Преглед на файлове

增加定时删除日志功能

weizhengliang преди 1 година
родител
ревизия
ab28876ca7

+ 26 - 0
android_bed/src/main/h7_3128/java/com/wdkl/app/ncs/callingbed/activity/CallingbedActivity.kt

@@ -1663,6 +1663,25 @@ class CallingbedActivity :BaseActivity<CallingbedActivityPresenter, Callingbed2M
         }
     }
 
+    private fun deleteLog() {
+        try {
+            Log.e(TAG, "start delete logs")
+            debugLog(TAG, "start delete log...")
+
+            //定期删除日志
+            DeleteFileUtil.delete(
+                BaseApplication.appContext,
+                BaseApplication.appContext.getExternalFilesDir("xcrash").toString(),
+                true,
+                "tombstone",
+                5,
+                null
+            )
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
     inner class TimeReceiver: BroadcastReceiver() {
         override fun onReceive(context: Context, intent: Intent) {
             if (intent.action == Intent.ACTION_TIME_TICK) {
@@ -1679,6 +1698,13 @@ class CallingbedActivity :BaseActivity<CallingbedActivityPresenter, Callingbed2M
                     presenter.loadTcpServerHost()
                 }*/
                 checkNet()
+
+                val calendar = Calendar.getInstance()
+                val hour = calendar[Calendar.HOUR_OF_DAY]
+                val minute = calendar[Calendar.MINUTE]
+                if (hour == 23 && minute == 0) {
+                    deleteLog()
+                }
             } else if (intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
                 updateNetState()
             }

+ 152 - 0
common/src/main/code/com/wdkl/ncs/android/lib/utils/DeleteFileRunnable.java

@@ -0,0 +1,152 @@
+package com.wdkl.ncs.android.lib.utils;
+
+import android.content.Context;
+import android.os.Environment;
+import android.support.annotation.NonNull;
+import android.text.TextUtils;
+import android.util.Log;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+public class DeleteFileRunnable implements Runnable {
+
+    private Context context;
+    private String regEx;
+    private String dirPath;
+    private boolean prefix;
+    private int day;
+    private ExeCallBack callBack;
+    private static final String TAG = DeleteFileRunnable.class.getSimpleName();
+
+    public DeleteFileRunnable(Context context, String dirPath, boolean prefix, String regEx, int day, final ExeCallBack callBack) {
+        this.context = context;
+        this.regEx = regEx;
+        this.dirPath = dirPath;
+        this.prefix = prefix;
+        this.day = day;
+        this.callBack = callBack;
+    }
+
+    @Override
+    public void run() {
+        //删除文件
+        deleteFiles();
+        //删除缓存
+        //clearAllCache(context);
+    }
+
+
+    private void deleteFiles() {
+        if (!TextUtils.isEmpty(dirPath)) {
+            File dir = new File(dirPath);
+            if (dir.exists() && dir.isDirectory()) {
+                if (TextUtils.isEmpty(regEx)) {
+                    //删除所有文件
+                    deleteDir(dir);
+                } else {
+                    //删除指定前缀或后缀名称文件
+                    DeleteFileFilter filter = new DeleteFileFilter(prefix, regEx);
+
+                    File[] fileList = dir.listFiles(filter);
+                    if (fileList != null && fileList.length > 0) {
+                        for (File file : fileList) {
+                            if (file.isFile() && file.exists()) {
+                                if (day > 0) {
+                                    //按时间删除文件
+                                    try {
+                                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+                                        //获取当前时间
+                                        Date end = dateFormat.parse(dateFormat.format(new Date(System.currentTimeMillis())));
+                                        //文件时间减去当前时间
+                                        Date start = dateFormat.parse(dateFormat.format(new Date(file.lastModified())));
+                                        long diff = end.getTime() - start.getTime();//这样得到的差值是微秒级别
+                                        long days = diff / (1000 * 60 * 60 * 24);
+                                        if (days >= day) {
+                                            boolean delete = file.delete();
+                                            Log.i(TAG, "delete file 111111" + (delete ? " --> success" : "failed"));
+                                        }
+                                    } catch (Exception ex) {
+                                        //
+                                    }
+                                } else {
+                                    boolean delete = file.delete();
+                                    Log.i(TAG, "delete file 222222" + (delete ? " --> success" : "failed"));
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+
+            if (callBack != null) {
+                callBack.onFinish();
+            }
+        }
+    }
+
+    public void clearAllCache(Context context) {
+        deleteDir(context.getCacheDir());
+        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+            deleteDir(context.getExternalCacheDir());
+        }
+    }
+
+    private boolean deleteDir(File dir) {
+        if (dir != null) {
+            if (dir.isDirectory()) {
+                String[] children = dir.list();
+                for (String child : children) {
+                    boolean success = deleteDir(new File(dir, child));
+                    if (!success) {
+                        return false;
+                    }
+                }
+            } else {
+                if (day > 0) {
+                    //按时间删除文件
+                    try {
+                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+                        //获取当前时间
+                        Date end = dateFormat.parse(dateFormat.format(new Date(System.currentTimeMillis())));
+                        //文件时间减去当前时间
+                        Date start = dateFormat.parse(dateFormat.format(new Date(dir.lastModified())));
+                        long diff = end.getTime() - start.getTime();
+                        long days = diff / (1000 * 60 * 60 * 24);
+                        if (days >= day) {
+                            return dir.delete();
+                        }
+                    } catch (Exception ex) {
+                        //
+                    }
+                } else {
+                    return dir.delete();
+                }
+            }
+        }
+
+        return false;
+    }
+
+    class DeleteFileFilter implements FilenameFilter {
+
+        private boolean prefix;
+        private String reg; //文件前缀或后缀
+
+        public DeleteFileFilter(boolean isPrefix, @NonNull String regEx) {
+            this.prefix = isPrefix;
+            this.reg = regEx;
+        }
+
+        @Override
+        public boolean accept(File file, String s) {
+            return prefix ? s.startsWith(reg) : s.endsWith(reg);
+        }
+    }
+
+    public interface ExeCallBack {
+        void onFinish();
+    }
+}

+ 91 - 0
common/src/main/code/com/wdkl/ncs/android/lib/utils/DeleteFileUtil.java

@@ -0,0 +1,91 @@
+package com.wdkl.ncs.android.lib.utils;
+
+import android.content.Context;
+import android.os.Environment;
+
+import java.io.File;
+import java.math.BigDecimal;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class DeleteFileUtil {
+
+    private static final ExecutorService executor = Executors.newSingleThreadExecutor();
+
+    /**
+     * 获取缓存大小
+     * @param context
+     * @return
+     * @throws Exception
+     */
+    public static String getTotalCacheSize(Context context) throws Exception {
+        long cacheSize = getFolderSize(context.getCacheDir());
+        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
+            cacheSize += getFolderSize(context.getExternalCacheDir());
+        }
+        return getFormatSize(cacheSize);
+    }
+
+    // 获取文件
+    //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 "0K";
+        }
+
+        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";
+    }
+
+    //执行删除文件操作
+    public static void delete(Context context, String dirPath, boolean isPrefix, String regEx, int day, DeleteFileRunnable.ExeCallBack exeCallBack) {
+        executor.execute(new DeleteFileRunnable(context, dirPath, isPrefix, regEx, day, exeCallBack));
+    }
+}