4

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.

Omar Kohl
  • 1,372
  • 2
  • 15
  • 32

2 Answers2

2

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:

Omar Kohl
  • 1,372
  • 2
  • 15
  • 32
1

You can use a Messenger to pass information between the service and main application.

Define a messenger in your main activity, as follow:

private Messenger = mMessengerCliente = new Messenger(new IncomingHandler());

/**
 * Handler of incoming messages from service.
 */
private class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_1:
                //actions to perform on message type 1
                break;
            case MSG_2:
                //actions to perform on message type 2
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

Pass the Messenger object as a Extra or when binding to your service.

In your service, recover the Messenger object and use it to communicate back:

                mMsgClientMain = (Messenger)intent.getExtras().get(EXTRA_MESSENGER);

                Message msg = Message.obtain(null, MSG_1, arg1, arg2);
                msg.replyTo=reply_to; // if you need to have bidirectional communication, pass here the service messenger object
                mMsgClientMain.send(msg);

Regards.

Luis
  • 11,978
  • 3
  • 27
  • 35