简体   繁体   中英

Service still bound to main activity when pressing home button, when viewing different activity

Ok, so the application I've written has a service (that tracks GPS data) with a single main activity that binds to it with bindService in it's onStart() method, and unbinds from the service in it's onStop() method using unbindService(ServiceConnection) .

I also have an activity which is an options screen, that is launched by pressing a button on the main activity. On this options screen, I have a checkbox that says "Run in background", which, if set to true, means that when the user exits the application with either the Home or Back buttons, the service will continue running, not turning the GPS off.

I do this by calling this.startForeground onUnbind , and this.stopForeground onRebind , if the setting is set to true, and stopping and starting my location reader onUnbind and onRebind respectively if the setting is false.

If the service is running in the background, it also displays a notification to ensure the user understands that the GPS is still running and draining their power. This notification is displayed and stopped by relying on the startForeground and stopForeground methods.

So, the problem lies in the fact that whether or not this setting is true, if I'm viewing the options screen, I want the service to keep going, and I do not want that notification to appear. So I set a flag that is set to true if I've hit the button to go to the options screen, and do not call unbindService if the flag is true.

This works, except for one slight problem. If the user hits the home button while viewing the options screen, the service is not stopped if it is supposed to be (because it's still bound to the main screen), and if it is supposed to keep running, it does not display the warning notification (and of course, this means that the service is still considered to be in the background).

How should I go about getting this application to behave the way I want it to?

Ok, so I just found a solution that seems to work. I bind the options screen to the service in the activity's onStart() method, and unbind it again in onStop(). The previous activity's onStop() method isn't called until after the new one's onResume() method, so it works.

Does anyone have a better way though? It seems silly to bind an activity to a service that it doesn't actually need access to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM