`
whotodo
  • 浏览: 166994 次
文章分类
社区版块
存档分类
最新评论

Using Handler to Avoid ANR

 
阅读更多

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.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics