Android移动应用开发中常见的经验技巧总结

转:http://wwwdevstorecn/essay/essayInfo/6128.html

1. 对话保持的解决方案。

要求:

1、app中使用webview访问具体网站的内容,但是app与服务器的沟通是使用HttpUrlConnection来完成。

2、webview访问时不需要再次登陆,继承app的登陆状态。

会话未保持的现象:

1、虽然app已经登录服务器,但是在webview中还是提示需要登录。

2、app下一次对服务器的请求也会失败,提示session过期。

解决方案:

1、获取到HttpUrlConnection中服务器返回的session id。

2、本地保存session id,每次对服务器的请求,手动添加。

3、将此session id设置到持有webview的activity中的CookieManager里

 1 网络处理类  NetHelper
 2  
 3 /**
 4      * 发送登陆请求,并将SESSIONID保存起来
 5      * @param urlPath 登陆请求的地址
 6      * @return 返回的内容
 7      * */
 8 public static String login(String urlPath)  {
 9  
10         ......省略号......
11  
12         try {
13             URL url = new URL(urlPath);
14             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
15  
16             //设置请求方式
17             conn.setRequestMethod("GET");
18             conn.setConnectTimeout(5000);
19 //            conn.setReadTimeout(5000);
20  
21             int responseCode = conn.getResponseCode();
22             if (responseCode == HttpURLConnection.HTTP_OK) {
23                 InputStream is = conn.getInputStream();
24                 cookList = conn.getHeaderFields().get("Set-Cookie");
25                 if ((sessionId == null) && (cookList != null)) {
26                     for (String value : cookList) {
27                         if ((value != null) && (value.toUpperCase().indexOf(";") > 0)) {
28                             sessionId = value.split(";")[0];
29                         }
30                     }
31                 }
32  
33             ......省略号......
34  
35 }
36         }catch (Exception e){
37             e.printStackTrace();
38 }
39 ......省略号......
40     }/**
41      * 发送一条请求,将内容以字符串返回
42      * @param urlPath 请求的地址
43      * @return 返回的内容
44      * */
45 public static String request(String urlPath) {
46  
47         ......省略号......
48  
49         try {
50             URL url = new URL(urlPath);
51             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
52             if(sessionId !=null ){
53                 conn.setRequestProperty("Cookie",sessionId);
54             }
55             conn.setRequestMethod("GET");
56             conn.setConnectTimeout(5000);
57 //          conn.setReadTimeout(5000);
58  
59         ......省略号......
60  
61         } catch (Exception e) {
62             e.printStackTrace();
63 }
64  
65         ......省略号......
66  
67     }持有webview的Activity  MainActivity
68  
69 private CookieManager cookieManager;
70  
71 cookieManager = CookieManager.getInstance();
72 cookieManager.setAcceptCookie(true);
73 clearSession();
74  
75 private void clearSession() {
76     if (NetHelper.cookList != null) {
77     cookieManager.removeSessionCookie();
78     }
79 }
80  
81 //在第一次请求的时候,设置一次session即可
82 private void setSession(String url) {
83     if (NetHelper.cookList != null) {
84         String values = NetHelper.cookList.toString();
85         cookieManager.setCookie(url, values); //设置cookie
86         CookieSyncManager.getInstance().sync(); //同步
87     }
88 }

2. 自定义控件的实现方案

自定义控件的实现方式(详细内容可以参考压缩包中的<自定义控件.pdf>):

1、继承方式

当简单控件不满足需求时,通过继承重写简单控件,实现对控件的定制。

2、组合方式

当单个控件不满足需求时,可以采用多个控件的组合,实现对控件的定制。

3、控件自绘方式

通过继承自view,重写onDraw方法实现。

项目中的具体应用:

1、登录邮箱的自动补全功能实现(纯代码实现布局)。

2、弹窗滚轮的实现(代码加布局文件)

3、TabButton的实现(两种实现方式)

A、 登录邮箱的自动补全功能实现:

效果:

实现原理:

1、继承重写简单控件AutoCompleteTextView

2、编写自定义数据适配器和布局文件,并实现文字变化监听器

3、通过组合方式,实现右侧的删除图标。并根据焦点和文字的变化,动态显示右侧删除图标。

1、通过继承自简单控件AutoCompleteTextView实现帐号自动补全

