I assume the problem is not with onTaskRemoved
not being called when you are removing the app from the recent list. I would say, maybe the service that you started was killed before the app went into the recent apps list.
I would like to share an answer here at SO, which tries to describe the problem of foreground services being killed.
Hence, if you run the service as a foreground service as suggested here, you need to do something on a periodic basis to keep the service alive. I assume you should be able to get the onTaskRemoved
called if the service was not killed before.
Suggestions based on your use-case:
As mentioned in the comment of this answer, you want to remove the items from the cart when the user has left the app, to make it available to order for other users.
This is more like a design problem to me which can be done in many ways. I can drop some suggestions, however, my suggestions might not fit in your case.
- Solving it from server-side:
- When a user is adding an item in the cart, store the timestamp value when it was added to the cart, in your server-side database.
- Take a default threshold for the expiry of the cart items. When a new user from another device is trying to access the same item, check the timestamp value and mark that item as available if the time is passed the threshold time.
- Solving it from server-side 2:
- IMHO, an item is always available until the item is checked out/paid. In your implementation, if I can get your API endpoints, I can make a simple scripting attack, so that I can hold the item in my cart without buying it. Hence there is a serious vulnerability in your current implementation which can be exploited easily. I would rather keep the item available in the cart until someone pays for it.
- If you keep the item available to order until someone pays for it, you can check the availability just before making the payment and tell the customer that the item is already sold.
- Solving this from the app side:
- I would say, I could not find a good way to ensure that the API for cart cancellation was called to remove the items from the cart. The solution that I proposed earlier, still might work, however, IMHO, this is overkill.
- If you take the
onTaskRemoved
implementation, you might consider having a timer there as well so that you can also have a threshold value for the items to be removed from the cart, after a certain period of time. Otherwise, you will end up keeping the item unavailable for other users forever (as I stated above).