1

I am developing an application where I start a background service and I want my main activity to perform a certain action when the service stops

I tried this in my service

public void onDestroy() {
    myActivity.getInstance().performAction();
}

however this causes timeout service exception as the service doesn't stop except when this action is completed and this action takes a lot of time

how can I get around that . Any suggestions ?

htc
  • 125
  • 2
  • 5

3 Answers3

1

Service and Activity do not have the same lifecycle. This means your Service may find no instance of YourActivity when calling YourActivity.getInstance(). Your code should resist to that.

And as performAction() is a method of YourActivity, it would certainly be better to execute it from YourActivity instead of executing it from your Service.

So you should do as follows I think:

  • post a Message from your Service to YourActivity using a Handler (more details on Handler and on Message) instead of making a direct call to YourActivity.performAction() from your Service. You would send this message just before calling Service.stopSelf() (more details on stopSelf()) or why not from an override of this method.

  • make YourActivity able to handle this message and execute performAction() (you can find examples of how to handle messages here: just Ctrl-F "Handler" in this page). Execute it in a separate Thread to avoid the dreaded "Application Not Responding".

Shlublu
  • 10,917
  • 4
  • 51
  • 70
0

Any action that takes a lot of time needs separated thread. You can look at AsyncTask, Thread, HandlerThread for solution. AsyncTask is probably the best option, since it executes code in own thread. After AsyncTask is finished, callback is called from GUI thread.

Salw
  • 1,880
  • 17
  • 22
0

Normally Notifications are used to retrieve the Status from a service.

There are some Threads which might interest you:

Sending a notification from a service in Android

or:

Notify activity from service

See also the examples in:

http://developer.android.com/reference/android/app/Service.html

Community
  • 1
  • 1
Dyonisos
  • 3,541
  • 2
  • 22
  • 25