且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 android 应用程序关闭后使用侦听器

更新时间:2023-01-12 08:47:16

在关闭 Android 应用程序后使用侦听器

Using a listener after an android application is closed

您可以在 android 应用程序关闭后使用侦听器,但不删除它.使用侦听器后,您还需要将其删除 根据您活动的生命周期.但这只会在一段时间内起作用,因为如果应用程序不在前台,Android 将停止您的服务.它这样做是为了在不使用应用程序时节省资源.它也可能会阻止您的应用程序进行任何网络连接,甚至完全终止应用程序进程.正如您已经提到的,除了将其设为前台服务之外,您无法阻止这种情况发生.

You can use a listener after an android application is closed, by not removing it. Once you are using a listener, you also need to remove it according to the life-cycle of your activity. But this will work only for a shot period of time because Android will stop your service if the app is not in the foreground. It does this to save resources when the app isn't being used. It also might stop your app from doing any networking, or even kill the app process completely. There's nothing you can do to prevent this, other than making it a foreground service, as you already mentioned.

前台服务可能不是最适合您的案例,也不是最适合您的用户的方式.详细了解后台服务限制.

A foreground service is probably not the best thing to do for your case, nor is it the best thing for your users. Read more about limitations on background services.

我的建议是使用 Firebase Cloud Messaging 来通知您的应用已更改它可能感兴趣的内容.因此,您的用户即使关闭应用也会收到通知.

My recommendation is to use Firebase Cloud Messaging to notify your app when something has changed that it might be interested in. So your users will recieve notification even if they will keep their app closed.