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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值