之前想写个app来过滤log,有通过service来启动,也试过重定向到sdcard,但是总是得不到想要的结果,打印的只是本进程的一些log,后来想到通过AIDL去启动,没想到真的可以打印全局log。下面分享下简单的步骤:
1、定义aidl接口
interface ILogactService { /** * Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); void startlocat(); }
2、写个service,来启动过滤log的服务,至于commands,可以按照自己的需求自己定义,我过滤的是E级
public class LogcatService extends Service{ private IBinder binder = new LogCatBinder(); String resultpath; @Nullable @Override public IBinder onBind(Intent intent) { Log.e("scripttool", "onBind success"); return binder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } public void logcat() throws IOException { SharedPreferences sp = getSharedPreferences("logcatpath", Activity.MODE_PRIVATE); resultpath = sp.getString("resultpath", ""); Log.e("scripttool","startlogcat"); Log.e("scripttool", resultpath); String[] commands = {"logcat -c ", "logcat -v time *:E " + " >>" + resultpath + "/exec.txt", }; ShellUtils.execCommand(commands, true); } @Override public void onDestroy() { Log.e("scripttool", "logcat kill"); super.onDestroy(); } private final class LogCatBinder extends ILogactService.Stub{ @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { } @Override public void startlogcat() throws RemoteException { new Thread(new Runnable() { @Override public void run() { try { logcat(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } } }
3、定义好service后,可以设置一个开关来启动logcat服务,代码没有贴全,但是大概思路是这样,读者可以自由发挥