之前想寫個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服務,代碼沒有貼全,但是大概思路是這樣,讀者可以自由發揮