简体   繁体   English

如何检测Android应用程序何时最小化?

[英]How to detect when an Android application is minimized?

How to detect when an Android app goes to the background? 如何检测Android应用程序何时进入后台? onPause() or onUserLeaveHint() works but are also called when the orientation is changed or another activity is presented. onPause()或onUserLeaveHint()可以工作,但在更改方向或显示其他活动时也会调用它。

If orientation changes the app will call through the life cycle once again that means from oncreate 如果方向改变,应用程序将再次调用生命周期,这意味着从oncreate

you can avoid it as well by writing the following to code to the manifest 您可以通过将以下内容写入清单的代码来避免它

 <activity
      android:name=""
      android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
      android:label="@string/app_name" />

this tell the system that when orientation changes or keyboardHidden or screenLayout changes I will handle it by myself no need to re create it. 这告诉系统当方向改变或者keyboardHidden或screenLayout改变时,我将自己处理它,无需重新创建它。

then write your code on on pause 然后在暂停时编写代码

Try this 试试这个

 @Override
    protected void onUserLeaveHint() 
   { 
        // When user presses home page
        Log.v(TAG, "Home Button Pressed");
        super.onUserLeaveHint();
    }

For detail : https://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint() 有关详细信息: https//developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()

The marked answer is a workaround for the OP's question. 明确的答案是OP问题的解决方法。 For the rest of us that are looking for an answer you can achieve this using Android Architecture Components 对于寻求答案的我们其他人,您可以使用Android架构组件实现这一目标

import android.arch.lifecycle.LifecycleObserver;

class OurApplication extends Application implements LifecycleObserver {

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

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        Logger.localLog("APP BACKGROUNDED");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        Logger.localLog("APP FOREGROUNDED");
    }
}

and remember to update the manifest file. 并记得更新清单文件。 set the android:name=".OurApplication" attribute for the <application> tag <application>标签设置android:name=".OurApplication"属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM