CatchLog log信息捕捉

#tech #android #java

一定一定要添加权限!!!

<uses-permission android:name="android.permission.READ_LOGS" />

通过启动另一个service来获取log信息。并通过broadcast 发送log信息。

public void run() {  
        // TODO Auto-generated method stub  
        System.out.println("the function run() is running.");  
        Process pro = null;  
        String line=null;  
        try{  
            //Runtime.getRuntime().exec("logcat -d");  
            pro= Runtime.getRuntime().exec(new String[] {"logcat","*:I"});  
            BufferedReader br= new BufferedReader(new InputStreamReader(pro.getInputStream()));  
            while(isCatchLog){  
                if((line=br.readLine())!=null){  
                    logContentsArrayList.add(line);  
                    sendLogContent(logContentsArrayList);  
                    Thread.sleep(1000);  
                }else{  
                    System.out.println("readline() is null");  
                }  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
          
    }  

mainactivity从broadcast里获取intent,从而取得bundle内的log信息。

private class LogBroadcastReceiver extends BroadcastReceiver {       
        private String action = null;  
        private Bundle bundle = null;  
  
        @Override  
        public void onReceive(Context context, Intent intent) {  
            action = intent.getAction();  
            if (LOG_ACTION.equals(action)) {  
                bundle = intent.getExtras();  
                ArrayList<String> logArrayList = bundle  
                        .getStringArrayList("log");  
                adapter = new ArrayAdapter<String>(MainActivity.this,  
                        android.R.layout.simple_list_item_1, logArrayList);  
                logListView.setAdapter(adapter);  
                /*String[] logs = new String[logArrayList.size()];           //log存储 
                logs = logArrayList.toArray(logs); 
                if (logs.length > 0) { 
                    for (int i = 0; i < logs.length; i++) { 
                        logString.append(logs[i]); 
                        logString.append("\n"); 
                    } 
                } 
 
                try { 
                    fileService.saveToSDCard("/log.txt", logString.toString()); 
                } catch (Exception e) { 
                    e.printStackTrace(); 
                }*/  
            }  
        }  
    }  
    private void registerLogBroadcastReceiver() {  
        logBroadcastReceiver = new LogBroadcastReceiver();  
        IntentFilter filter = new IntentFilter();  
        filter.addAction(LOG_ACTION);  
        registerReceiver(logBroadcastReceiver, filter);  
        //System.out.println("register logBroadcastReceiver");  
    }