Finding what violated StrictMode policy

故事扮演 提交于 2019-11-30 02:08:56

You need to call penaltyLog() on your StrictMode.ThreadPolicy.Builder, so that it will show you the underlying reason as well as stopping your app.

Here's what you probably have currently:

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyDeath()
.build());

If you call the network on the main thread, you'll get this exception which is hard to understand:

E/AndroidRuntime(8752): android.os.StrictMode$StrictModeViolation: policy=71 violation=4
E/AndroidRuntime(8752):     at android.os.StrictMode.executeDeathPenalty(StrictMode.java:1311)

If you then add penaltyLog() to your policy...

StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath()
.build());

then you will see a much more helpful message like the one below. This will be in the LogCat output.

D/StrictMode(8810): StrictMode policy violation; ~duration=2956 ms: android.os.StrictMode$StrictModeNetworkViolation: policy=87 violation=4
D/StrictMode(8810):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1090)

If you look closely, you'll see that this stack trace will lead you to the code which is causing the StrictMode violation.

Whenever I see stack traces like this I always look into my Activity lifecycle events. Checkout what's going on in your onCreate, onResume, onPause methods (there are more lifecycle events but these are the common ones). Put break points in those methods and see which one terminates with this fatal message. Then take it from there.

Try catching this error using

protected void onResume() {
  super.onResume();
  try {
    codeThatCrashesBecauseOfStrictMode();
  } catch(Throwable tr) { Log.e(tr); }
}

This should be a pretty good starting point for debugging this problem.

Dimitri Dewaele

StrictMode (android.os.StrictMode) class can be used to enable and enforce various policies that can be checked for and reported upon.

This can be a StrictMode violation in executing a disk write violation that occurs when you are performing disk writes on the main UI thread. To solve it, you need to move the disk writes off the main thread.

If you can't move the code at this point, you could disable the check for a part of the code.

Explicitly add code to stop checking for a particular rule violation just before the offending code is executed and then re-enable detection for that rule after the offending code has completed.

StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);

Source code taken from here.

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