gpt4 book ai didi

Android bindService 或/和 startService

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:23 33 4
gpt4 key购买 nike

我想使用 bindService 方法创建服务。但是当我关闭一个 Activity 时,我的服务被破坏了,我不希望这样。

我尝试使用 startForeground(NOTIFICATION_ID, notification); service onCreate 将服务置于前台,但服务仍然被破坏。

现在我尝试调用两种方法同时启动服务:

    Intent bindIntent= new Intent(this, ServiceC.class);
startService(bindIntent);
bindService(bindIntent, onService, BIND_AUTO_CREATE);

通过调用这两个方法Service没有被销毁。我的应用程序使用这种方法运行良好。

有人可以向我解释这是否是一个好方法,如果不是,请告诉我为什么 startForeground(NOTIFICATION_ID, notification); 不起作用?

使用 bindService 的最佳方式是什么,但同时我不希望该服务自行销毁。

最佳答案

我使用了相同的解决方案,这是一个合法的解决方案。来自 Service引用:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated.

startForeground() 不起作用,因为它只是试图防止服务被系统杀死,但它的生命周期是另一回事:如果没有什么更绑定(bind)到该服务并且它不是'它开始了,它就停止了。

关于Android bindService 或/和 startService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689460/

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