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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章