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 UI interactions and therefore increases the chance of getting ANR (application not responding errors ).
In such kind of service, we usually want to sort y 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.