如何检测 Android 应用程序何时最小化?
How to detect when an Android application is minimized?
如何检测 Android 应用何时进入后台?
onPause() 或 onUserLeaveHint() 有效,但在方向改变或出现另一个 activity 时也会被调用。
试试这个
@Override
protected void onUserLeaveHint()
{
// When user presses home page
Log.v(TAG, "Home Button Pressed");
super.onUserLeaveHint();
}
详情:https://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()
如果方向改变,应用程序将再次调用整个生命周期,这意味着从 oncreate
您也可以通过将以下代码写入清单来避免它
<activity
android:name=""
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:label="@string/app_name" />
这告诉系统,当方向改变或keyboardHidden或screenLayout改变时,我会自己处理,不需要重新创建它。
然后在暂停时编写代码
标记的答案是 OP 问题的解决方法。
对于我们其他正在寻找答案的人,您可以使用 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");
}
}
并记得更新清单文件。为 <application>
标签
设置 android:name=".OurApplication"
属性
如何检测 Android 应用何时进入后台? onPause() 或 onUserLeaveHint() 有效,但在方向改变或出现另一个 activity 时也会被调用。
试试这个
@Override
protected void onUserLeaveHint()
{
// When user presses home page
Log.v(TAG, "Home Button Pressed");
super.onUserLeaveHint();
}
详情:https://developer.android.com/reference/android/app/Activity.html#onUserLeaveHint()
如果方向改变,应用程序将再次调用整个生命周期,这意味着从 oncreate
您也可以通过将以下代码写入清单来避免它
<activity
android:name=""
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:label="@string/app_name" />
这告诉系统,当方向改变或keyboardHidden或screenLayout改变时,我会自己处理,不需要重新创建它。
然后在暂停时编写代码
标记的答案是 OP 问题的解决方法。 对于我们其他正在寻找答案的人,您可以使用 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");
}
}
并记得更新清单文件。为 <application>
标签
android:name=".OurApplication"
属性