Getting data from an Unbound Service in Android

2019-05-06 02:57发布

I currently I have an unbound service that is running continually grabbing my gps position that I start on boot. I then have an app that is suppose to plot where I've been by pulling data from the service.

I can't bind the the service to talk to it or it will be destroyed once I close the app.

Is there any good way to get data from an unbound service or keep a bound service from dying once I unbind it?

Cheers! :)

2条回答
冷血范
2楼-- · 2019-05-06 03:38

There is a workaround for keeping your service alive. Call your service by calling startService and then bind to the service. This way your activity is maintaining the the lifecycle of the service.

查看更多
3楼-- · 2019-05-06 03:40

As the documentation states:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections

So first, start the service with startService(), then bind to it in onResume(), and unbind in onPause(). The service will continue to run nevertheless because it is started. And when you want to stop the service either call stopSelf() from within the service or stopService() from an activity. It will stop right away or as soon as you unbind from it if there's any connection alive.

查看更多
登录 后发表回答