绑定从Android活动服务 [英] Bind to service from android activity

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

问题描述

我有一个启动的服务一个活动。当活动被关闭,我希望服务继续在后台运行。我有几个问题在这里。

I have an Activity that starts a service. When the activity is closed, I want the service to continue running in the background. I have a couple of questions here.

将关闭活动的屏幕使活动真正停止?或者,我需要强制停止它导致其停止?

Will closing the activity screen cause the activity to actually stop? Or do I need to forcibly stop it to cause it to stop?

如果关闭屏幕并导致其停止,那么我想我需要使用 startService 来启动它。那是对的吗?如果是这样的话,有没有办法得到一个处理正在运行的服务下一个活动开始时间呢?如果不是的话,那么我可以绑定到服务。

If closing the screen does cause it to stop, then I assume I need to use startService to start it. Is that correct? If that is the case, is there a way to get a handle to the running service next time the activity starts? If it is not the case, then I can just bind to the service.

推荐答案

在你的活动不再可见在屏幕上,它被停止。停止一个活动绑定到服务不会停止服务。不过,你要确保你从服务当你的活动通话解除的onDestroy(),以确保你没有悬挂任何处理程序和类似的东西。

When your Activity is no longer visible on the screen, it is stopped. Stopping an Activity bound to a Service does not stop the Service. However, you'll want to make sure you unbind from the Service when your Activity calls onDestroy() to make sure you don't have any dangling handlers and suchlike.

您可以重新绑定到正在运行的服务像你一样在第一时间以同样的方式。发送意图来启动服务这已经运行,则不会创建它的第二个实例,所以这是安全的。

You can rebind to a running Service the same way as you did the first time. Sending an Intent to start a Service that's already running doesn't create a second instance of it, so that's safe.

一个很好的方式开始新的服务像你描述的是使用启动它的 Context.BIND_AUTO_CREATE 参数您的来电 bindService()

A good way to start a Service like you're describing is to start it using the Context.BIND_AUTO_CREATE argument to your call to bindService().

这一切的细节可以在href=\"http://developer.android.com/guide/topics/fundamentals/bound-services.html\" rel=\"nofollow\">关于Android文档的的。它可以在第一有点混乱。按照教程code密切,因为它听起来像你的问题以及映射到他们所提供的样本。

The details of all of this can be found at the Android docs about bound services. It can be a little confusing at first. Follow the tutorial code closely since it sounds like your problem maps well onto the sample they provide.

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

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