关键代码:

 1 public class AutoComplete extends AutoCompleteTextView {
 2  
 3     private static final String[] emailSuffix = {
 4         "@qq.com", "@163.com", "@126.com", "@gmail.com", "@sina.com", "@hotmail.com",
 5         "@yahoo.cn", "@sohu.com", "@foxmail.com", "@139.com", "@yeah.net", "@vip.qq.com",
 6         "@vip.sina.com"};
 7  
 8     ......省略号......
 9  
10     //构造函数原型要正确,留给系统调用
11  
12     public AutoComplete(Context context) {
13         super(context);
14         mContext = context;
15     }
16  
17     public AutoComplete(Context context, AttributeSet attrs) {
18         super(context, attrs);
19         mContext = context;
20     }
21  
22     public void init(ImageView imageView) {
23         mImageView = imageView;
24         final MyAdatper adapter = new MyAdatper(mContext);
25         setAdapter(adapter);
26         addTextChangedListener(new TextWatcher() {
27             @Override
28             public void afterTextChanged(Editable s) {
29                 if (isTextWatch) {
30                     String input = s.toString();
31  
32                     ......省略号......
33  
34                     adapter.clearList(); //注意要清空数据,根据输入的变化,自动生成数据
35                     if (input.length() > 0) {
36                         for (int i = 0; i < emailSuffix.length; ++i) {
37                             adapter.addListData(input + emailSuffix[i]);
38                         }
39                     }
40                     adapter.notifyDataSetChanged();
41                     showDropDown();//该行代码会造成崩溃
42                 }
43             }
44         });
45         //当输入一个字符的时候就开始检测
46         setThreshold(1);
47     }
48  
49     private class ViewHolder {
50         TextView tv_Text;
51     }
52  
53     class MyAdatper extends BaseAdapter implements Filterable {
54         private List<String> mList;
55         private Context mContext;
56         private MyFilter mFilter;
57  
58         ......省略号......
59  
60         public void clearList() {
61             mList.clear();
62         }
63  
64         public void addListData(String strData) {
65             mList.add(strData);
66         }
67  
68         @Override
69         public View getView(int position, View convertView, ViewGroup parent) {
70             View view;
71             ViewHolder viewHolder;
72  
73             if (convertView == null) {
74                 view = LayoutInflater.from(mContext).inflate(R.layout.activity_autocomplete_item, null);
75                 viewHolder = new ViewHolder();
76                 viewHolder.tv_Text = (TextView) view.findViewById(R.id.tv_autocomplete);
77                 view.setTag(viewHolder);
78             } else {
79                 view = convertView;
80                 viewHolder = (ViewHolder) view.getTag();
81             }
82  
83             viewHolder.tv_Text.setText(mList.get(position));
84  
85             return view;
86         }
87  
88         ......省略号......
89  
90     }

activity_autocomplete_item 下拉列表布局文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:background="@color/White"
 6     android:layout_height="wrap_content">
 7  
 8     <TextView
 9         android:id="@+id/tv_autocomplete"
10         android:padding="15dp"
11         android:textSize="20sp"
12         android:singleLine="true"
13         android:textColor="@color/Black"
14         android:layout_width="match_parent"
15         android:layout_height="wrap_content" />
16  
17 </LinearLayout>

上面自动补全的效果图:

2、通过组合方式实现帐号自动补全复杂控件

关键代码:

 1 public class AdvancedAutoCompleteTextView extends RelativeLayout {
 2     private Context mContext;
 3     private AutoComplete mAutoComplete; //上面的自定义控件
 4     private ImageView mImageView;       //右侧的图标控件
 5  
 6     ......省略号......
 7  
 8     @Override
 9     protected void onFinishInflate() {
10         super.onFinishInflate();
11         initViews();
12     }
13     //代码方式,初始化布局
14     private void initViews() {
15         RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
16         params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
17         params.addRule(RelativeLayout.CENTER_VERTICAL);
18         mAutoComplete = new AutoComplete(mContext);
19         mAutoComplete.setLayoutParams(params);
20         mAutoComplete.setPadding(0, 0, 40, 0);
21         mAutoComplete.setSingleLine(true);
22         mAutoComplete.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
23         mAutoComplete.setFitsSystemWindows(true);
24         mAutoComplete.setEms(10);
25         mAutoComplete.setHint("URS账号");
26         mAutoComplete.setImeOptions(EditorInfo.IME_ACTION_NEXT
27                                 | EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN);
28         mAutoComplete.setDropDownHorizontalOffset(0);
29         mAutoComplete.setDropDownVerticalOffset(2);
30         mAutoComplete.setBackgroundResource(R.drawable.edit_text_background);
31  
32         RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
33         p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
34         p.addRule(RelativeLayout.CENTER_VERTICAL);
35         p.rightMargin = 10;
36         mImageView = new ImageView(mContext);
37         mImageView.setLayoutParams(p);
38         mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
39         mImageView.setImageResource(R.drawable.unselect);
40         mImageView.setClickable(true);
41         mImageView.setOnClickListener(new View.OnClickListener() {
42             @Override
43             public void onClick(View v) {
44                 setText("");
45             }
46         });
47  
48         this.addView(mAutoComplete);
49         this.addView(mImageView);
50         //监听获取焦点事件,目的:输入帐号时,右侧图标的显示
51         mAutoComplete.setOnFocusChangeListener(new OnFocusChangeListener() {
52             @Override
53             public void onFocusChange(View v, boolean hasFocus) {
54                 if (hasFocus && !mAutoComplete.getText().toString().isEmpty()) {
55                     mAutoComplete.setShow(false); //如果获取首次获取焦点,此时文本不为空,则显示,并禁止文本改变监听里的设置
56                     mImageView.setImageResource(R.drawable.item_delete);
57                 } else if (hasFocus) {
58                     mAutoComplete.setShow(true);//如果获取首次获取焦点,此时文本为空,则不改变,并开启文本改变监听里的设置
59                 } else {
60                     mAutoComplete.setShow(false);
61                     mImageView.setImageResource(R.drawable.unselect);
62                 }
63             }
64         });
65  
66                  //对AutoComplete自定义控件初始化,一定要放到最后.否则,会由于AutoComplete初始化未完成,就弹窗,而崩溃
67  
68         mAutoComplete.init(mImageView); 
69     }
70 }

B、弹窗滚轮的实现

效果:

实现原理:

1、继承重写简单控件ScrollView,实现滚动效果,并添加回调接口,用于获取选择的内容。

2、为自定义控件添加内容,其中每一项为一个TextView,用于内容显示。

3、通过自绘添加上下两条直线,实现选中状态。

4、最后利用popup弹窗,加载整个视图,显示弹窗滚动效果。

1、通过继承ScrollView实现滚动,并向布局添加具体项

关键代码:

  1 ublic class WheelView extends ScrollView {
  2  
  3     //选择后的回调接口
  4     public interface OnWheelViewListener {
  5         void onSelected(int selectedIndex, String item);
  6     }
  7  
  8     ......省略号......
  9  
 10     //初始化,并创建布局
 11     private void init(Context context) {
 12         this.context = context;
 13         this.setVerticalScrollBarEnabled(false);
 14  
 15         views = new LinearLayout(context);  //为自定义控件创建线性布局
 16         views.setOrientation(LinearLayout.VERTICAL);
 17         this.addView(views);
 18  
 19         //异步任务,根据滚动的位置自动调整待显示的数据,该异步任务会在滚动事件触发式执行
 20         scrollerTask = new Runnable() {
 21             public void run() {
 22                 if (itemHeight == 0) {
 23                     return;
 24                 }
 25                 int newY = getScrollY();
 26                 if (initialY - newY == 0) { // stopped
 27                     final int remainder = initialY % itemHeight;
 28                     final int divided = initialY / itemHeight;
 29  
 30                     if (remainder == 0) {
 31                         selectedIndex = divided + offset;
 32                         onSeletedCallBack();
 33                     } else {
 34                         if (remainder > itemHeight / 2) {
 35                             WheelView.this.post(new Runnable() {
 36                                 @Override
 37                                 public void run() {
 38                                     WheelView.this.smoothScrollTo(0, initialY - remainder + itemHeight);
 39                                     selectedIndex = divided + offset + 1;
 40                                     onSeletedCallBack();
 41                                 }
 42                             });
 43                         } else {
 44                             WheelView.this.post(new Runnable() {
 45                                 @Override
 46                                 public void run() {
 47                                     WheelView.this.smoothScrollTo(0, initialY - remainder);
 48                                     selectedIndex = divided + offset;
 49                                     onSeletedCallBack();
 50                                 }
 51                             });
 52                         }
 53                     }
 54                 } else {
 55                     initialY = getScrollY();
 56                     WheelView.this.postDelayed(scrollerTask, newCheck);
 57                 }
 58             }
 59         };
 60     }
 61  
 62     //往布局添加数据
 63  
 64     private void initData() {
 65         displayItemCount = offset * 2 + 1;
 66  
 67         //添加新view之前,必须移除旧的,否则不正确
 68         views.removeAllViews();
 69  
 70         for (String item : items) {
 71             views.addView(createView(item));
 72         }
 73  
 74         refreshItemView(0);
 75     }
 76  
 77     private TextView createView(String item) {
 78         TextView tv = new TextView(context);
 79         tv.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
 80         tv.setSingleLine(true);
 81         tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
 82         tv.setText(item);
 83         tv.setGravity(Gravity.CENTER);
 84         int padding = dip2px(15);
 85         tv.setPadding(padding, padding, padding, padding);
 86         if (0 == itemHeight) {
 87             itemHeight = getViewMeasuredHeight(tv);
 88             views.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * displayItemCount));
 89             LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.getLayoutParams();
 90             this.setLayoutParams(new LinearLayout.LayoutParams(lp.width, itemHeight * displayItemCount));
 91         }
 92         return tv;
 93     }
 94  
 95     ......省略号......
 96  
 97     @Override   //上下直线的自绘
 98     public void setBackgroundDrawable(Drawable background) {
 99  
100         if (viewWidth == 0) {
101             viewWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
102         }
103  
104         if (null == paint) {
105             paint = new Paint();
106             paint.setColor(Color.parseColor("#83cde6"));
107             paint.setStrokeWidth(dip2px(1f));
108         }
109  
110         background = new Drawable() {
111             @Override
112             public void draw(Canvas canvas) {
113                 canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[0], viewWidth * 5 / 6, 
114  
115 obtainSelectedAreaBorder()[0], paint);
116  
117                 canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[1], viewWidth * 5 / 6, 
118  
119 obtainSelectedAreaBorder()[1], paint);
120  
121             }
122         };
123  
124         super.setBackgroundDrawable(background);
125     }
126  
127 }

