在React Native中检测屏幕关闭。

huangapple go评论80阅读模式
英文:

Detect whatever screen off in react native

问题

我正在开发一个应用程序,希望用户保持应用程序处于打开状态,不使用其他应用程序(以帮助他们专注于工作),但允许他们关闭手机屏幕。我使用了AppState API 来检测应用程序是否在后台运行,但当屏幕关闭时也会触发它。所以我需要一种方法来知道屏幕是开启还是关闭的。我尝试了搜索,但找不到任何解决方案。

英文:

I'm making an app which wants the user to keep the app open and not using other apps (to help them focuses on works), but allows them to turn the phone screen off. I used AppState API to detect if the app running in the background but it also triggered when the screen turned off. So I need a way to know if the screen is on or off. I tried googling around but I couldn't find any solution.

答案1

得分: 0

短答案是,没有RN库支持两个平台。例如,你可以在这里找到iOS的解决方案:https://stackoverflow.com/questions/14191980/detect-screen-on-off-from-ios-service/14208787#14208787,并且还有一个RN的封装库react-native-lock-detection

然而,在你的情况下,如果我们知道在屏幕关闭时会接收到第二个事件,我们可以添加一个计数器,当应用程序第一次进入后台时增加该值,如果第二次进入后台,则再次增加该值并添加一些逻辑。如果应用程序重新激活,你可以重置这个值。

英文:

The short answer is that no RN library supports it for both platforms. For example, here you can find a solution for ios https://stackoverflow.com/questions/14191980/detect-screen-on-off-from-ios-service/14208787#14208787 and wrapper for RN react-native-lock-detection

However in your case, if we know that we receive a second event when the screen is off we can add a counter and when the app goes background the first time you increase the value if the second time you increase it again and add some logic. If the app goese active you reset this value.

huangapple
  • 本文由 发表于 2023年1月9日 17:24:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定