I have an Android Service that does some background processing on an image using a separate Thread. If an error occurs in this Service or even worse in the thread, what is the best practice to inform the launching Activity of the problem and allow the application to recover to a stable state (i.e. the state it was in before launching the service).
From within the Service I could post a Toast or a Notification, but that doesn’t help me. I would like to inform the user about the problem but at the same time recover the application to a stable state.
In case anyone searches for this I will explain what I ended up doing.
Inside the service I added a private class that extends AsyncTask. This is were all the processing is done.
In this class I have a private variable ‘exception’. The content of the doInBackground method is surrounded by a try/catch and any exception catched is stored in ‘exception’. In the onPostExecute method I check if ‘exception’ is set and if that is the case I send a broadcast PROCESSING_ERROR with the exception details so that the calling Activity will be informed.
If you don’t know what AsyncTask, doInBackground or onPostExecute are you should read following:
http://developer.android.com/guide/components/processes-and-threads.html#AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html