Filter Android StrictMode violations by duration

时间秒杀一切 提交于 2019-12-31 02:03:50

问题


Is there a way to filter StrictMode violations based on duration?

It's getting a bit annoying having these

StrictMode policy violation; ~duration=6 ms: android.os.StrictMode$StrictModeDiskWriteViolation: policy=31 violation=1

poisoning my logcat.

I think StrictMode is a useful feature, but I'd like to deal only with violations with a duration greater than, let's say, 50 ms, in the first development phase.


回答1:


The StrictMode API does not support filtering by duration.

But you can easily do so by filtering StrictMode's log reports:


A. Configure StrictMode to write errors to log:

public void onCreate() {
     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()
                 .penaltyLog() //<---------- write reports to log
                 .build());
     }
     super.onCreate();
}


B. Read logcat lines:

logcat = Runtime.getRuntime().exec(new String[]{"logcat", "-d"});
br = new BufferedReader(new InputStreamReader(logcat.getInputStream()),4*1024);
String line;
  final StringBuilder log = new StringBuilder();
  String separator = System.getProperty("line.separator");
    while ((line = br.readLine()) != null) {
          filterLogLine(line)
    }
}


C. filter lines by duration:

void filterLogLine(String line) {
    use StringTokenizer to parse the line
    get value of "~duration"
    and filter if lesser than your threshold
}

I leave you to figure out the exact details of the line parsing.



来源:https://stackoverflow.com/questions/25056157/filter-android-strictmode-violations-by-duration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!