本文主要是介绍Android判断应用程序处于前台还后台,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
转自 http://blog.csdn.net/zansl/article/details/39398615
/** * 判断当前应用程序处于前台还是后台 */ public static boolean isApplicationBroughtToBackground(final Context context) { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
继承Activity的,重写Activity的onStop方法,代码如下:
public class BaseActivity extends Activity { @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); boolean b = Utils.isApplicationBroughtToBackground(this); if (b) { Toast.makeText(this, "当前应用处于后台", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "当前应用处于前台", Toast.LENGTH_SHORT).show(); } } }
后面的所有Activity全部继承BaseActivity,在这些activity中重写on Resume方法,在onResume中判断app是否从后台切换到前台,
@Override protected void onResume() { super.onResume(); /** * 用静态变量isApplicationBroughtToBackground 保存onStop中判断的是否处于后台的结果 */ if (C.isApplicationBroughtToBackground) { Toast.makeText(this, "从后台切换回前台", Toast.LENGTH_SHORT).show(); C.isApplicationBroughtToBackground = false; }
这篇关于Android判断应用程序处于前台还后台的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!