2、动态加载布局,并利用PopupWindow弹窗显示。

关键代码:

1 private void addView(int num){
2  
3     ......省略号......
4  
5     wheel_layout_view = LayoutInflater.from(this).inflate(R.layout.wheel_view, null);
6  
7     ......省略号......
8  
9  }

布局文件 wheel_view 效果图

 1 private void popupWindows(List<String> list){
 2     if (wheel_layout_view != null){
 3  
 4         mPopupWindow = null;
 5         mPopupWindow = new PopupWindow(wheel_layout_view);
 6         mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
 7         mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
 8  
 9         //点击外部,自动消失
10         mPopupWindow.setFocusable(true);
11         mPopupWindow.setOutsideTouchable(true);
12  
13         ......省略号......
14  
15         mPopupWindow.showAtLocation(ll_weidu_condition, Gravity.BOTTOM, 0, 0);
16     }
17 }

C、TabButton的实现

效果:

1、利用.9.png图标实现(简单、美观)

属性定义attrs.xml:

1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3     <!-- 自定义的button控件,用于日期的选择-->
4     <declare-styleable name="TabButton">
5         <attr name="normal_bg_res" format="reference" />
6         <attr name="selected_bg_res" format="reference" />
7     </declare-styleable>
8 </resources>

布局文件:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:custom="http://schemas.android.com/apk/res-auto"   //声明自定义属性空间
 3  
 4     ......省略号......
 5  
 6     android:orientation="vertical">
 7  
 8     ......省略号......
 9  
