[mobilesafe] 07_读取用户的日志

Android 4.0

读取用户的日志

收集用户日志adb log
adb logcat -b radio 打印通话过程的日志
核心代码:
package cn.zengfansheng.readuserlog;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
 
/**
* 读取用户日志的服务类
* @author hacket
*/

public class ReadUserLogService extends Service {
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
 
        Toast.makeText(getApplicationContext(), "开始收集日志", 1).show();
 
        // 服务一被创建,就读取用户日志
        // 要开启子线程
        new Thread() {
            public void run() {
                try {
                    Process process = Runtime.getRuntime().exec("logcat");
                    InputStream is = process.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
                    File file = new File(getFilesDir(), "logcat.log");
                    FileOutputStream fos = new FileOutputStream(file);
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
 
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        if (line.contains("ActivityManager")) {
                            bw.write("---------------");
                            bw.write(line);
                            bw.newLine();
                            bw.flush();
                        }
                    }
                    // 可以不关闭,因为总是在打印日志
                    bw.close();
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
 
    }
}