Android移動應用開發中常見的經驗技巧總結

轉:http://wwwdevstorecn/essay/essayInfo/6128.htmlhtml

1. 對話保持的解決方案。前端

要求:android

一、app中使用webview訪問具體網站的內容,可是app與服務器的溝通是使用HttpUrlConnection來完成。web

二、webview訪問時不須要再次登錄,繼承app的登錄狀態。canvas

會話未保持的現象:windows

一、雖然app已經登陸服務器,可是在webview中仍是提示須要登陸。後端

二、app下一次對服務器的請求也會失敗,提示session過時。服務器

解決方案:cookie

一、獲取到HttpUrlConnection中服務器返回的session id。網絡

二、本地保存session id,每次對服務器的請求,手動添加。

三、將此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>):

一、繼承方式

當簡單控件不知足需求時,經過繼承重寫簡單控件,實現對控件的定製。

二、組合方式

當單個控件不知足需求時,能夠採用多個控件的組合,實現對控件的定製。

三、控件自繪方式

經過繼承自view,重寫onDraw方法實現。

項目中的具體應用:

一、登陸郵箱的自動補全功能實現(純代碼實現佈局)。

二、彈窗滾輪的實現(代碼加布局文件)

三、TabButton的實現(兩種實現方式)

A、 登陸郵箱的自動補全功能實現:

效果:

實現原理:

一、繼承重寫簡單控件AutoCompleteTextView

二、編寫自定義數據適配器和佈局文件,並實現文字變化監聽器

三、經過組合方式,實現右側的刪除圖標。並根據焦點和文字的變化,動態顯示右側刪除圖標。

一、經過繼承自簡單控件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>

上面自動補全的效果圖:

二、經過組合方式實現賬號自動補全複雜控件

關鍵代碼:

 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、彈窗滾輪的實現

效果:

實現原理:

一、繼承重寫簡單控件ScrollView,實現滾動效果,並添加回調接口,用於獲取選擇的內容。

二、爲自定義控件添加內容,其中每一項爲一個TextView,用於內容顯示。

三、經過自繪添加上下兩條直線,實現選中狀態。

四、最後利用popup彈窗,加載整個視圖,顯示彈窗滾動效果。

一、經過繼承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 }

二、動態加載佈局,並利用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的實現

效果:

一、利用.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 }

二、利用佈局文件實現(複雜、靈活)。

更多樣式,能夠參數官方的SDK(android-sdk-windows\platforms\android-1.5\data\res\)

佈局樣式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 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 }

二、保留標題欄蒙板的實現

效果:

原理:

一、根據需求,設置蒙板佈局大小。

二、彈窗時,顯示蒙板佈局

二、取消彈窗時,隱藏蒙板佈局

關鍵代碼:

一、蒙板佈局實現:

 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>

二、代碼處理

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

4. Activity的回收與操做超時的處理

一、Activity的回收

針對多個activity退出的處理

關鍵代碼:

一、新建活動管理類:

 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 }

二、建立基類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()便可

二、操做超時處理

原理:

一、在activity的stop函數中,根據app進程IMPORTANCE_FOREGROUND判斷app在前臺或後臺

二、在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();
相關文章
相關標籤/搜索