10         <xxxxxxxxxxx.customui.TabButton
11             style="@style/commonButton"
12             android:layout_width="0dp"
13             android:layout_margin="0dp"
14             android:layout_weight="1"
15             android:layout_height="40dp"
16             android:text="昨天"
17             android:textSize="22sp"
18             android:gravity="center"
19             android:background="@drawable/btn_left"
20             android:textColor="@color/blue"
21             custom:normal_bg_res="@drawable/btn_left"
22             custom:selected_bg_res="@drawable/btn_left_selected"
23             android:id="@+id/bt_yesterday" />
24  
25     ......省略号......
26  
27 </LinearLayout>

关键代码:

 1 public class TabButton extends Button {
 2     private int normal_bg_res;
 3     private int selected_bg_res;
 4  
 5     public TabButton(Context context) {
 6         super(context);
 7     }
 8  
 9     public TabButton(Context context, AttributeSet attrs) {
10         super(context, attrs);
11  
12         TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.TabButton);
13         normal_bg_res = typeArray.getResourceId(R.styleable.TabButton_normal_bg_res, 0);
14         selected_bg_res = typeArray.getResourceId(R.styleable.TabButton_selected_bg_res, 0);
15  
16         typeArray.recycle();
17     }
18  
19     public void setSelected(boolean selected) {
20         if (selected) {
21             setBackgroundResource(selected_bg_res);
22             setTextColor(Color.WHITE);
23         } else {
24             setBackgroundResource(normal_bg_res);
25             setTextColor(getResources().getColor(R.color.blue));
26         }
27     }
28 }

