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

查看:28
本文介绍了如何知道我的应用程序是在前台还是后台,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.

开始运行任务

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

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()

Then to check the state at runtime call MyApplication().isActivityVisible()

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

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