Creating Toast in IntentService

来源:互联网 发布:js pdf在线阅读 编辑:程序博客网 时间:2024/05/18 00:23

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");}@Overrideprotected void onHandleIntent(Intent arg0) {//do something every 5 secondswhile(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");}@Overridepublic void onCreate() {super.onCreate();Toast.makeText(getApplicationContext(), "hello service", Toast.LENGTH_SHORT).show();h=new Handler();}@Overrideprotected void onHandleIntent(Intent arg0) {while(true){try{Thread.sleep(5000);h.post(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplicationContext(), "handling...", Toast.LENGTH_SHORT).show();}});} catch(Exception e){}}}}
Now we successfully walk around this issue.

原创粉丝点击