安卓:检测应用程序是否进入后台

4
似乎这个问题有很多答案,但都不完整。我有一个具有多个活动的应用程序。我所需要的只是一个IF语句,意思是如果我的应用进入了后台,那么我就做这个...如果它回到前台,我就做那个...
!!!请注意,如果我从一个活动切换到另一个活动,也就是说我的第一个活动停止了,这并不意味着我的应用程序已经进入了后台——只是一个活动被另一个活动替换。

请查看此链接 https://dev59.com/LnI95IYBdhLWcg3www2Y#49181737 - Sarthak Mittal
4个回答

3

首先在应用级别的gradle中添加一些必要的依赖项

dependencies {
def lifecycle_version = "2.1.0"

// ViewModel and LiveData
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" // For Kotlin use lifecycle-viewmodel-ktx
// alternatively - just LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData). Some UI
//     AndroidX libraries use this lightweight import for Lifecycle
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version" // For Kotlin use lifecycle-reactivestreams-ktx

// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$lifecycle_version"

}

你可以在这里参考最新的依赖版本。

https://developer.android.com/jetpack/androidx/releases/lifecycle?authuser=1

你的应用程序必须扩展Application类并覆盖以下示例中给出的方法。

您可以使用arch库的生命周期感知组件轻松实现相同的功能。我刚刚发布了一个适用于Kotlin和Java的示例代码,供您使用。

Java版本。

public class YourApp extends Application implements LifecycleObserver {

@Override
public void onCreate() {
    super.onCreate();

    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}

// Application level lifecycle events
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onEnteredForeground() {
    //Timber.d("Application did enter foreground");

}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onEnteredBackground() {
   // Timber.d("Application did enter background");
}

}

Kotlin版本:

class ZumeApp : Application(), LifecycleObserver {

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

// Application level lifecycle events
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onEnteredForeground() {
    Timber.d("Application did enter foreground")

}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onEnteredBackground() {
    Timber.d("Application did enter background")
}
}

我希望这能对你有所帮助。如果无法正常工作,请留下评论或参考Android文档中的以下文章。

https://developer.android.com/topic/libraries/architecture/lifecycle?authuser=1


是的...我知道...但是我之后该如何在我的Activity中使用观察者...检查它是在后台还是前台? - ekashking
然后,一个简单的方法是在您的应用程序类中创建一个易失状态变量,您的应用程序类默认为整个应用程序的单例,在应用程序生命周期更新时更新该易失状态变量。从您的任何活动/片段/对话框中,这些都是您应用程序容器中的组件,您可以像这样访问该状态变量,例如YourApp.state,它返回布尔值或字符串或整数,具体取决于您如何定义它。由于您的应用程序是所有组件的容器,因此该变量始终可从您的组件中使用。这是其中一种不好的做法。 - Farruh Habibullaev
2
@OnLifecycleEvent已被弃用。请参考https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01。 - Akito

1

嘿,我发布了自己的答案。你能否请检查一下它是否是正确的方式?我更关心的是 ProcessLifecycleOwner 是否被支持从 SDK 22 开始及以上的 API。谢谢! - ekashking

1

好的,使用观察器和ProcessLifecycleOwner实现。我在我的片段中得到了这个。状态从ON_PAUSE到ON_RESUME并返回的唯一时间是整个应用程序进入后台并回来时。然后,根据状态(在我的示例中),我将使用后台方法或前台回调获取我的位置。

@Override
public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    setRetainInstance(true);
    //...
    // some other stuff
    //...

    ProcessLifecycleOwner.get().getLifecycle().addObserver(new LifecycleEventObserver() {
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {

            if (event == Lifecycle.Event.ON_PAUSE) {
                Log.e("Lifecycle", "Background");


                getLocationFromBackground();


            } else if (event == Lifecycle.Event.ON_RESUME) {
                Log.e("Lifecycle", "Foreground");

                getLocationFromForeground();
            }
        }
    });

return view;
}

private void getLocationFromBackground() {
    // some code
}


private void getLocationFromForeground() {
    // some code
}

0
  1. Application类由LifecycleObserver实现
  2. 使用静态布尔变量来检查应用程序是在后台还是前台
  3. 使用LifecycleEvent方法检查应用程序的状态
class Application() : LifecycleObserver {

    companion object {
        var isAppInBackground: Boolean = true

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        isAppInBackground = true
        Log.d(TAG, "background")
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        isAppInBackground = false
        Log.d(TAG, "foreground")

    }
} 

嗯...这就是我所说的不完整答案。我已经看到过很多次了。但没有一个逐步实现的。 - ekashking
@OnLifecycleEvent 已被弃用。https://developer.android.com/jetpack/androidx/releases/lifecycle#2.4.0-beta01 - Akito

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接