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

标签 android service

我在类里面多次调用 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/

相关文章:

grails - 更改grails中注入(inject)服务的名称

java - 使用键值对解析字符串响应并将它们添加到映射或数组中

java - 如何显示内部存储器中所有音频文件的列表

java - 使用 LibVLC for android 创建视频播放器

file - 网盘的 Camel 文件组件

c# - 调用服务电话的良好做法

c# - Windows 7 操作系统中的服务不使用主机文件作为本地服务

java - 在 android 中更改 ImageView 的位图图像

android - 如何在 Android 的 QuickAction 对话框中添加 Listview

android - 是否有可能在Android中连续检测外部声音?