android - 查找违反 StrictMode 策略的内容

标签 android android-strictmode

我在我的应用程序中启用了 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/

相关文章:

java - Android - 在 if else 语句之间使用相同的变量值

java - 如何将上传到云存储的图片调整为指定大小?

android - 严格模式 + 分析

android - 在 logcat 上看不到 StrictMode 详细信息 - 在屏幕旋转时抑制了 StrictMode 策略违规

android - 2.3 之前的 StrictMode

Android Kotlin 协程在严格模式下崩溃

android - 如何在 Android 3.0 (Honeycomb) 中调暗系统栏?

android - 我可以在 Android 应用程序的后端使用一些 Python 吗?

android - 为多个设备适配 Android 蓝牙聊天