3. What triggers ANR ?
No response to an input event (e.g. Key press,
screen touch within 5 seconds)
A BroadcastReceiver hasn't finished executing
within 10 seconds
5. How to avoid it ?
Android applications normally run entirely on a
single main thread.
Hence anything that takes a long time to complete
might trigger the ANR dialog.
6. How to avoid it
Long running operations and computationally
expensive calculations should be done in child
threads.
7. Create a child thread
Handler class allows you to queue tasks to be run
on different threads and allows you schedule
tasks using Message and Runnable objects
8. Handler mHandler = new Handler(){
public void handleMessage(Message m){ //a hook that let you pass messages
//do something here when receive messages
}
}
new Thread(){
public void run(){
doStuff();
Message m = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("key","value");
m.setData(b);
mHandler.sendMessage(m); // add Message to the end of the MessageQueue
}
}.start();
9. Create a child thread
Besides sending messages, we can also send
Runnable objects directly and schedule things to
be run at different times in the future.
post(Runnable r)
postAtFrontOfQueue(Runnable r)
postAtTime(Runnable r, long uptimeMillis)
Etc.
docs/reference/android/os/Handler.html
10. Manage > 1 Threads
Executor: an object that executes submitted
Runnable tasks. This interface provides a way to
decoupling task submission from the mechanics
of how each task will be run, including details of
thread use, scheduling, etc.
An Executor is normally used instead of explicitly
creating threads
docs/reference/java/util/concurrent/Executor.html
11. Manage > 1 Threads
ExecutorService : a more extensive interface for
Executor.
Allows you to manage termination and tracking
progress of one or more async tasks.
12. Demo program
http://www.engineyard.com/blog/2009/programmingco
sequence of twelve words that when hashed is bit
wise closest to a hash of a challenge phrase
All words must be from a 1,000 word dictionary
Basically a Hamming distance problem.
Let's dive into the code