[英]How to detect if android application is minimized or not in Android Kotlin
我想使用 Kotlin 檢測我的應用程序是否已最小化(我的意思是按下主頁按鈕)。請注意,我不是在談論任何特定的活動或片段,我的意思是整個應用程序。 我需要為應用程序假設三個單獨的 state:在視口中顯示、最小化和完全關閉。 我應該如何檢測前兩個狀態? 如果 android 生命周期可以做到這一點,請描述如何。 謝謝!
如果按下應用程序主頁按鈕,您可以在Application
中檢查LifecycleObserver
inner class ApplicationObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun onPause() {
}
}
要檢測何時使用滑動並終止您的應用程序,您可以使用服務和您
並注冊它
ProcessLifecycleOwner
.get()
.lifecycle
.addObserver(ApplicationObserver())
或者覆蓋 Activity 的 onUserLeaveHint 方法,該方法在按下主頁按鈕時運行。
/**
* Called as part of the activity lifecycle when an activity is about to go
* into the background as the result of user choice. For example, when the
* user presses the Home key, {@link #onUserLeaveHint} will be called, but
* when an incoming phone call causes the in-call Activity to be automatically
* brought to the foreground, {@link #onUserLeaveHint} will not be called on
* the activity being interrupted. In cases when it is invoked, this method
* is called right before the activity's {@link #onPause} callback.
*
* <p>This callback and {@link #onUserInteraction} are intended to help
* activities manage status bar notifications intelligently; specifically,
* for helping activities determine the proper time to cancel a notification.
*
* @see #onUserInteraction()
* @see android.content.Intent#FLAG_ACTIVITY_NO_USER_ACTION
*/
protected void onUserLeaveHint() {
}
要檢測用戶何時向右滑動並完成您的應用程序,您可以使用Service
並覆蓋
override fun onTaskRemoved(rootIntent: Intent?) {
super.onTaskRemoved(rootIntent)
setRestartAppAlarm()
}
我們將此方法用於展示應用程序,該應用程序需要始終運行。 當商店里的顧客關閉應用程序時,我們會設置一個警報並重新啟動它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.