When our application can not respond the user input in time, the Android will invoke a ANR dialog (shown as the following figure)

As we know, if we do nothing,all Android application components — including Activities, Services, and Broadcast Receivers — start on the main application thread. So, if our application invoke some action that needs a long time, we'd better put it into another thread. In this way, our main thread can respond user action in time.
One of the functionality of Android Handler isto enqueue an action to be performed on a different thread than your own. So, we can put our i/o operation into a Handler. The following steps show how we can achieve this.
Step 0: Perpare a Runnable object who will do some processing in background:
Runnable worker = new Runnable()
{
@Override
public void run()
{
Toast.makeText(HandlerDemo.this,
"threading running", Toast.LENGTH_SHORT)
.show();
}
};
Step 1: Construct a Hanlder object in main thread.
/**
* Default constructor associates this handler with the queue for
* the current thread. If there isn't one, this handler won't be
* able to receive messages.
*/
handler = new Handler();
Step 2: Add the Runnable object to the messge queue:
/**
* Causes the Runnable r to be added to the message queue. The
* runnable will be run on the thread to which this handler is
* attached.
*/
handler.post(worker);
Ok, by now, the Runnable object will do the precess in a background thread for you. In this way, your main thread can respond the UI events now.
本文介绍了在Android应用中处理长时间运行的任务以避免ANR对话框的方法,通过使用Android Handler将I/O操作放入后台线程执行,确保主线程能够及时响应用户输入。
280

被折叠的 条评论
为什么被折叠?



