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 ?
ServiceandActivitydo not have the same lifecycle. This means yourServicemay find no instance ofYourActivitywhen callingYourActivity.getInstance(). Your code should resist to that.And as
performAction()is a method ofYourActivity, it would certainly be better to execute it fromYourActivityinstead of executing it from yourService.So you should do as follows I think:
post a
Messagefrom yourServicetoYourActivityusing aHandler(more details on Handler and on Message) instead of making a direct call toYourActivity.performAction()from yourService. You would send this message just before callingService.stopSelf()(more details on stopSelf()) or why not from an override of this method.make
YourActivityable to handle this message and executeperformAction()(you can find examples of how to handle messages here: just Ctrl-F “Handler” in this page). Execute it in a separateThreadto avoid the dreaded “Application Not Responding”.