我在我的应用程序中启用了 StrictMode,它导致了一些预期的崩溃。 我如何才能找出我的代码中哪些地方违反了这些政策?
这是堆栈跟踪:
E/AndroidRuntime(19523): FATAL EXCEPTION: main
E/AndroidRuntime(19523): android.os.StrictMode$StrictModeViolation: policy=95 violation=2
E/AndroidRuntime(19523): at android.os.StrictMode.executeDeathPenalty(StrictMode.java:1326)
E/AndroidRuntime(19523): at android.os.StrictMode.access$1300(StrictMode.java:111)
E/AndroidRuntime(19523): at android.os.StrictMode$AndroidBlockGuardPolicy.handleViolation(StrictMode.java:1319)
E/AndroidRuntime(19523): at android.os.StrictMode$AndroidBlockGuardPolicy$1.run(StrictMode.java:1206)
E/AndroidRuntime(19523): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime(19523): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(19523): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(19523): at android.app.ActivityThread.main(ActivityThread.java:4424)
E/AndroidRuntime(19523): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(19523): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(19523): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
E/AndroidRuntime(19523): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
E/AndroidRuntime(19523): at dalvik.system.NativeStart.main(Native Method)
但是如您所见...它不是很有用...我知道是谁杀死了我的应用程序,我需要知道为什么!
谢谢。
最佳答案
您需要在您的 StrictMode.ThreadPolicy.Builder 上调用 penaltyLog()
,以便它向您显示根本原因并停止您的应用。
这是你目前可能拥有的:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyDeath()
.build());
如果你在主线程上调用网络,你会得到这个难以理解的异常:
E/AndroidRuntime(8752): android.os.StrictMode$StrictModeViolation: policy=71 violation=4
E/AndroidRuntime(8752): at android.os.StrictMode.executeDeathPenalty(StrictMode.java:1311)
如果您随后将 penaltyLog()
添加到您的策略中......
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.penaltyLog()
.penaltyDeath()
.build());
然后您会看到一条更有帮助的消息,如下所示。这将在 LogCat 输出中。
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)
如果仔细观察,您会发现此堆栈跟踪将引导您找到导致 StrictMode 违规的代码。
关于android - 查找违反 StrictMode 策略的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9780934/