- 浏览: 96118 次
- 性别:
- 来自: 珠海
最新评论
-
yingwei0831:
09-10 03:56:07.128: D/LogServic ...
Android日志服务例子,将日志记录在文件中并每天生成一个日志文件 -
yingwei0831:
<div class="quote_title ...
Android日志服务例子,将日志记录在文件中并每天生成一个日志文件 -
yingwei0831:
成功,楼主好厉害。接下来看看咋用吧
Android日志服务例子,将日志记录在文件中并每天生成一个日志文件 -
lanxin_zxy_it:
垃圾残品,发出来很好玩的样子
Android中加入悬浮窗 -
feixiangsmile:
<div class="quote_title ...
Android日志服务例子,将日志记录在文件中并每天生成一个日志文件
在调试的时候一般都是在logcat中看日志的信息,以便找出BUG和调试信息,但是如果在真机上的话不可能一直连接电脑查看日志,所以生成日志文件并保存,是一个比较普遍的需求,下面就是最近实现的一个例子。欢迎大家讨论并给出别的思路。
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.List; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Environment; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; /** * 日志服务,日志默认会存储在SDcar里如果没有SDcard会存储在内存中的安装目录下面。 * 1.本服务默认在SDcard中每天生成一个日志文件, * 2.如果有SDCard的话会将之前内存中的文件拷贝到SDCard中 * 3.如果没有SDCard,在安装目录下只保存当前在写日志 * 4.SDcard的装载卸载动作会在步骤2,3中切换 * 5.SDcard中的日志文件只保存7天 * @author Administrator * */ public class LogService extends Service { private static final String TAG = "LogService"; private static final int MEMORY_LOG_FILE_MAX_SIZE = 10 * 1024 * 1024; //内存中日志文件最大值,10M private static final int MEMORY_LOG_FILE_MONITOR_INTERVAL = 10 * 60 * 1000; //内存中的日志文件大小监控时间间隔,10分钟 private static final int SDCARD_LOG_FILE_SAVE_DAYS = 7; //sd卡中日志文件的最多保存天数 private String LOG_PATH_MEMORY_DIR; //日志文件在内存中的路径(日志文件在安装目录中的路径) private String LOG_PATH_SDCARD_DIR; //日志文件在sdcard中的路径 @SuppressWarnings("unused") private String LOG_SERVICE_LOG_PATH; //本服务产生的日志,记录日志服务开启失败信息 private final int SDCARD_TYPE = 0; //当前的日志记录类型为存储在SD卡下面 private final int MEMORY_TYPE = 1; //当前的日志记录类型为存储在内存中 private int CURR_LOG_TYPE = SDCARD_TYPE; //当前的日志记录类型 private String CURR_INSTALL_LOG_NAME; //如果当前的日志写在内存中,记录当前的日志文件名称 private String logServiceLogName = "Log.log";//本服务输出的日志文件名称 private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private OutputStreamWriter writer; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HHmmss");//日志名称格式 private Process process; private WakeLock wakeLock; private SDStateMonitorReceiver sdStateReceiver; //SDcard状态监测 private LogTaskReceiver logTaskReceiver; /* 是否正在监测日志文件大小; * 如果当前日志记录在SDcard中则为false * 如果当前日志记录在内存中则为true*/ private boolean logSizeMoniting = false; private static String MONITOR_LOG_SIZE_ACTION = "MONITOR_LOG_SIZE"; //日志文件监测action private static String SWITCH_LOG_FILE_ACTION = "SWITCH_LOG_FILE_ACTION"; //切换日志文件action @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); init(); register(); deploySwitchLogFileTask(); new LogCollectorThread().start(); } private void init(){ LOG_PATH_MEMORY_DIR = getFilesDir().getAbsolutePath() + File.separator + "log"; LOG_SERVICE_LOG_PATH = LOG_PATH_MEMORY_DIR + File.separator + logServiceLogName; LOG_PATH_SDCARD_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyApp" + File.separator + "log"; createLogDir(); /* ****************************************************** try { writer = new OutputStreamWriter(new FileOutputStream( LOG_SERVICE_LOG_PATH, true)); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); } * ******************************************************/ PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE); 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 */ 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); am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender); recordLogServiceLog("deployNextTask succ,next task time is:"+myLogSdf.format(calendar.getTime())); } /** * 日志收集 * 1.清除日志缓存 * 2.杀死应用程序已开启的Logcat进程防止多个进程写入一个日志文件 * 3.开启日志收集进程 * 4.处理日志文件 * 移动 OR 删除 */ class LogCollectorThread extends Thread { public LogCollectorThread(){ super("LogCollectorThread"); Log.d(TAG, "LogCollectorThread is create"); } @Override public void run() { try { wakeLock.acquire(); //唤醒手机 clearLogCache(); List<String> orgProcessList = getAllProcess(); List<ProcessInfo> processInfoList = getProcessInfoList(orgProcessList); killLogcatProc(processInfoList); createLogCollector(); Thread.sleep(1000);//休眠,创建文件,然后处理文件,不然该文件还没创建,会影响文件删除 handleLog(); wakeLock.release(); //释放 } catch (Exception e) { e.printStackTrace(); recordLogServiceLog(Log.getStackTraceString(e)); } } } /** * 每次记录日志之前先清除日志的缓存, 不然会在两个日志文件中记录重复的日志 */ private void clearLogCache() { Process proc = null; List<String> commandList = new ArrayList<String>(); commandList.add("logcat"); commandList.add("-c"); try { proc = Runtime.getRuntime().exec( commandList.toArray(new String[commandList.size()])); StreamConsumer errorGobbler = new StreamConsumer(proc .getErrorStream()); StreamConsumer outputGobbler = new StreamConsumer(proc .getInputStream()); errorGobbler.start(); outputGobbler.start(); if (proc.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 { proc.destroy(); } catch (Exception e) { Log.e(TAG, "clearLogCache failed", e); recordLogServiceLog("clearLogCache failed"); } } } /** * 关闭由本程序开启的logcat进程: * 根据用户名称杀死进程(如果是本程序进程开启的Logcat收集进程那么两者的USER一致) * 如果不关闭会有多个进程读取logcat日志缓存信息写入日志文件 * * @param allProcList * @return */ private void killLogcatProc(List<ProcessInfo> allProcList) { if(process != null){ process.destroy(); } String packName = this.getPackageName(); String myUser = getAppUser(packName, allProcList); /* recordLogServiceLog("app user is:"+myUser); recordLogServiceLog("========================"); for (ProcessInfo processInfo : allProcList) { recordLogServiceLog(processInfo.toString()); } recordLogServiceLog("========================"); */ for (ProcessInfo processInfo : allProcList) { 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 * @param allProcList * @return */ private String getAppUser(String packName, List<ProcessInfo> allProcList) { for (ProcessInfo processInfo : allProcList) { if (processInfo.name.equals(packName)) { return processInfo.user; } } return null; } /** * 根据ps命令得到的内容获取PID,User,name等信息 * * @param orgProcessList * @return */ private List<ProcessInfo> getProcessInfoList(List<String> orgProcessList) { List<ProcessInfo> procInfoList = new ArrayList<ProcessInfo>(); 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<String>(); 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); procInfoList.add(pInfo); } } return procInfoList; } /** * 运行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> orgProcList = new ArrayList<String>(); Process proc = null; try { proc = Runtime.getRuntime().exec("ps"); StreamConsumer errorConsumer = new StreamConsumer(proc .getErrorStream()); StreamConsumer outputConsumer = new StreamConsumer(proc .getInputStream(), orgProcList); errorConsumer.start(); outputConsumer.start(); if (proc.waitFor() != 0) { Log.e(TAG, "getAllProcess proc.waitFor() != 0"); recordLogServiceLog("getAllProcess proc.waitFor() != 0"); } } catch (Exception e) { Log.e(TAG, "getAllProcess failed", e); recordLogServiceLog("getAllProcess failed"); } finally { try { proc.destroy(); } catch (Exception e) { Log.e(TAG, "getAllProcess failed", e); recordLogServiceLog("getAllProcess failed"); } } return orgProcList; } /** * 开始收集日志信息 */ public void createLogCollector() { String logFileName = sdf.format(new Date()) + ".log";// 日志文件名称 List<String> commandList = new ArrayList<String>(); commandList.add("logcat"); commandList.add("-f"); //commandList.add(LOG_PATH_INSTALL_DIR + File.separator + logFileName); commandList.add(getLogPath()); commandList.add("-v"); commandList.add("time"); 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{ 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); am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), MEMORY_LOG_FILE_MONITOR_INTERVAL, sender); Log.d(TAG, "deployLogSizeMonitorTask() succ !"); //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); am.cancel(sender); Log.d(TAG, "canelLogSizeMonitorTask() succ"); } /** * 检查日志文件大小是否超过了规定大小 * 如果超过了重新开启一个日志收集进程 */ private void checkLogSize(){ if(CURR_INSTALL_LOG_NAME != null && !"".equals(CURR_INSTALL_LOG_NAME)){ 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?"); 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()) { mkOk = file.mkdirs(); if (!mkOk) { mkOk = file.mkdirs(); } } /* ************************************ file = new File(LOG_SERVICE_LOG_PATH); if (!file.exists()) { try { mkOk = file.createNewFile(); if (!mkOk) { file.createNewFile(); } } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } * ************************************/ 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"); return; } } } } /** * 将日志文件转移到SD卡下面 */ private void moveLogfile() { 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); boolean isSucc = copy(logFile, new File(LOG_PATH_SDCARD_DIR + File.separator + fileName)); if (isSucc) { 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); if (canDeleteSDLog(createDateInfo)) { logFile.delete(); Log.d(TAG, "delete expired log success,the log path is:" + logFile.getAbsolutePath()); } } } } /** * 判断sdcard上的日志文件是否可以删除 * @param createDateStr * @return */ public boolean canDeleteSDLog(String createDateStr) { boolean canDel = false; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -1 * SDCARD_LOG_FILE_SAVE_DAYS);//删除7天之前日志 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; } _file.delete(); Log.d(TAG, "delete expired log success,the log path is:"+_file.getAbsolutePath()); } } } /** * 拷贝文件 * @param source * @param target * @return */ private boolean copy(File source, File target) { FileInputStream in = null; FileOutputStream out = null; try { if(!target.exists()){ boolean createSucc = target.createNewFile(); if(!createSucc){ 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"); return false; } } } /** * 记录日志服务的基本信息 防止日志服务有错,在LogCat日志中无法查找 * 此日志名称为Log.log * * @param 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 * @return */ private String getFileNameWithoutExtension(String fileName){ return fileName.substring(0, fileName.indexOf(".")); } class ProcessInfo { public String user; public String pid; public String ppid; public String name; @Override public String toString() { String str = "user=" + user + " pid=" + pid + " ppid=" + ppid + " name=" + name; return str; } } 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 = null; while ((line = br.readLine()) != null) { if (list != null) { list.add(line); } } } catch (IOException ioe) { ioe.printStackTrace(); } } } /** * 监控SD卡状态 * @author Administrator * */ 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, "SDcar is UNMOUNTED"); CURR_LOG_TYPE = MEMORY_TYPE; new LogCollectorThread().start(); } }else{ //存储卡被挂载 if(CURR_LOG_TYPE == MEMORY_TYPE){ Log.d(TAG, "SDcar 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(); if(SWITCH_LOG_FILE_ACTION.equals(action)){ new LogCollectorThread().start(); }else if(MONITOR_LOG_SIZE_ACTION.equals(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; } } } @Override public void onDestroy() { super.onDestroy(); recordLogServiceLog("LogService onDestroy"); if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } if (process != null) { process.destroy(); } unregisterReceiver(sdStateReceiver); unregisterReceiver(logTaskReceiver); } }
最后不要忘记在配置文件中加入
<uses-permission android:name="android.permission.READ_LOGS" />
评论
21 楼
yingwei0831
2015-09-10
09-10 03:56:07.128: D/LogService(16172): Log stored in SDcard, the path is:/storage/emulated/0/Wonders/log/2015-09-10 035607.log
09-10 03:56:07.198: I/Timeline(16172): Timeline: Activity_idle id: android.os.BinderProxy@42084a98 time:10431434
09-10 03:56:08.148: D/LogService(16172): canelLogSizeMonitorTask() succ
09-10 03:56:17.428: I/LogService(16172): LogService onCreate
09-10 03:56:17.438: D/LogService(16172): LogCollectorThread is create
09-10 03:56:17.468: E/LogService(16172): clearLogCache proc.waitFor() != 0
09-10 03:56:17.498: W/System.err(16172): java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.508: W/System.err(16172): at java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.508: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:435)
09-10 03:56:17.508: W/System.err(16172): at at java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.518: W/System.err(16172): at libcore.io.IoBridge.read(IoBridge.java:435)
09-10 03:56:17.518: W/System.err(16172): at java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.528: W/System.err(16172): at java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.528: W/System.err(16172): java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.538: W/System.err(16172): at at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
09-10 03:56:17.548: W/System.err(16172): java.io.BufferedReader.fillBuf(BufferedReader.java:145) at
09-10 03:56:17.548: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.558: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.558: W/System.err(16172): com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.568: W/System.err(16172): at Caused by: com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.578: W/System.err(16172): Caused by: libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.588: W/System.err(16172): libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.588: W/System.err(16172): at libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.598: W/System.err(16172): at at libcore.io.Posix.read(Posix.java:128)libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.608: W/System.err(16172): at at libcore.io.Posix.read(Posix.java:128)libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.618: W/System.err(16172): at at java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.618: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:425)libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.628: W/System.err(16172): at ... at 5 more
09-10 03:56:17.628: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:435)libcore.io.IoBridge.read(IoBridge.java:425)
09-10 03:56:17.638: W/System.err(16172): ... at 5 more
09-10 03:56:17.638: W/System.err(16172): java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.638: W/System.err(16172): at java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.648: W/System.err(16172): at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
09-10 03:56:17.648: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.658: W/System.err(16172): at com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.658: W/System.err(16172): Caused by: libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.668: W/System.err(16172): at libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.668: W/System.err(16172): at libcore.io.Posix.read(Posix.java:128)
09-10 03:56:17.678: W/System.err(16172): at libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.678: W/System.err(16172): at libcore.io.IoBridge.read(IoBridge.java:425)
09-10 03:56:17.678: W/System.err(16172): ... 5 more
09-10 03:56:07.198: I/Timeline(16172): Timeline: Activity_idle id: android.os.BinderProxy@42084a98 time:10431434
09-10 03:56:08.148: D/LogService(16172): canelLogSizeMonitorTask() succ
09-10 03:56:17.428: I/LogService(16172): LogService onCreate
09-10 03:56:17.438: D/LogService(16172): LogCollectorThread is create
09-10 03:56:17.468: E/LogService(16172): clearLogCache proc.waitFor() != 0
09-10 03:56:17.498: W/System.err(16172): java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.508: W/System.err(16172): at java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.508: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:435)
09-10 03:56:17.508: W/System.err(16172): at at java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.518: W/System.err(16172): at libcore.io.IoBridge.read(IoBridge.java:435)
09-10 03:56:17.518: W/System.err(16172): at java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.528: W/System.err(16172): at java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.528: W/System.err(16172): java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.538: W/System.err(16172): at at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
09-10 03:56:17.548: W/System.err(16172): java.io.BufferedReader.fillBuf(BufferedReader.java:145) at
09-10 03:56:17.548: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.558: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.558: W/System.err(16172): com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.568: W/System.err(16172): at Caused by: com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.578: W/System.err(16172): Caused by: libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.588: W/System.err(16172): libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.588: W/System.err(16172): at libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.598: W/System.err(16172): at at libcore.io.Posix.read(Posix.java:128)libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.608: W/System.err(16172): at at libcore.io.Posix.read(Posix.java:128)libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.618: W/System.err(16172): at at java.io.IOException: read failed: EBADF (Bad file number)
09-10 03:56:17.618: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:425)libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.628: W/System.err(16172): at ... at 5 more
09-10 03:56:17.628: W/System.err(16172): libcore.io.IoBridge.read(IoBridge.java:435)libcore.io.IoBridge.read(IoBridge.java:425)
09-10 03:56:17.638: W/System.err(16172): ... at 5 more
09-10 03:56:17.638: W/System.err(16172): java.io.FileInputStream.read(FileInputStream.java:179)
09-10 03:56:17.638: W/System.err(16172): at java.io.InputStreamReader.read(InputStreamReader.java:233)
09-10 03:56:17.648: W/System.err(16172): at java.io.BufferedReader.fillBuf(BufferedReader.java:145)
09-10 03:56:17.648: W/System.err(16172): at java.io.BufferedReader.readLine(BufferedReader.java:397)
09-10 03:56:17.658: W/System.err(16172): at com.yinwei.utils.LogService$StreamConsumer.run(LogService.java:727)
09-10 03:56:17.658: W/System.err(16172): Caused by: libcore.io.ErrnoException: read failed: EBADF (Bad file number)
09-10 03:56:17.668: W/System.err(16172): at libcore.io.Posix.readBytes(Native Method)
09-10 03:56:17.668: W/System.err(16172): at libcore.io.Posix.read(Posix.java:128)
09-10 03:56:17.678: W/System.err(16172): at libcore.io.BlockGuardOs.read(BlockGuardOs.java:149)
09-10 03:56:17.678: W/System.err(16172): at libcore.io.IoBridge.read(IoBridge.java:425)
09-10 03:56:17.678: W/System.err(16172): ... 5 more
20 楼
yingwei0831
2015-09-10
nc_quick 写道
while ((line = br.readLine()) != null) 具体的是这行代码出错的
貌似是这里有点不对劲,为什么呢???
19 楼
yingwei0831
2015-09-10
成功,楼主好厉害。
接下来看看咋用吧
接下来看看咋用吧
18 楼
feixiangsmile
2014-09-09
nc_quick 写道
楼主,您好,我在测试您的代码的时候,文件生成不了。在run()里面抛出的异常, java.io.IOException: stream is closed,在xml中加入了
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />,
求指导?非常感谢
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />,
求指导?非常感谢
楼主这个问题怎么处理的呀? 我发现是引文proc.waitFor() 这句没有起到等待的作用,所以造成继续向下执行finally语句的proc.destroy(),从而关闭了流,造成readLine的异常。但是waitFor()的APi说明是应该阻塞,等待proc执行结束呀。求楼主解释一下为什么呀?
17 楼
csbbbird
2014-08-22
怎么停止这个服务呢,
我是想在我自己的程序运行的时候启动服务, 该程序退出后, 停止这个服务
我用stopService但是服务还是在运行
我是想在我自己的程序运行的时候启动服务, 该程序退出后, 停止这个服务
我用stopService但是服务还是在运行
16 楼
ttdevs
2013-05-07
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<service android:name=".LogService" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<service android:name=".LogService" />
15 楼
Sunnyfans
2012-09-17
别忘了在应用程序androidManifest里面忘了加
<service android:name=".LogService" ></service>注册LogService这个Server
顶楼主
<service android:name=".LogService" ></service>注册LogService这个Server
顶楼主
14 楼
RZMars
2012-08-29
我的连目录都木有,,,,,,何解?
13 楼
dianqijiaojian
2011-12-15
我的ok了,,,
12 楼
dianqijiaojian
2011-12-15
补充一下,服务启动了,但没有生成文件,只生成目录walktour---->log ,LOG下面没有文件。楼主请帮忙一下
<uses-permission android:name="android.permission.READ_LOGS" />权限已经加入,不过还是只生成目录。
me too;
<uses-permission android:name="android.permission.READ_LOGS" />权限已经加入,不过还是只生成目录。
me too;
11 楼
cgxinyan
2011-11-04
楼主威武
10 楼
nc_quick
2011-10-19
while ((line = br.readLine()) != null) 具体的是这行代码出错的
9 楼
nc_quick
2011-10-19
楼主,您好,我在测试您的代码的时候,文件生成不了。在run()里面抛出的异常, java.io.IOException: stream is closed,在xml中加入了
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />,
求指导?非常感谢
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />,
求指导?非常感谢
8 楼
easion_zms
2011-10-19
freemanls 写道
LZ如果可能,能给一份源码么?
这已经是剥离出来的源码了
直接可以用的
7 楼
freemanls
2011-09-30
LZ如果可能,能给一份源码么?
6 楼
freemanls
2011-09-30
peter_ims 写道
补充一下,服务启动了,但没有生成文件,只生成目录walktour---->log ,LOG下面没有文件。楼主请帮忙一下
同样的错误,<uses-permission android:name="android.permission.READ_LOGS" />权限已经加入,不过还是只生成目录。
peter_ims 写道
您好,我用Intent stateService = new Intent (this,LogService.class);
startService( stateService ); 我在一个Activity里启动服务后,只生成目录,没有文件。后来在查看LogService,发现LogService都没有启动,但奇怪为什么又生成目录了
startService( stateService ); 我在一个Activity里启动服务后,只生成目录,没有文件。后来在查看LogService,发现LogService都没有启动,但奇怪为什么又生成目录了
这个问题应该是service生命周期的。可能是sercice没有死的原因。
5 楼
easion_zms
2011-08-17
peter_ims 写道
补充一下,服务启动了,但没有生成文件,只生成目录walktour---->log ,LOG下面没有文件。楼主请帮忙一下
有没有加入
<uses-permission android:name="android.permission.READ_LOGS" />
4 楼
peter_ims
2011-08-16
补充一下,服务启动了,但没有生成文件,只生成目录walktour---->log ,LOG下面没有文件。楼主请帮忙一下
3 楼
peter_ims
2011-08-16
您好,我用Intent stateService = new Intent (this,LogService.class);
startService( stateService ); 我在一个Activity里启动服务后,只生成目录,没有文件。后来在查看LogService,发现LogService都没有启动,但奇怪为什么又生成目录了
startService( stateService ); 我在一个Activity里启动服务后,只生成目录,没有文件。后来在查看LogService,发现LogService都没有启动,但奇怪为什么又生成目录了
2 楼
easion_zms
2011-06-17
extramoney 写道
菜鸟问题:怎么使用LogService?
Intent stateService = new Intent (this,com.app.service.app.LogService.class);
startService( stateService );
相关推荐
Android日志服务例子,将日志记录在文件中并每天生成一个日志文件
在Android开发中,条码和二维码扫描功能是一个常见的需求,比如在商品管理、信息录入、电子票务等场景。这个“Android条码扫描例子”提供了一个实用的解决方案,旨在帮助开发者快速集成并实现扫描功能。下面我们将...
在Android开发中,JNI(Java Native Interface)是一个关键的组件,它允许Java代码与其他编程语言(如C++)交互。JNI在很多场景下都非常重要,比如优化性能、使用硬件加速功能、接入第三方库或者实现与操作系统更...
在Android环境中,虽然Android本身已经提供了一个内置的日志系统(Log类),但Log4j由于其强大的功能和可配置性,也受到了一些开发者的青睐。本篇将详细介绍如何在Android项目中使用log4j。 首先,理解Log4j的基本...
本插件示例展示了如何在Cordova应用中调用Android服务,通过AIDL(Android Interface Definition Language)进行通信,并将服务打包为一个单独的jar文件。 首先,理解Cordova插件机制至关重要。Cordova插件是连接...
在这个“android MQTT 带SSL加密连接例子demo”中,我们将探讨如何在Android应用中使用BKS(Bouncy Castle Key Store)加密文件来实现安全的MQTT连接。 首先,我们需要理解MQTT协议。MQTT是一种基于发布/订阅模式的...
本文将通过一个具体的例子,即ANR(Application Not Responding)问题,来深入探讨如何利用LOG分析和解决Android应用中的故障。 首先,我们遇到的问题是ANR,这是用户在使用应用时常见的错误,通常发生在主线程被...
这个例子假设你有一个名为`native-lib.cpp`的本地源文件,它将链接到Android的日志库。 3. **引入三方库**:如果你有三方的SO文件,可以在`CMakeLists.txt`中使用`add_library`命令添加它们。例如,如果你有`...
在Android应用开发中,逆向工程是一个常见的技术领域,它涉及到对APK文件的解包、反编译、修改和重新打包,以了解其内部工作原理或进行安全分析。在这个"android smali插桩重打包逆向调试例子"中,我们将深入探讨...
本篇将详细介绍如何成功集成Tinker到你的Android项目中,并通过一个小型示例来演示其工作原理。 **一、Tinker概述** Tinker是一个动态加载技术,它基于Android的DexClassLoader和ApkPatch工具,能够实现对APK进行...
在Android Native Development Kit (NDK)中,`android.mk`文件是用于编译原生C/C++代码的关键构建脚本。这个文件告诉NDK如何处理源代码、链接库和其他资源,以便将它们编译成可供Android应用使用的共享库或静态库。 ...
在`Build Settings`中,选择`Export Project`,这将导出一个Android Studio项目。在Android Studio中,按照步骤签署并打包应用,然后上传到Google Play或其他分发平台。 7. **源代码分析** 提供的源代码可能包含...
【Bugly-Android-Demo】是一个开源项目,主要目的是向开发者展示如何在Android应用中集成并有效使用腾讯Bugly的SDK。Bugly是一款强大的移动应用稳定性管理平台,它能够帮助开发者快速定位、修复运行时错误,提升应用...
在Android平台上,开发一款音乐播放器是一个常见的任务,Android Studio作为官方推荐的集成开发环境,提供了丰富的工具和库来帮助开发者实现这样的应用。本项目是一个简单的音乐播放器示例,适用于Android 6.0(API...
**例子**:例如在Windows环境下,如果你的Android工程目录在`E:\Projects\Demo`,符号表工具在`D:\Downloads\buglySymbolAndroid`,App ID为900012345,App Key为`abcdefghijk`,App包名为`com.batman.demo`,App...
在Android开发中,有时我们需要使用C或C++的代码来实现一些高性能的计算或与硬件交互,这时就需要创建本地库(Native Library),通常以.so文件形式存在。Android.mk文件是Android NDK(Native Development Kit)的...
4. **定义服务操作**:在这个例子中,可能包含一个循环,每隔一段时间生成一个随机数,并根据需求进行相应的操作,如写入日志或发送广播。 5. **注册服务**:在AndroidManifest.xml文件中声明你的Service,确保它能...
本篇将详细介绍如何在Android环境中创建和使用自定义的日志信息。 首先,我们要了解Android内核中的LOG机制。Android基于Linux内核,因此,它的内核日志系统采用了Linux的`printk`函数。`printk`类似于C语言的`...
也有分析认为,谷歌并不想做一个简单的手机终端制造商或者软件平台开发商,而意在一统传统互联网和 移 动互联网。----------------------------------- Android 编程基础 4 Android Android Android Android 手机新...