所谓后台,我的意思是应用程序的活动目前对用户都不可见?


当前回答

Idolon的答案是容易出错的,更复杂的,尽管在这里重复检查android应用程序是在前台或不是?从后台任务或服务中确定当前的前台应用程序

有一个更简单的方法:

在所有活动扩展的BaseActivity上:

protected static boolean isVisible = false;

 @Override
 public void onResume()
 {
     super.onResume();
     setVisible(true);
 }


 @Override
 public void onPause()
 {
     super.onPause();
     setVisible(false);
 }

无论何时你需要检查你的应用程序活动是否在前台,只需检查isVisible();

要理解这种方法,请检查side-by-side活动生命周期的答案:activity side-by-side生命周期

其他回答

在我的onResume和onPause活动中,我写了一个isVisible布尔值给sharedpreferences。

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = sharedPrefs.edit();
    editor.putBoolean("visible", false);
    editor.commit();

如有需要可在其他地方阅读,

    // Show a Toast Notification if App is not visible (ie in background. Not running, etc) 
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    if(!sharedPrefs.getBoolean("visible", true)){...}

也许不优雅,但对我来说很管用……

根据CommonsWare和Key所说的,你可以扩展Application类,并让你所有的活动在onPause/onResume方法上调用它。这将允许您知道哪些活动是可见的,但这可能会得到更好的处理。

你能详细说明一下你的想法吗?当你说在后台运行,你的意思是简单地让你的应用程序仍然在内存中,即使它目前不在屏幕上?你有没有考虑过使用服务作为一种更持久的方式来管理你的应用程序,当它不在焦点?

使用getApplicationState().isInForeground()怎么样?

简单直接的回答:

override fun onPause() {
    Log.i("APP LIFECYCLE", "App Enter BACKground")
    isForeground = false
    super.onPause()
}

override fun onResume() {
    Log.i("APP LIFECYCLE", "App Enter FOREground")
    isForeground = true
    super.onResume()
}

然后只需使用您的活动的isForeground属性来检查状态。

除非你自己跟踪它,否则无法确定你的任何活动是否可见。也许你应该考虑问一个新的StackOverflow问题,解释一下你想从用户体验中获得什么,这样我们也许可以给你其他的实现想法。