繁体   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