问题
I know that StrictMode designed mainly to be used in application development phase, but according to my app needs, it's not acceptable to get ANR while it's quite acceptable to get crash, and StrictMode
provides a way to prevent ANR dialogs:
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().penaltyDeath().build());
what if I used it inside the app production phase? and what will happen when the app getting ANR while StrictMode
used? will it freeze, crash, or wait until getting responded again?
回答1:
StrictMode is disabled by default, and users needs to enter "Developer's mode" in their Android to enable it.
That makes the solution of using StrictMode irrelevant.
ANR's could occur in very rare occasions completely out of your control, due to conditions such as very low memory or other app choking the CPU.
However, you can minimize the likelihood of getting ANR's simply by moving every single operation that access storage or network to an asynchronous task.
In my software I add this line of code to all dangerous places:
assert !Util.isMainThread():"woh! what am I doing on the main thread??"
and have this method in some Util class:
public static boolean isMainThread() {
return Looper.myLooper().equals(Looper.getMainLooper());
}
... And a useful tip to quickly enable the assertion from command line:adb shell setprop debug.assert 1
or 0
to disable.
来源:https://stackoverflow.com/questions/29392969/using-strictmode-in-app-production-phase