Creating Toast in IntentService

Oftentimes, we need a background service to do a long running task like downloading a file when we develop android apps. IntentService is a simple solution. All we need is to configure the manifest xml, adding the new service, and create subclass of IntentService, implementing the constructor and onHandleIntent method. Here is sample code.

public class IntentServiceExample extends IntentService {

	public IntentServiceExample(){
		super("IntentServiceExample");
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		//do something every 5 seconds
		while(true){
			try{
				Thread.sleep(5000);
			} catch(Exception e){

			}
		}
	}

}

IntentService create a new worker thread to do the task specified in onHandlerIntent. I don't fully understand how android systems supoorts this. All you have to remember is that onHandleIntent runs in the worker thread, not the main UI thread. The reason is simple, long running task being stuck in the main thread will slow down the the UI interactions and therefore increases the chance of getting ANR (Application Not Responding errors).

In such kind of service, we usually want to notify the user that somethings have been done. I prefer to use Toast although that using notification bar might be more often in background services. However, if you directly post a Toast inside onHandleIntent, the Toast won't show. As I mentioned before, the onHandleIntent runs in the worker thread, which has nothing to do with UI. If you want to post a Toast, you should do it in the main UI thread. How? Here is the trick to do so.

Since onCreate runs in main thread, we obtain a Handler from it and then post our Toast to the main thread through the handler. Below is the sample code.

public class IntentServiceExample extends IntentService {
	private Handler h;
	
	public IntentServiceExample(){
		super("IntentServiceExample");
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Toast.makeText(getApplicationContext(), "hello service", Toast.LENGTH_SHORT).show();
		h=new Handler();
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		while(true){
			try{
				Thread.sleep(5000);
				h.post(new Runnable() {
					
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), "handling...", Toast.LENGTH_SHORT).show();
					}
				});
			} catch(Exception e){
				
			}
		}
	}
}
Now we successfully walk around this issue.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值