如何检测应用何时最小化或退出 [英] How to detect when the app goes to minimized or exit

查看:114
本文介绍了如何检测应用何时最小化或退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有一个应用程序现在要在APP转到onPause或onDestroy时使用,因为我想在发生这种情况时调用某个函数。
我试图在一个活动中覆盖onPause并在所有项目中扩展该活动,但是活动之间的每次迁移都调用了onPause(这是合乎逻辑的),但这不是我想要的。
我想知道用户何时退出或暂停应用程序(按主页按钮)
致谢,

Hey I have an application where I want to now when the APP goes to onPause or onDestroy because I want to call a certain function when this happens. I tried to override the onPause in an activity and extended that activity in all project but the onPause was being called on every migration between activities (which is logical) but this is not what I want. I want to know when the user exits the app or pauses it (pressing the home button) Regards,

推荐答案


将此依赖项拉到build.gradle文件中:

Pull this dependency in your build.gradle file:



dependencies {
implementation "android.arch.lifecycle:extensions:1.1.1"
}




然后在您的Application类中,使用此命令:

Then in your Application class, use this:



public class MyApplication extends Application implements LifecycleObserver {

@Override
public void onCreate() {
    super.onCreate();
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private void onAppBackgrounded() {
    Log.d("MyApp", "App in background");
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
private void onAppForegrounded() {
    Log.d("MyApp", "App in foreground");
}
}




更新您的AndroidManifest。 xml文件:

Update your AndroidManifest.xml file:



<application
    android:name=".MyApplication"
    ....>
</application>

这篇关于如何检测应用何时最小化或退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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