簡體   English   中英

Android-檢測應用移至背景和前景

[英]Android - Detect app moving to background and foreground

如果應用程序退到后台並在5分鍾后返回,則需要重新啟動應用程序。 我們可以離開重啟部分,如何檢測應用程序移到后台和前台? 請幫忙。

如果有其官方不可能或可能性的詳細信息的鏈接,請分享。

當它移到后台時,它執行onPause() ,當它恢復到后台時,它執行onResume() ,請參見活動生命周期。

http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

我有一個類似的問題,每次應用程序從后台片段B返回時,都會根據活動中片段A的輸出重新計算結果(片段A根據用戶輸入將數據發送到片段B)。 以下解決方案使用簡單的布爾檢查,應可用於大多數目的。 這使我即使在遠離應用程序很長時間后仍可以保留舊的FragmentB結果(假設FragmentB中的結果不是很耗內存,因此Android在一段時間后會清除它們)。

//Code from Fragment B
public class FragmentB extends Fragment {
    Boolean app_was_in_background;
    @Override public void onPause() {
        super.onPause();
        app_was_in_background = true;
    }
    @Override public void onResume() {
        super.onResume();
        if (getArguments() != null) {
            String output_to_FragmentB = getArguments().getString("input_from_FragmentA");

            if (app_was_in_background == null || !app_was_in_background) {
                app_was_in_background = false;

                PerformMyAlgorithm(output_to_FragmentB);
            }
        }
    }
    public void PerformMyAlgorithm(String input) {
        //Code that includes Spinners and calculations, where I want to app
        //to return to the user's chosen spinner location and display
        //results as the user saw them before switching to another app
        //on the device. All this without explicitly "saving" the Spinner 
        //position and data in memory.
    }
}

附帶說明一下,將相同的邏輯應用於onStart() 而不是 onResume()可能會導致不良結果:

PerformMyAlgorithm再次在onResume()上自動再次接收FragmentA輸出(即,字符串output_to_FragmentB), 用戶沒有選擇通過單擊FragmentA中的按鈕選擇接收(我猜測這是由於Android管理Fragment生命周期的方式)。

我不希望這樣,因為從后台(即onResume)返回時,FragmentB視圖和計算將被重置並重新顯示/重新計算,而不是在將應用程序發送至后台(即onPause)之前立即向用戶顯示結果。

覆蓋每個Activity中的onStop() 當活動進入后台時,將調用此方法。 然后記下時間。

覆蓋onStart() 當活動從后台移動到前台時,將調用此方法。 然后在這里記下時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM