就是让app中所有的activity继承与一个公共的activity(例如:BaseActivity),然后在BaseActivity的onStop()中判断当前程序是否处于后台
代码片段
[java] view plaincopyprint?
01./**
02. * 文件名:BaseActivity.java
03. * 版本号:
04. * 日期:2012-6-20
05. * 创建人:
06. * Copyright wadata 版权所有
07. * 变更:
08. */
09.
10.package com.wadata.mobilefollowup.view.base;
11.
12.import java.util.List;
13.import android.app.Activity;
14.import android.app.ActivityManager;
15.import android.app.ActivityManager.RunningAppProcessInfo;
16.import android.content.Context;
17.
18./**
19. * 名称:BaseActivity
20. * 描述:
21. * 创建人:
22. * 日期:2012-6-20 下午5:53:35
23. * 变更:
24. */
25.
26.public class BaseActivity extends Activity {
27. @Override
28. protected void onStop() {
29. // TODO Auto-generated method stub
30. super.onStop();
31.
32. if (!isAppOnForeground()) {
33. //app 进入后台
34.
35. //全局变量isActive = false 记录当前已经进入后台
36. }
37. }
38.
39. @Override
40. protected void onResume() {
41. // TODO Auto-generated method stub
42. super.onResume();
43.
44.
45. //if (!isActive) {
46. //app 从后台唤醒,进入前台
47.
48. //isActive = true;
49. //}
50. }
51.
52. /**
53. * 程序是否在前台运行
54. *
55. * @return
56. */
57. public boolean isAppOnForeground() {
58. // Returns a list of application processes that are running on the
59. // device
60.
61. ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
62. String packageName = getApplicationContext().getPackageName();
63.
64. List
65. .getRunningAppProcesses();
66. if (appProcesses == null)
67. return false;
68.
69. for (RunningAppProcessInfo appProcess : appProcesses) {
70. // The name of the process that this object is associated with.
71. if (appProcess.processName.equals(packageName)
72. && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
73. return true;
74. }
75. }
76.
77. return false;
78. }
79.}
这样更方便简洁 http://blog.csdn.net/lin_dianwei/article/details/79213732