public static void e(String msg) { if (isDebug){ Log.e(TAG, msg); PrintToFileUtil.input2File(msg,"path"); } }
/** * 將內容直接寫過文件中,本身設置路徑 * 這個是一邊打印日誌,一邊將日誌寫入到file * 不建議直接new一個子線程作寫入邏輯,建議開啓線程池,避免處處開啓線程損耗性能 * @param input 寫入內容 * @param filePath 路徑 * @return */ static boolean input2File(final String input, final String filePath) { if (sExecutor == null) { sExecutor = Executors.newScheduledThreadPool(5); } Future<Boolean> submit = sExecutor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { BufferedWriter bw = null; try { // 構造給定文件名的FileWriter對象,並使用布爾值指示是否追加寫入的數據。 FileWriter fileWriter = new FileWriter(filePath, true); bw = new BufferedWriter(fileWriter); bw.write(input); return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { if (bw != null) { bw.close(); } } catch (IOException e) { e.printStackTrace(); } } } }); try { return submit.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return false; }
/** * 遇到問題: * 1.何時調用這個方法? * 2.爲何調用這個方法會形成程序無響應,卡在什麼地方? * 3.如何避免形成線程堵塞 * 4.當打印到必定日誌後,如何切換到下一個.txt文件? * @param logPath */ public static void setPrint(String logPath){ if (sExecutor == null) { sExecutor = Executors.newScheduledThreadPool(5); } //以xx月xx日爲命名文件名,這樣天天的文件都是不同的 Date now = new Date(System.currentTimeMillis()); String format = FORMAT.format(now); String date = format.substring(0, 5); final String newLogPath = logPath +date; Future<Boolean> submit = sExecutor.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { /*核心代碼*/ while(captureLogThreadOpen){ /*命令的準備*/ ArrayList<String> getLog = new ArrayList<>(); getLog.add("logcat"); getLog.add("-d"); getLog.add("-v"); getLog.add("time"); ArrayList<String> clearLog = new ArrayList<>(); clearLog.add("logcat"); clearLog.add("-c"); try{ //抓取當前的緩存日誌 Process process = Runtime.getRuntime().exec(getLog.toArray(new String[getLog.size()])); //獲取輸入流 BufferedReader buffRead = new BufferedReader(new InputStreamReader(process.getInputStream())); //清除是爲了下次抓取不會從頭抓取 Runtime.getRuntime().exec(clearLog.toArray(new String[clearLog.size()])); String str = null; //打開文件 File logFile = new File(newLogPath + "log.txt"); //true表示在寫的時候在文件末尾追加 FileOutputStream fos = new FileOutputStream(logFile, true); //換行的字符串 String newline = System.getProperty("line.separator"); //Date date = new Date(System.currentTimeMillis()); //String time = format.format(date); //Log.i(TAG, "thread"); //打印設備信息 fos.write(printDeviceInfo().getBytes()); while((str=buffRead.readLine())!=null){ //循環讀取每一行 //Runtime.getRuntime().exec(clearLog.toArray(new String[clearLog.size()])); //Log.i(TAG, str); @SuppressLint("SimpleDateFormat") Date date = new Date(System.currentTimeMillis()); String time = FORMAT.format(date); //加上年 fos.write((time + str).getBytes()); //換行 fos.write(newline.getBytes()); logCount++; //大於100000行就退出 if(logCount>100000){ captureLogThreadOpen = false; fos.close(); break; } } fos.close(); String[] strings = clearLog.toArray(new String[clearLog.size()]); Runtime.getRuntime().exec(strings); return true; }catch(Exception e){ e.printStackTrace(); return false; } } return true; } }); try { submit.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }
5.1 文檔要點php
5.2 具體的實現代碼android
<service android:name=".service.LogService" /> <!--系統日誌權限--> <uses-permission android:name="android.permission.READ_LOGS" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
public class LogService extends Service { //日誌 private static final String TAG = "LogService"; //內存中日誌文件最大值,10M private static final int MEMORY_LOG_FILE_MAX_SIZE = 10 * 1024 * 1024; //內存中的日誌文件大小監控時間間隔,10分鐘 private static final int MEMORY_LOG_FILE_MONITOR_INTERVAL = 10 * 60 * 1000; //sd卡中日誌文件的最多保存天數 private static final int SDCARD_LOG_FILE_SAVE_DAYS = 7; //日誌文件在內存中的路徑(日誌文件在安裝目錄中的路徑) private String LOG_PATH_MEMORY_DIR; //日誌文件在sdcard中的路徑【主要這個很重要】 private String LOG_PATH_SDCARD_DIR; //當前的日誌記錄類型爲存儲在SD卡下面 private final int SDCARD_TYPE = 0; //當前的日誌記錄類型爲存儲在內存中 private final int MEMORY_TYPE = 1; //當前的日誌記錄類型,默認是SD卡 private int CURR_LOG_TYPE = SDCARD_TYPE; //若是當前的日誌寫在內存中,記錄當前的日誌文件名稱 private String CURR_INSTALL_LOG_NAME; //本服務輸出的日誌文件名稱,也能夠是txt格式,或者後綴名是.log private String logServiceLogName = "Log.log"; @SuppressLint("SimpleDateFormat") private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //日誌名稱格式 @SuppressLint("SimpleDateFormat") private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH時mm分ss秒"); private OutputStreamWriter writer ; private Process process; //喚醒 private PowerManager.WakeLock wakeLock; //SDCard狀態監測,廣播監聽sd卡動態,好比用戶拔下sd卡 private SDStateMonitorReceiver sdStateReceiver; private LogTaskReceiver logTaskReceiver; /* 是否正在監測日誌文件大小; * 若是當前日誌記錄在SDard中則爲false * 若是當前日誌記錄在內存中則爲true*/ private boolean logSizeMoniting = false; //日誌文件監測action private static String MONITOR_LOG_SIZE_ACTION = "MONITOR_LOG_SIZE"; //切換日誌文件action private static String SWITCH_LOG_FILE_ACTION = "SWITCH_LOG_FILE_ACTION"; /** * 無需綁定 * @param intent intent * @return IBinder對象 */ @Override public IBinder onBind(Intent intent) { return null; } /** * 銷燬時調用該方法 */ @Override public void onDestroy() { super.onDestroy(); recordLogServiceLog("LogService onDestroy"); if (writer != null) { try { writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } } if (process != null) { process.destroy(); } //注意須要註銷廣播 if(sdStateReceiver!=null){ unregisterReceiver(sdStateReceiver); } if(logTaskReceiver!=null){ unregisterReceiver(logTaskReceiver); } } /** * 每次開啓service時,都會調用一次該方法,用於初始化 */ @Override public void onCreate() { super.onCreate(); init(); register(); deploySwitchLogFileTask(); new LogCollectorThread().start(); } private void init(){ //日誌文件在內存中的路徑(日誌文件在安裝目錄中的路徑) LOG_PATH_MEMORY_DIR = getFilesDir().getAbsolutePath() + File.separator + "log"; //本服務產生的日誌,記錄日誌服務開啓失敗信息 String LOG_SERVICE_LOG_PATH = LOG_PATH_MEMORY_DIR + File.separator + logServiceLogName; //日誌文件在sdcard中的路徑 LOG_PATH_SDCARD_DIR = FileUtils.getLocalRootSavePathDir("logger")+ File.separator + "log"; //建立log文件夾 createLogDir(); try { //true 表示能夠接着寫入 FileOutputStream fos = new FileOutputStream(LOG_SERVICE_LOG_PATH, true); writer = new OutputStreamWriter(fos); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); } //獲取PowerManager管理者 PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE); if (pm != null) { wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); } //當前的日誌記錄類型 CURR_LOG_TYPE = getCurrLogType(); Log.i(TAG, "LogService onCreate"); } private void register(){ IntentFilter sdCarMonitorFilter = new IntentFilter(); sdCarMonitorFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); sdCarMonitorFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); sdCarMonitorFilter.addDataScheme("file"); sdStateReceiver = new SDStateMonitorReceiver(); registerReceiver(sdStateReceiver, sdCarMonitorFilter); IntentFilter logTaskFilter = new IntentFilter(); logTaskFilter.addAction(MONITOR_LOG_SIZE_ACTION); logTaskFilter.addAction(SWITCH_LOG_FILE_ACTION); logTaskReceiver = new LogTaskReceiver(); registerReceiver(logTaskReceiver,logTaskFilter); } /** * 獲取當前應存儲在內存中仍是存儲在SDCard中 * @return 若是有sd卡,就放到sd卡中;沒有則放到內存卡中 */ public int getCurrLogType(){ if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return MEMORY_TYPE; }else{ return SDCARD_TYPE; } } /** * 部署日誌切換任務,天天凌晨切換日誌文件 */ private void deploySwitchLogFileTask() { Intent intent = new Intent(SWITCH_LOG_FILE_ACTION); PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); // 部署任務 AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); if (am != null) { am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender); } recordLogServiceLog("deployNextTask success,next task time is:"+myLogSdf.format(calendar.getTime())); } /** * 日誌收集 * 1.清除日誌緩存 * 2.殺死應用程序已開啓的Logcat進程防止多個進程寫入一個日誌文件 * 3.開啓日誌收集進程 * 4.處理日誌文件,移動 OR 刪除 */ class LogCollectorThread extends Thread { LogCollectorThread(){ super("LogCollectorThread"); Log.d(TAG, "LogCollectorThread is create"); } @SuppressLint("WakelockTimeout") @Override public void run() { try { //喚醒手機 wakeLock.acquire(); //每次記錄日誌以前先清除日誌的緩存, 否則會在兩個日誌文件中記錄重複的日誌 clearLogCache(); //運行PS命令獲得進程信息 List<String> orgProcessList = getAllProcess(); //根據ps命令獲得的內容獲取PID,User,name等信息 List<ProcessInfo> processInfoList = getProcessInfoList(orgProcessList); //關閉由本程序開啓的logcat進程 killLogcatPro(processInfoList); //開始收集日誌信息 createLogCollector(); //休眠,建立文件,而後處理文件,否則該文件還沒建立,會影響文件刪除 Thread.sleep(1000); //處理日誌文件,這裏面主要是處理sd卡和內存卡切換存儲日誌邏輯 handleLog(); //釋放 wakeLock.release(); } catch (Exception e) { e.printStackTrace(); recordLogServiceLog(Log.getStackTraceString(e)); } } } /** * 每次記錄日誌以前先清除日誌的緩存, 否則會在兩個日誌文件中記錄重複的日誌 */ private void clearLogCache() { Process pro = null; List<String> commandList = new ArrayList<>(); commandList.add("logcat"); commandList.add("-c"); try { pro = Runtime.getRuntime().exec(commandList.toArray(new String[commandList.size()])); StreamConsumer errorGobbler = new StreamConsumer(pro.getErrorStream()); StreamConsumer outputGobbler = new StreamConsumer(pro.getInputStream()); errorGobbler.start(); outputGobbler.start(); if (pro.waitFor() != 0) { Log.e(TAG, " clearLogCache proc.waitFor() != 0"); recordLogServiceLog("clearLogCache clearLogCache proc.waitFor() != 0"); } } catch (Exception e) { Log.e(TAG, "clearLogCache failed", e); recordLogServiceLog("clearLogCache failed"); } finally { try { if (pro != null) { pro.destroy(); } } catch (Exception e) { Log.e(TAG, "clearLogCache failed", e); recordLogServiceLog("clearLogCache failed"); } } } /** * 關閉由本程序開啓的logcat進程: * 根據用戶名稱殺死進程(若是是本程序進程開啓的Logcat收集進程那麼二者的USER一致) * 若是不關閉會有多個進程讀取logcat日誌緩存信息寫入日誌文件 * @param allPro allPro */ private void killLogcatPro(List<ProcessInfo> allPro) { if(process != null){ process.destroy(); } String packName = this.getPackageName(); //獲取本程序的用戶名稱 String myUser = getAppUser(packName, allPro); for (ProcessInfo processInfo : allPro) { if (processInfo.name.toLowerCase().equals("logcat") && processInfo.user.equals(myUser)) { android.os.Process.killProcess(Integer.parseInt(processInfo.pid)); //recordLogServiceLog("kill another logcat process success,the process info is:" // + processInfo); } } } /** * 獲取本程序的用戶名稱 * @param packName packName * @param allProList allProList * @return 程序名稱 */ private String getAppUser(String packName, List<ProcessInfo> allProList) { for (ProcessInfo processInfo : allProList) { if (processInfo.name.equals(packName)) { return processInfo.user; } } return null; } /** * 根據ps命令獲得的內容獲取PID,User,name等信息 * @param orgProcessList orgProcessList * @return 集合 */ private List<ProcessInfo> getProcessInfoList(List<String> orgProcessList) { List<ProcessInfo> proInfoList = new ArrayList<>(); for (int i = 1; i < orgProcessList.size(); i++) { String processInfo = orgProcessList.get(i); String[] proStr = processInfo.split(" "); // USER PID PPID VSIZE RSS WCHAN PC NAME // root 1 0 416 300 c00d4b28 0000cd5c S /init List<String> orgInfo = new ArrayList<>(); for (String str : proStr) { if (!"".equals(str)) { orgInfo.add(str); } } if (orgInfo.size() == 9) { ProcessInfo pInfo = new ProcessInfo(); pInfo.user = orgInfo.get(0); pInfo.pid = orgInfo.get(1); pInfo.ppid = orgInfo.get(2); pInfo.name = orgInfo.get(8); proInfoList.add(pInfo); } } return proInfoList; } /** * 運行PS命令獲得進程信息 * @return * USER PID PPID VSIZE RSS WCHAN PC NAME * root 1 0 416 300 c00d4b28 0000cd5c S /init */ private List<String> getAllProcess() { List<String> orgProList = new ArrayList<>(); Process pro = null; try { pro = Runtime.getRuntime().exec("ps"); StreamConsumer errorConsumer = new StreamConsumer(pro.getErrorStream()); StreamConsumer outputConsumer = new StreamConsumer(pro.getInputStream(), orgProList); errorConsumer.start(); outputConsumer.start(); if (pro.waitFor() != 0) { Log.e(TAG, "getAllProcess pro.waitFor() != 0"); recordLogServiceLog("getAllProcess pro.waitFor() != 0"); } } catch (Exception e) { Log.e(TAG, "getAllProcess failed", e); recordLogServiceLog("getAllProcess failed"); } finally { try { if (pro != null) { pro.destroy(); } } catch (Exception e) { Log.e(TAG, "getAllProcess failed", e); recordLogServiceLog("getAllProcess failed"); } } return orgProList; } /** * 開始收集日誌信息 * 日誌包括,f,d,v,time, */ public void createLogCollector() { // 日誌文件名稱 String logFileName = sdf.format(new Date()) + ".log"; List<String> commandList = new ArrayList<>(); commandList.add("logcat"); commandList.add("-f"); commandList.add("-d"); //commandList.add(LOG_PATH_INSTALL_DIR + File.separator + logFileName); commandList.add(getLogPath()); commandList.add("-v"); commandList.add("time"); // 過濾全部的i信息 commandList.add("*:I"); // 過濾全部的錯誤信息 //commandList.add("*:E"); // 過濾指定TAG的信息 // commandList.add("MyAPP:V"); // commandList.add("*:S"); try { process = Runtime.getRuntime().exec(commandList.toArray(new String[commandList.size()])); recordLogServiceLog("start collecting the log,and log name is:"+logFileName); // process.waitFor(); } catch (Exception e) { Log.e(TAG, "CollectorThread == >" + e.getMessage(), e); recordLogServiceLog("CollectorThread == >" + e.getMessage()); } } /** * 根據當前的存儲位置獲得日誌的絕對存儲路徑 * @return 路徑 */ public String getLogPath(){ createLogDir(); // 日誌文件名稱 String logFileName = sdf.format(new Date()) + ".log"; if(CURR_LOG_TYPE == MEMORY_TYPE){ CURR_INSTALL_LOG_NAME = logFileName; Log.d(TAG, "Log stored in memory, the path is:"+LOG_PATH_MEMORY_DIR + File.separator + logFileName); return LOG_PATH_MEMORY_DIR + File.separator + logFileName; }else{ CURR_INSTALL_LOG_NAME = null; Log.d(TAG, "Log stored in SDcard, the path is:"+LOG_PATH_SDCARD_DIR + File.separator + logFileName); return LOG_PATH_SDCARD_DIR + File.separator + logFileName; } } /** * 處理日誌文件 * 1.若是日誌文件存儲位置切換到內存中,刪除除了正在寫的日誌文件 * 而且部署日誌大小監控任務,控制日誌大小不超過規定值 * 2.若是日誌文件存儲位置切換到SDCard中,刪除7天以前的日誌,移 * 動全部存儲在內存中的日誌到SDCard中,並將以前部署的日誌大小 * 監控取消 */ public void handleLog(){ //當前的日誌記錄類型爲存儲在內存中 if(CURR_LOG_TYPE == MEMORY_TYPE){ //部署日誌大小監控任務 deployLogSizeMonitorTask(); //刪除內存中的過時日誌,刪除規則:除了當前的日誌和離當前時間最近的日誌保存其餘的都刪除 deleteMemoryExpiredLog(); }else{ //將日誌文件轉移到SD卡下面 moveLogfile(); //取消部署日誌大小監控任務 cancelLogSizeMonitorTask(); //刪除內存下過時的日誌 deleteSDCardExpiredLog(); } } /** * 部署日誌大小監控任務 */ private void deployLogSizeMonitorTask() { //若是當前正在監控着,則不須要繼續部署 if(logSizeMoniting){ return; } logSizeMoniting = true; Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION); PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); if (am != null) { am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), MEMORY_LOG_FILE_MONITOR_INTERVAL, sender); } Log.d(TAG, "deployLogSizeMonitorTask() suc !"); //recordLogServiceLog("deployLogSizeMonitorTask() succ ,start time is " + calendar.getTime().toLocaleString()); } /** * 取消部署日誌大小監控任務 */ private void cancelLogSizeMonitorTask() { logSizeMoniting = false; AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION); PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0); if (am != null) { am.cancel(sender); } Log.d(TAG, "canelLogSizeMonitorTask() suc"); } /** * 檢查日誌文件大小是否超過了規定大小 * 若是超過了從新開啓一個日誌收集進程 */ private void checkLogSize(){ //當文件不爲空時 if(CURR_INSTALL_LOG_NAME != null && CURR_INSTALL_LOG_NAME.length()>0){ //日誌文件在內存中的路徑+若是當前的日誌寫在內存中,記錄當前的日誌文件名稱 String path = LOG_PATH_MEMORY_DIR + File.separator + CURR_INSTALL_LOG_NAME; File file = new File(path); if(!file.exists()){ return; } Log.d(TAG, "checkLog() ==> The size of the log is too big?"); //當文件長度>=10M時,從新建立一個新的文件夾 if(file.length() >= MEMORY_LOG_FILE_MAX_SIZE){ Log.d(TAG, "The log's size is too big!"); new LogCollectorThread().start(); } } } /** * 建立日誌目錄 */ private void createLogDir() { //日誌文件在內存中的路徑的文件夾 File file = new File(LOG_PATH_MEMORY_DIR); boolean mkOk; if (!file.isDirectory() && file.exists()) { mkOk = file.mkdirs(); if (!mkOk) { //noinspection ResultOfMethodCallIgnored file.mkdirs(); } } //判斷SD卡是否存在,而且是否具備讀寫權限 //建立SD卡路徑下的文件夾 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { file = new File(LOG_PATH_SDCARD_DIR); if (!file.isDirectory()) { mkOk = file.mkdirs(); if (!mkOk) { recordLogServiceLog("move file failed,dir is not created succ"); } } } } /** * 將日誌文件轉移到SD卡下面 */ private void moveLogfile() { //首先判斷sd卡狀態 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { //recordLogServiceLog("move file failed, sd card does not mount"); return; } File file = new File(LOG_PATH_SDCARD_DIR); if (!file.isDirectory()) { boolean mkOk = file.mkdirs(); if (!mkOk) { //recordLogServiceLog("move file failed,dir is not created succ"); return; } } file = new File(LOG_PATH_MEMORY_DIR); if (file.isDirectory()) { File[] allFiles = file.listFiles(); for (File logFile : allFiles) { String fileName = logFile.getName(); if (logServiceLogName.equals(fileName)) { continue; } //String createDateInfo = getFileNameWithoutExtension(fileName); File beforeFile = new File(LOG_PATH_SDCARD_DIR + File.separator + fileName); boolean isSuccess = copy(logFile,beforeFile); if (isSuccess) { //noinspection ResultOfMethodCallIgnored logFile.delete(); //recordLogServiceLog("move file success,log name is:"+fileName); } } } } /** * 刪除內存下過時的日誌 */ private void deleteSDCardExpiredLog() { File file = new File(LOG_PATH_SDCARD_DIR); if (file.isDirectory()) { File[] allFiles = file.listFiles(); for (File logFile : allFiles) { String fileName = logFile.getName(); if (logServiceLogName.equals(fileName)) { continue; } //去除文件的擴展類型 String createDateInfo = getFileNameWithoutExtension(fileName); //判斷sdcard上的日誌文件是否能夠刪除 if (canDeleteSDLog(createDateInfo)) { //noinspection ResultOfMethodCallIgnored logFile.delete(); Log.d(TAG, "delete expired log success,the log path is:" + logFile.getAbsolutePath()); } } } } /** * 判斷sdcard上的日誌文件是否能夠刪除 * @param createDateStr createDateStr * @return 是否能夠刪除 */ public boolean canDeleteSDLog(String createDateStr) { boolean canDel ; //獲取當前時間 Calendar calendar = Calendar.getInstance(); //刪除7天以前日誌 calendar.add(Calendar.DAY_OF_MONTH, -1 * SDCARD_LOG_FILE_SAVE_DAYS); Date expiredDate = calendar.getTime(); try { Date createDate = sdf.parse(createDateStr); canDel = createDate.before(expiredDate); } catch (ParseException e) { Log.e(TAG, e.getMessage(), e); canDel = false; } return canDel; } /** * 刪除內存中的過時日誌,刪除規則: * 除了當前的日誌和離當前時間最近的日誌保存其餘的都刪除 */ private void deleteMemoryExpiredLog(){ File file = new File(LOG_PATH_MEMORY_DIR); if (file.isDirectory()) { File[] allFiles = file.listFiles(); Arrays.sort(allFiles, new FileComparator()); for (int i=0;i<allFiles.length-2;i++) { //"-2"保存最近的兩個日誌文件 File _file = allFiles[i]; if (logServiceLogName.equals(_file.getName()) || _file.getName().equals(CURR_INSTALL_LOG_NAME)) { continue; } //noinspection ResultOfMethodCallIgnored _file.delete(); Log.d(TAG, "delete expired log success,the log path is:"+_file.getAbsolutePath()); } } } /** * 拷貝文件 * @param source file * @param target file * @return 是否拷貝成功 */ private boolean copy(File source, File target) { FileInputStream in = null; FileOutputStream out = null; try { if(!target.exists()){ boolean createSuccess = target.createNewFile(); if(!createSuccess){ return false; } } in = new FileInputStream(source); out = new FileOutputStream(target); byte[] buffer = new byte[8*1024]; int count; while ((count = in.read(buffer)) != -1) { out.write(buffer, 0, count); } return true; } catch (Exception e) { e.printStackTrace(); Log.e(TAG, e.getMessage(), e); recordLogServiceLog("copy file fail"); return false; } finally{ try { if(in != null){ in.close(); } if(out != null){ out.close(); } } catch (IOException e) { e.printStackTrace(); Log.e(TAG, e.getMessage(), e); recordLogServiceLog("copy file fail"); } } } /** * 這個注意是記錄錯誤的日誌 * 記錄日誌服務的基本信息 防止日誌服務有錯,在LogCat日誌中沒法查找 * 此日誌名稱爲Log.log * @param msg msg */ private void recordLogServiceLog(String msg) { if (writer != null) { try { Date time = new Date(); writer.write(myLogSdf.format(time) + " : " + msg); writer.write("\n"); writer.flush(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, e.getMessage(), e); } } } /** * 去除文件的擴展類型(.log) * @param fileName fileName * @return 字符串 */ private String getFileNameWithoutExtension(String fileName){ return fileName.substring(0, fileName.indexOf(".")); } class ProcessInfo { public String user; private String pid; private String ppid; public String name; @Override public String toString() { return "ProcessInfo{" + "user='" + user + '\'' + ", pid='" + pid + '\'' + ", ppid='" + ppid + '\'' + ", name='" + name + '\'' + '}'; } } class StreamConsumer extends Thread { InputStream is; List<String> list; StreamConsumer(InputStream is) { this.is = is; } StreamConsumer(InputStream is, List<String> list) { this.is = is; this.list = list; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line ; while ((line = br.readLine()) != null) { if (list != null) { list.add(line); } } } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * 監控SD卡狀態 * @author Administrator * */ private class SDStateMonitorReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { //存儲卡被卸載 if(Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())){ if(CURR_LOG_TYPE == SDCARD_TYPE){ Log.d(TAG, "SDCard is UNMOUNTED"); CURR_LOG_TYPE = MEMORY_TYPE; new LogCollectorThread().start(); } }else{ //存儲卡被掛載 if(CURR_LOG_TYPE == MEMORY_TYPE){ Log.d(TAG, "SDCard is MOUNTED"); CURR_LOG_TYPE = SDCARD_TYPE; new LogCollectorThread().start(); } } } } /** * 日誌任務接收廣播 * 切換日誌,監控日誌大小 * @author Administrator * */ class LogTaskReceiver extends BroadcastReceiver{ public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //切換日誌文件action if(SWITCH_LOG_FILE_ACTION.equals(action)){ new LogCollectorThread().start(); }else if(MONITOR_LOG_SIZE_ACTION.equals(action)){ //日誌文件監測action checkLogSize(); } } } class FileComparator implements Comparator<File> { public int compare(File file1, File file2) { if(logServiceLogName.equals(file1.getName())){ return -1; }else if(logServiceLogName.equals(file2.getName())){ return 1; } String createInfo1 = getFileNameWithoutExtension(file1.getName()); String createInfo2 = getFileNameWithoutExtension(file2.getName()); try { Date create1 = sdf.parse(createInfo1); Date create2 = sdf.parse(createInfo2); if(create1.before(create2)){ return -1; }else{ return 1; } } catch (ParseException e) { return 0; } } } }