2、利用布局文件实现(复杂、灵活)。

更多样式,可以参数官方的SDK(android-sdk-windowsplatformsandroid-1.5data es)

布局样式button_style:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <selector xmlns:android="http://schemas.android.com/apk/res/android">
 3     <item android:state_pressed="true">
 4         <shape android:shape="rectangle">
 5             <solid android:color="#0d76e1" />
 6         </shape>
 7     </item>
 8  
 9     <item android:state_focused="true">
10         <shape android:shape="rectangle">
11             <solid android:color="@color/Grey" />
12         </shape>
13     </item>
14  
15     <item>
16         <shape android:shape="rectangle">
17             <solid android:color="@color/Grey" />
18         </shape>
19     </item>
20 </selector>

样式应用:

1 <Button android:id="@+id/tab_button"
2     android:layout_width="wrap_content"
3     android:layout_height="wrap_content"
4     android:background="@drawable/button_style">

3. 蒙板效果的实现

1、不保留标题栏蒙板的实现

效果:

原理:

1、弹窗时,设置背景窗体的透明度

2、取消弹窗时,恢复背景窗体的透明度

关键代码:

 1 private void popupWindows(List<String> list){
 2     //产生背景变暗效果
 3     WindowManager.LayoutParams lp=getWindow().getAttributes();
 4     lp.alpha = 0.4f;
 5     getWindow().setAttributes(lp);
 6  
 7         ......省略号......
 8  
 9     mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
10             @Override
11             public void onDismiss() {
12                 WindowManager.LayoutParams lp = getWindow().getAttributes();
13                 lp.alpha = 1f;
14                 getWindow().setAttributes(lp);
15             }
16         });
17  
18       ......省略号......
19  
20 }

2、保留标题栏蒙板的实现

效果:

原理:

1、根据需求,设置蒙板布局大小。

2、弹窗时,显示蒙板布局

2、取消弹窗时,隐藏蒙板布局

关键代码:

1、蒙板布局实现:

 1 <!-- popup蒙板 -->
 2 <LinearLayout
 3     android:id="@+id/ll_popup_hide"
 4     android:layout_width="match_parent"
 5     android:background="@color/hide_bg"
 6     android:orientation="vertical"
 7     android:layout_height="match_parent">
 8 </LinearLayout>
 9  
10 <color name="hide_bg">#88323232</color>

2、代码处理

1 ll_popup_hide.setVisibility(View.VISIBLE); //显示蒙板
2 ll_popup_hide.setVisibility(View.INVISIBLE); //隐藏蒙板

4. Activity的回收与操作超时的处理

1、Activity的回收

针对多个activity退出的处理

关键代码:

1、新建活动管理类:

 1 public class ActivityCollector {
 2     private static List<Activity> activityList = new ArrayList<Activity>();
 3     public static void addActivity(Activity activity){
 4         activityList.add(activity);
 5     }
 6     public static void removeActivity(Activity activity){
 7         activityList.remove(activity);
 8     }
 9  
10     public static void finishAllButLast(){
11         Activity activity = activityList.get(activityList.size()-1);
12         removeActivity(activity);
13  
14         for (Activity activityItem: activityList){
15             if (!activityItem.isFinishing()){
16                 activityItem.finish();
17             }
18         }
19  
20         activityList.clear();
21         activityList.add(activity);
22     }
23  
24     public static void finishAll(){
25         for (Activity activity: activityList){
26             if (!activity.isFinishing()){
27                 activity.finish();
28             }
29         }
30  
31         activityList.clear();
32     }
33 }

