在Application的onCreate中启动一个服务

发布于 2024-12-20 08:16:48 字数 539 浏览 2 评论 0原文

我试图在我的应用程序启动时启动一项服务,并且我需要重新启动服务,以防用户决定强制关闭服务,即使应用程序正在运行(没关系,他可以强制关闭应用程序,但是我需要防止在应用程序运行时关闭服务)。

所以我开始扩展应用程序类,这就是我正在做的启动服务...

ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d("start","ok");
        }

        public void onServiceDisconnected(ComponentName className) {
        }
    };
    bindService(new Intent(this,DueService.class), conn, 0);

但是,这不会启动服务。不过,使用 startService 似乎可行。有什么想法吗?

I am trying to start a service when my app begins, and I need it the service to restart, incase a user decides to force close the service, even though the app is running(its ok, for him to force close the app, but i need to prevent closing of service while the app is running).

So i went about extending the Application class, and this is what I am doing to start the service...

ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            Log.d("start","ok");
        }

        public void onServiceDisconnected(ComponentName className) {
        }
    };
    bindService(new Intent(this,DueService.class), conn, 0);

This, however, does not start the service. Though, using startService seems to work. Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

番薯 2024-12-27 08:16:48

Application 使用 bindService() 是没有意义的,因为您永远无法调用 unbindService()

当然,最好的情况是您的服务仅在主动为用户提供价值时才位于内存中,而不仅仅是因为应用程序的某些其他组件恰好被加载。就目前情况而言,如果您继续从 Application 使用 startService() 的计划,那么您将走上一条泄漏此服务的道路。 Android 中不存在将“应用程序正在运行”作为生命周期构造的真正概念,因此您没有合理的时间来停止服务。

(顺便说一句,虽然 Application 有一个 onTerminate() 方法,但它永远不会被调用)

Using bindService() from an Application is pointless, as you will never be able to call unbindService().

Best, of course, would be for your service to only be in memory if it is actively delivering value to the user, instead of just because some other component of your app happens to be loaded. As it stands, you are headed down a path towards leaking this service, if you go with your plan of using startService() from the Application. There is no real concept in Android of "the app is running" as a lifecycle construct, so you will not have a logical time to stop the service.

(BTW, while Application has an onTerminate() method, it will never be called)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文