gpt4 book ai didi

Android:如何强制在 onBind() 之前调用 onStartCommand()?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:36 25 4
gpt4 key购买 nike

我正在尝试创建一个可绑定(bind)的粘性服务(我需要在后台对该服务持有的某些数据运行潜在的异步操作)。为此,我需要确保 onBind 始终在 onStartCommand 之后运行。有什么办法可以保证这一点?

最佳答案

根据您的要求,您可能不需要绑定(bind)到您的服务。然后使用 IntentService就足够了,因为该服务将在其工作完成后自行停止。

取自文档:

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

IntentService 示例:

public class MyService extends IntentService {

@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
// Do some work here, get Intent extras if any, etc.
// ...
// Once this method ends, the IntentService will stop itself.
}
}
}

可以找到有关如何创建 IntentService 的更多信息 here .

可以处理您的异步操作。如果您需要任何反馈,这将“破坏”要求的异步部分,您可以使用 LocalBroadcastManager或者如您所说,您可以绑定(bind)到此 Service .再一次,这取决于您要做什么。

根据文档,您有两种类型的服务。

开始

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

绑定(bind)

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

提醒:您可以通过startService()启动一个Service,使其“无限期”运行,并通过调用绑定(bind)到它>onBind() 稍后。

Intent it = new Intent(this, MyService.class);
startService(it); // Start the service.
bindService(it, this, 0); // Bind to it.

如果您只想在 Activity 运行时运行此服务,您可以调用 onBind()

Intent it = new Intent(this, MyService.class);
bindService(it, this, 0); // This will create the service and bind to it.

有关“默认”服务 的更多信息,可以找到如何使用和实现它here .

只需选择最适合您的用例的内容,您就可以开始了。

关于Android:如何强制在 onBind() 之前调用 onStartCommand()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17384490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com