Reputation: 2108
Somewhere I read that By using StrictMode we can avoid ANR in android. I tried like that below is the code
public class MyApplication extends Application {
@Override
public void onCreate() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyFlashScreen()
.penaltyDeath()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
.build());
super.onCreate();
}
and i tried to generate ANR for the testing purposes like below:
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("kishan","onTouchEvent");
while(true) {}
}
But still, ANR is coming on the screen. how to avoid ANR by using StrictMode? is it possible?
Upvotes: 1
Views: 6064
Reputation: 12362
What is ANR?
When the UI thread of an Android app is blocked for too long, an "Application Not Responding" (ANR) error is triggered. If the app is in the foreground, Android will display the ANR dialog for a particular application when it detects one of the following conditions:
How to avoid ANR?
By keeping your application's main thread responsive, you can prevent ANR dialogs from being shown to users.
onCreate()
and onResume()
.Diagnosing ANRs:
StrictMode is a developer tool which detects accidental disk or network access on the application's main thread, where UI operations are received and animations take place. You can use StrictMode at the application or activity level.
Checkout official android developer documents to know, How to fix the ANR problems?
Upvotes: 4
Reputation: 1167
You can disable Strict Mode by the following code snippet
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
What you were doing is enabling strict mode, you need to disable it, as per I understand your question.
Upvotes: 1
Reputation: 29824
As the StrictMode documentation says:
StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.
StrictMode will help you telling which part of your code doing some excessive works like network or disk by limiting the access then giving you ANR or a crash log which depends by the penalty you've set. It won't remove any of your ANR but limit you from creating code which result in ANR.
Upvotes: 1