2、创建基类BaseActivity,并使所有的activity继承自该基类 。在创建时,添加到活动管理器,销毁时,从活动管理器中移除。

 1 public class BaseActivity extends Activity {
 2     @Override
 3     protected void onCreate(Bundle savedInstanceState) {
 4         super.onCreate(savedInstanceState);
 5         ActivityCollector.addActivity(this);
 6     }
 7  
 8     @Override
 9     protected void onDestroy() {
10         super.onDestroy();
11         ActivityCollector.removeActivity(this);
12     }
13 }

如果需要销毁所有activity,只需调用finishAll()即可

2、操作超时处理

原理:

1、在activity的stop函数中,根据app进程IMPORTANCE_FOREGROUND判断app在前台或后台

2、在activity的onResume函数中,做超时检查。

关键代码:

 1 abstract public class TimeOutCheckActivity extends BaseActivity {
 2     private boolean isLeave = false;
 3  
 4     @Override
 5     protected void onCreate(Bundle savedInstanceState) {
 6         super.onCreate(savedInstanceState);
 7         pref = getSharedPreferences(Constant.CONFIG_NAME, Context.MODE_PRIVATE);
 8     }
 9  
10     /**
11      * 回调函数,方便测试
12      * @return
13     */
14     abstract protected String getTag();
15  
16     ......省略号......
17  
18     /***
19      * 当用户使程序恢复为前台显示时执行onResume()方法,在其中判断是否超时.
20      */
21     @Override
22     protected void onResume() {
23 //        Log.i("Back",getTag() + ",onResume,是否在前台:" + isOnForeground());
24         super.onResume();
25         if (isLeave) {
26             isLeave = false;
27             timeOutCheck();
28         }
29     }
30  
31     @Override 
32     protected void onStop() {
33         super.onStop();
34         if (!isOnForeground()){
35             if (!isLeave && isOpenALP()) {
36                 isLeave = true;
37                 saveStartTime();
38             }
39         }
40     }
41  
42     public void timeOutCheck() {
43         long endtime = System.currentTimeMillis();
44         if (endtime - getStartTime() >= Constant.TIMEOUT_ALP * 1000) {
45             Util.toast(this, "超时了,请重新验证");
46             String alp = pref.getString(Constant.ALP, null);
47             if (alp == null || alp == "") {
48             } else {
49                 Intent intent = new Intent(this, UnlockGesturePasswordActivity.class);
50                 intent.putExtra("pattern", alp);
51                 intent.putExtra("login",false); //手势验证,不进行登录验证
52                 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
53                 // 打开新的Activity
54                 startActivityForResult(intent, Constant.REQ_COMPARE_PATTERN_TIMEOUT_CHECK);
55             }
56         }
57     }
58  
59     public void saveStartTime() {
60         pref.edit().putLong(Constant.START_TIME, System.currentTimeMillis()).commit();
61     }
62  
63     public long getStartTime() {
64         long startTime = 0;
65         try {
66             startTime = pref.getLong(Constant.START_TIME, 0);
67         }catch (Exception e){
68             startTime = 0;
69         }
70         return startTime;
71     }
72  
73     /**
74      * 程序是否在前端运行,通过枚举运行的app实现。防止重复超时检测多次,保证只有一个activity进入超时检测
75      *当用户按home键时,程序进入后端运行,此时会返回false,其他情况引起activity的stop函数的调用,会返回true
76      * @return
77     */
78     public boolean isOnForeground() {
79         ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
80         String packageName = getApplicationContext().getPackageName();
81  
82         List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
83         if (appProcesses == null)
84             return false;
85  
86         for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
87             if (appProcess.processName.equals(packageName)
88                     && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 
89                 return true;
90             }
91         }
92  
93         return false;
94     }
95 }

补充说明:

可以根据importance的不同来判断前台或后台,RunningAppProcessInfo 里面的常量IMTANCE就是上面所说的前台后台,其实IMOPORTANCE是表示这个app进程的重要性,因为系统回收时候,会根据IMOPORTANCE来回收进程的。具体可以去看文档。

1 public static final int IMPORTANCE_BACKGROUND = 400//后台
2 public static final int IMPORTANCE_EMPTY = 500//空进程
3 public static final int IMPORTANCE_FOREGROUND = 100//在屏幕最前端、可获取到焦点 
4 可理解为Activity生命周期的OnResume();
5 public static final int IMPORTANCE_SERVICE = 300//在服务中
6 public static final int IMPORTANCE_VISIBLE = 
7 200//在屏幕前端、获取不到焦点可理解为Activity生命周期的OnStart();
原文地址:https://www.cnblogs.com/liyiran/p/5388837.html