Android是由Google推出的一款基於Linux平台的開源手機作業系統。已經推出就伸手廣大編程人員的喜愛。在這裡我們就先從Android logcat的相關應用來對這一系統進行一個深入的瞭解,以此方便我們的實際應用。
選項與說明
- -s 預設設定過濾器
- - f 檔案 輸出到記錄檔
- -c 清除日誌
- -d 擷取日誌
- -g 擷取日誌的大小
- - v 格式 設定日誌見下面的格式列印格式)
- v 格式與例範例
- brief W/tag ( 876): message
- process W( 876) message (tag)
- tag W/tag : message
- thread W( 876:0x37c) message
- raw message
- time 09-08 05:40:26.729 W/tag ( 876): message
- threadtime 09-08 05:40:26.729 876 892 W tag : message
- long [ 09-08 05:40:26.729 876:0x37c W/tag ] message
代碼例子:
AndroidManifest.xml添加讀取許可權
- < uses-permission android:name=
"android.permission.READ_LOGS" />
- < uses-permission android:name=
"android.permission.READ_LOGS" />
清除日誌
- try {
- Runtime.getRuntime().exec("logcat -c");
- } catch(Exception e) {
- try {
- Runtime.getRuntime().exec("logcat -c");
- } catch(Exception e) {
- }
擷取日誌
- try {
- ArrayList< String> commandLine = new ArrayList< String>();
- commandLine.add( "logcat");
- commandLine.add( "-d");
- commandLine.add( "-v");
- commandLine.add( "time");
- commandLine.add( "-s");
- commandLine.add( "tag:W");
- Process process = Runtime.getRuntime().exec
( commandLine.toArray( new String[commandLine.size()]));
- BufferedReader bufferedReader = new BufferedReader
( new InputStreamReader(process.getInputStream()), 1024);
- String line = bufferedReader.readLine();
- while ( line != null) {
- log.append(line);
- log.append("\n")
- }
- } catch ( IOException e) {
- }
- try {
- ArrayList< String> commandLine = new ArrayList< String>();
- commandLine.add( "logcat");
- commandLine.add( "-d");
- commandLine.add( "-v");
- commandLine.add( "time");
- commandLine.add( "-s");
- commandLine.add( "tag:W");
- Process process = Runtime.getRuntime().exec
( commandLine.toArray( new String[commandLine.size()]));
- BufferedReader bufferedReader = new BufferedReader
( new InputStreamReader(process.getInputStream()), 1024);
- String line = bufferedReader.readLine();
- while ( line != null) {
- log.append(line);
- log.append("\n")
- }
- } catch ( IOException e) {
- }
結果:
- 09-08 09:44:42.267 W/tag ( 754): message1
- 09-08 09:44:42.709 W/tag ( 754): message2
- 09-08 09:44:43.187 W/tag ( 754): message3
- 09-08 09:44:45.295 E/tag ( 754): message8