[英]Stop IntentService when user goes back to home screen in multi-activity app
My Android application exists of a main activity in which the user has the ability to start several other activities. 我的Android应用程序存在一个主要活动,其中用户可以启动其他几个活动。 In order to have a permanently working keyword recognition (speech recognition), I use an
IntentService
that is started in the onCreate()
of the main activity. 为了拥有永久有效的关键字识别(语音识别),我使用了在主要活动的
onCreate()
中启动的IntentService
。 The service needs to be working as long as any activity of the app is in the foreground. 只要应用程序的任何活动都在前台,该服务就必须正常运行。
However, this service uses the microphone all the time, so it's desirable to stop the service once the user returns to his/her home screen. 但是,此服务始终使用麦克风,因此,一旦用户返回其主屏幕,则最好停止该服务。 I know the basics about activity lifecycles, but my question is: what is the best way to stop the IntentService when the user returns to the home screen from any activity?
我知道有关活动生命周期的基础知识,但是我的问题是: 当用户从任何活动返回到主屏幕时,停止IntentService的最佳方法是什么?
To restart the service when the app is re-opened, I was thinking of a superclass that all activities inherit from. 要在重新打开应用程序时重新启动服务,我想到了所有活动都继承自的超类。 In the superclass I would set a static boolean
serviceStopped
that is set to true when the user goes to his/her home screen (and the service is stopped). 在超类中,我将设置一个静态布尔值
serviceStopped
,当用户转到其主屏幕时(该服务已停止),该值设置为true。 In the onResume()
method, this boolean will be checked and the service will be restarted if needed. 在
onResume()
方法中,将检查此布尔值,并在需要时重新启动服务。
As I know there is no way to detect if the user leave your application and is in the home screen. 据我所知,无法检测到用户是否离开了您的应用程序并处于主屏幕。
I think there is no a simple way to detect if your application is open/closed; 我认为没有简单的方法可以检测您的应用程序是否打开/关闭; however I found this How to get the list of running applications?
但是我发现了这个如何获取正在运行的应用程序的列表? and I think it could help you.
而且我认为它可以为您提供帮助。
You could also try to start a Service in the background and check when any of your activities start or is destroyed. 您也可以尝试在后台启动服务,并检查任何活动何时开始或被破坏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.