gpt4 book ai didi

android - 多次启动服务会在onStartCommand()中嵌套调用吗?

转载 作者:行者123 更新时间:2023-11-29 01:31:22 24 4
gpt4 key购买 nike

我在类里面多次调用 startService()

在我的服务的 onStartCommand() 中有一个函数,就像这样 -

    Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(StaticValues.TAG, "service started.");
processItem();
return 0;
}

我的问题是,如果我再次启动服务,onStartComamnd() 将再次被调用。那么这个调用会等到我之前的调用结束,还是会同时执行对 processItem() 的两个调用?

编辑:我从评论中的链接找到的答案

startService() is asynchronous. So while you are looping the calls, the service itself hasn't gotten any resources and didn't start yet.

The Service will only run in one instance. However, everytime you start the service, the onStartCommand() method is called.

检查:What happens if a Service is started multiple times?

最佳答案

服务只能启动一次,如果您想要并喜欢使用 bool 标志使事情复杂化

使用 startService() 覆盖由 bindService(Intent, ServiceConnection, int) 管理的默认服务生命周期:它要求服务保持运行直到 stopService(Intent) 被调用,无论是否有任何客户端连接到它。请注意,对 startService() 的调用不是嵌套的:无论您调用多少次 startService(),对 stopService(Intent) 的一次调用> 会阻止它。

If the service is being started or is already running, the ComponentName of the actual service that was started is returned; else if the service does not exist null is returned.

Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called;

Link to the Docs

Life Cycle of a Service

关于android - 多次启动服务会在onStartCommand()中嵌套调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31025092/

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