如何知道我的应用程序是在前台还是在后台,android? [英] How to know if my application is in foreground or background, android?

查看:294
本文介绍了如何知道我的应用程序是在前台还是在后台,android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查我的应用程序是在后台运行还是在前台运行,然后相对于它执行一些操作.

I need to check if my application is running in background or foreground and then perform some operations relatively to it.

我进行了很多搜索,没有明确的解决方案.

I searched a lot and a clear solution is not available.

  1. 在其onPause()和onResume()方法中进行父活动,以保留一些变量以相应地更新它们.当您创建任何新活动时,请继承您的父活动. 虽然这是实现任务的最佳解决方案,但是有时即使在应用程序处于后台时单击电源按钮,也会调用onResume().

  1. Make a parent activity in its onPause() and onResume() methods keep some variable to update them accordingly. When you create any new activity inherit your parent activity. Although this is the best solution I feel to achieve my task, but sometimes if the power button is clicked even though application is in background, it's onResume() is invoked.

使用GETTASKS权限-此解决方案也很好.但是它只能用于调试目的.如果您想将您的应用程序放到Google Play商店中,则不会.

Use GETTASKS permission - This solution is also good. But it can only used for debug purpose. Not if you want to put your app on Google Play Store.

开始运行Taks

还有其他首选的解决方案吗?

Any other preferred solution for this?

推荐答案

原始答案: https://stackoverflow.com/a/60212452/10004454 根据Android文档的推荐方法是

Original Answer : https://stackoverflow.com/a/60212452/10004454 The recommended way to do it in accordance with Android documentation is

class MyApplication : Application(), LifecycleObserver {

override fun onCreate() {
    super.onCreate()
    ProcessLifecycleOwner.get().lifecycle.addObserver(this);
}

fun isActivityVisible(): String {
    return ProcessLifecycleOwner.get().lifecycle.currentState.name
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
    //App in background

    Log.e(TAG, "************* backgrounded")
    Log.e(TAG, "************* ${isActivityVisible()}")
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {

    Log.e(TAG, "************* foregrounded")
    Log.e(TAG, "************* ${isActivityVisible()}")
    // App in foreground
}}

在gradle(应用程序)中添加:implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

In your gradle (app) add : implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

然后在运行时调用MyApplication().isActivityVisible()

这篇关于如何知道我的应用程序是在前台还是在后台,android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