ANR is actually a dialog that appears to the user whenever an application have been unresponsive for a long period of time or when some long operation takes place in the "main" thread.
so, how to diagnose the problem, it's easy,
adb shell cat/data/anr/traces.txt
the syntax will drump all the application not responding traces to the command prompt.(make sure to change the command promt buffer size otherwise you can not see the full log out)
Android will display the ANR dialog for a particular application when it detects one of the following conditions:
1. No response to an input event(such as a key press or screen touch events) within 5 seconds.
2. A BroadcastReceiver hasn't finished executing within 10 seconds.
3.if your application is doing work in the the background in response to user input, show that progress is being made(such as with a progressBar in your UI).
StrictMode:
You should avoid performing long running operations on the UI thread. This includes file and network access.
To ensure this you can use StrictMode. StrictMode is available as of API 9 (Android 2.3.3) and allows to setup thread policies for your application.
Via StrictMode you can instruct the Android system to crash your application if it performs long running operations, e.g. I/O in the user interface thread.
The following code shows how to use StrictMode. As the activity violates these settings it will crash.
package de.vogella.android.strictmode;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
public class TestStrictMode extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork()
// alternatively .detectAll() for all detectable problems
.penaltyLog()
.penaltyDeath()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
// alternatively .detectAll() for all detectable problems
.penaltyLog()
.penaltyDeath()
.build());
// Test code
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String eol = System.getProperty("line.separator");
try {
BufferedWriter writer =
new BufferedWriter(new OutputStreamWriter(openFileOutput("myfile",
MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
writer.write("This is a test3." + eol);
writer.write("This is a test4." + eol);
writer.write("This is a test5." + eol);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
using penaltyLog() you can watch the output of adb logcat while you use your application to see the violation as they happen.
No comments:
Post a Comment