Android:活动关闭时服务停止 [英] Android: Service stops when Activity is closed

查看:23
本文介绍了Android:活动关闭时服务停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我理解正确的话,带有 BIND_AUTO_CREATE 的 bindService() 将启动一个服务,并且在所有绑定都解除绑定之前不会终止.

If I understand it correctly, bindService() with BIND_AUTO_CREATE will start a service and will not die until all bindings are all unbinded.

但是如果我在 onCreate() 处 bindService(BIND_AUTO_CREATE) 并点击返回按钮关闭活动,该服务调用 onDestroy() 并终止.

But if I bindService(BIND_AUTO_CREATE) at onCreate() and hit back button to close the activity, the service calls onDestroy() and dies also.

我不会在任何时候调用 unbind().那么这是否意味着当 Activity 被销毁时,绑定也被销毁,服务也被销毁?

I don't call unbind() at anytime. So is that mean when the Activity got destroyed, the binding got destroyed also and the service gets destroyed also?

如果我希望服务在活动开始的同时一直运行怎么办我想绑定它以便我可以访问服务?

What if I want the service to be always running, at the same time when the activity starts I want to bind it so that I can access the service?

如果我在 onCreate() 调用 StartService() 和 bindService(),它将在每次启动 Activity 时重新启动服务.(我不想要的).

If I call StartService() and then bindService() at onCreate(), it will restart the service at every launch of Activity. (Which I don't want).

所以我可以启动一次服务,然后在下次启动活动时绑定吗?

So I could I start service once and then bind next time I launch the activity?

推荐答案

您需要使用 startService 以便在绑定到它的 Activity 被销毁时不会停止服务.

You need to use startService so that the service is not stopped when the activity that binds to it is destroyed.

startService 将确保即使您的 Activity 被破坏,该服务仍在运行(除非它因内存限制而停止).当您调用 startService 时,会在服务上调用 onStart 方法.它不会重新启动(终止并重新启动)服务.所以这取决于你如何在 Service 上实现 onStart 方法.但是,服务的 onCreate 只调用一次,因此您可能需要在那里初始化.

startService will make sure that the service is running even if your activity is destroyed (unless it is stopped because of memory constraints). When you call startService, the onStart method is called on the service. It doesn't restart (terminate and start again) the service. So it depends on how you implement the onStart method on the Service. The Service's onCreate, however, is only called once, so you may want to initialize things there.

这篇关于Android:活动关闭时服务停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