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

apksafe的部落格發表於2016-04-05

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裡。

關鍵程式碼:

網路處理類  NetHelper

/**
     * 傳送登陸請求,並將SESSIONID儲存起來
     * @param urlPath 登陸請求的地址
     * @return 返回的內容
     * */
public static String login(String urlPath)  {

        ......省略號......

        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //設定請求方式
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
//            conn.setReadTimeout(5000);

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream is = conn.getInputStream();
                cookList = conn.getHeaderFields().get("Set-Cookie");
                if ((sessionId == null) && (cookList != null)) {
                    for (String value : cookList) {
                        if ((value != null) && (value.toUpperCase().indexOf(";") > 0)) {
                            sessionId = value.split(";")[0];
                        }
                    }
                }

            ......省略號......

}
        }catch (Exception e){
            e.printStackTrace();
}
......省略號......
    }/**
     * 傳送一條請求,將內容以字串返回
     * @param urlPath 請求的地址
     * @return 返回的內容
     * */
public static String request(String urlPath) {

        ......省略號......

        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            if(sessionId !=null ){
                conn.setRequestProperty("Cookie",sessionId);
            }
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
//          conn.setReadTimeout(5000);

        ......省略號......

        } catch (Exception e) {
            e.printStackTrace();
}

        ......省略號......

    }持有webview的Activity  MainActivity

private CookieManager cookieManager;

cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
clearSession();

private void clearSession() {
    if (NetHelper.cookList != null) {
    cookieManager.removeSessionCookie();
    }
}

//在第一次請求的時候,設定一次session即可
private void setSession(String url) {
    if (NetHelper.cookList != null) {
        String values = NetHelper.cookList.toString();
        cookieManager.setCookie(url, values); //設定cookie
        CookieSyncManager.getInstance().sync(); //同步
    }
}

2. 自定義控制元件的實現方案

自定義控制元件的實現方式(詳細內容可以參考壓縮包中的<自定義控制元件.pdf>):

1、繼承方式

當簡單控制元件不滿足需求時,通過繼承重寫簡單控制元件,實現對控制元件的定製。

2、組合方式

當單個控制元件不滿足需求時,可以採用多個控制元件的組合,實現對控制元件的定製。

3、控制元件自繪方式

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

專案中的具體應用:

1、登入郵箱的自動補全功能實現(純程式碼實現佈局)。
2、彈窗滾輪的實現(程式碼加布局檔案)
3、TabButton的實現(兩種實現方式)

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

效果:

這裡寫圖片描述

實現原理:

1、繼承重寫簡單控制元件AutoCompleteTextView
2、編寫自定義資料介面卡和佈局檔案,並實現文字變化監聽器
3、通過組合方式,實現右側的刪除圖示。並根據焦點和文字的變化,動態顯示右側刪除圖示。

1、通過繼承自簡單控制元件AutoCompleteTextView實現帳號自動補全

關鍵程式碼:

public class AutoComplete extends AutoCompleteTextView {

    private static final String[] emailSuffix = {
        "@qq.com", "@163.com", "@126.com", "@gmail.com", "@sina.com", "@hotmail.com",
        "@yahoo.cn", "@sohu.com", "@foxmail.com", "@139.com", "@yeah.net", "@vip.qq.com",
        "@vip.sina.com"};

    ......省略號......

    //建構函式原型要正確,留給系統呼叫

    public AutoComplete(Context context) {
        super(context);
        mContext = context;
    }

    public AutoComplete(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    public void init(ImageView imageView) {
        mImageView = imageView;
        final MyAdatper adapter = new MyAdatper(mContext);
        setAdapter(adapter);
        addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (isTextWatch) {
                    String input = s.toString();

                    ......省略號......

                    adapter.clearList(); //注意要清空資料,根據輸入的變化,自動生成資料
                    if (input.length() > 0) {
                        for (int i = 0; i < emailSuffix.length; ++i) {
                            adapter.addListData(input + emailSuffix[i]);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    showDropDown();//該行程式碼會造成崩潰
                }
            }
        });
        //當輸入一個字元的時候就開始檢測
        setThreshold(1);
    }

    private class ViewHolder {
        TextView tv_Text;
    }

    class MyAdatper extends BaseAdapter implements Filterable {
        private List<String> mList;
        private Context mContext;
        private MyFilter mFilter;

        ......省略號......

        public void clearList() {
            mList.clear();
        }

        public void addListData(String strData) {
            mList.add(strData);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder viewHolder;

            if (convertView == null) {
                view = LayoutInflater.from(mContext).inflate(R.layout.activity_autocomplete_item, null);
                viewHolder = new ViewHolder();
                viewHolder.tv_Text = (TextView) view.findViewById(R.id.tv_autocomplete);
                view.setTag(viewHolder);
            } else {
                view = convertView;
                viewHolder = (ViewHolder) view.getTag();
            }

            viewHolder.tv_Text.setText(mList.get(position));

            return view;
        }

        ......省略號......

    }

activity_autocomplete_item 下拉選單佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:background="@color/White"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv_autocomplete"
        android:padding="15dp"
        android:textSize="20sp"
        android:singleLine="true"
        android:textColor="@color/Black"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

上面自動補全的效果圖:

這裡寫圖片描述

2、通過組合方式實現帳號自動補全複雜控制元件

關鍵程式碼:

public class AdvancedAutoCompleteTextView extends RelativeLayout {
    private Context mContext;
    private AutoComplete mAutoComplete; //上面的自定義控制元件
    private ImageView mImageView;       //右側的圖示控制元件

    ......省略號......

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initViews();
    }
    //程式碼方式,初始化佈局
    private void initViews() {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        params.addRule(RelativeLayout.CENTER_VERTICAL);
        mAutoComplete = new AutoComplete(mContext);
        mAutoComplete.setLayoutParams(params);
        mAutoComplete.setPadding(0, 0, 40, 0);
        mAutoComplete.setSingleLine(true);
        mAutoComplete.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
        mAutoComplete.setFitsSystemWindows(true);
        mAutoComplete.setEms(10);
        mAutoComplete.setHint("URS賬號");
        mAutoComplete.setImeOptions(EditorInfo.IME_ACTION_NEXT
                                | EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN);
        mAutoComplete.setDropDownHorizontalOffset(0);
        mAutoComplete.setDropDownVerticalOffset(2);
        mAutoComplete.setBackgroundResource(R.drawable.edit_text_background);

        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
        p.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        p.addRule(RelativeLayout.CENTER_VERTICAL);
        p.rightMargin = 10;
        mImageView = new ImageView(mContext);
        mImageView.setLayoutParams(p);
        mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        mImageView.setImageResource(R.drawable.unselect);
        mImageView.setClickable(true);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setText("");
            }
        });

        this.addView(mAutoComplete);
        this.addView(mImageView);
        //監聽獲取焦點事件,目的:輸入帳號時,右側圖示的顯示
        mAutoComplete.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && !mAutoComplete.getText().toString().isEmpty()) {
                    mAutoComplete.setShow(false); //如果獲取首次獲取焦點,此時文字不為空,則顯示,並禁止文字改變監聽裡的設定
                    mImageView.setImageResource(R.drawable.item_delete);
                } else if (hasFocus) {
                    mAutoComplete.setShow(true);//如果獲取首次獲取焦點,此時文字為空,則不改變,並開啟文字改變監聽裡的設定
                } else {
                    mAutoComplete.setShow(false);
                    mImageView.setImageResource(R.drawable.unselect);
                }
            }
        });

                 //對AutoComplete自定義控制元件初始化,一定要放到最後.否則,會由於AutoComplete初始化未完成,就彈窗,而崩潰

        mAutoComplete.init(mImageView); 
    }
}

B、彈窗滾輪的實現

效果:

這裡寫圖片描述

實現原理:

1、繼承重寫簡單控制元件ScrollView,實現滾動效果,並新增回撥介面,用於獲取選擇的內容。
2、為自定義控制元件新增內容,其中每一項為一個TextView,用於內容顯示。
3、通過自繪新增上下兩條直線,實現選中狀態。
4、最後利用popup彈窗,載入整個檢視,顯示彈窗滾動效果。

1、通過繼承ScrollView實現滾動,並向佈局新增具體項

關鍵程式碼:

public class WheelView extends ScrollView {

    //選擇後的回撥介面
    public interface OnWheelViewListener {
        void onSelected(int selectedIndex, String item);
    }

    ......省略號......

    //初始化,並建立佈局
    private void init(Context context) {
        this.context = context;
        this.setVerticalScrollBarEnabled(false);

        views = new LinearLayout(context);  //為自定義控制元件建立線性佈局
        views.setOrientation(LinearLayout.VERTICAL);
        this.addView(views);

        //非同步任務,根據滾動的位置自動調整待顯示的資料,該非同步任務會在滾動事件觸發式執行
        scrollerTask = new Runnable() {
            public void run() {
                if (itemHeight == 0) {
                    return;
                }
                int newY = getScrollY();
                if (initialY - newY == 0) { // stopped
                    final int remainder = initialY % itemHeight;
                    final int divided = initialY / itemHeight;

                    if (remainder == 0) {
                        selectedIndex = divided + offset;
                        onSeletedCallBack();
                    } else {
                        if (remainder > itemHeight / 2) {
                            WheelView.this.post(new Runnable() {
                                @Override
                                public void run() {
                                    WheelView.this.smoothScrollTo(0, initialY - remainder + itemHeight);
                                    selectedIndex = divided + offset + 1;
                                    onSeletedCallBack();
                                }
                            });
                        } else {
                            WheelView.this.post(new Runnable() {
                                @Override
                                public void run() {
                                    WheelView.this.smoothScrollTo(0, initialY - remainder);
                                    selectedIndex = divided + offset;
                                    onSeletedCallBack();
                                }
                            });
                        }
                    }
                } else {
                    initialY = getScrollY();
                    WheelView.this.postDelayed(scrollerTask, newCheck);
                }
            }
        };
    }

    //往佈局新增資料

    private void initData() {
        displayItemCount = offset * 2 + 1;

        //新增新view之前,必須移除舊的,否則不正確
        views.removeAllViews();

        for (String item : items) {
            views.addView(createView(item));
        }

        refreshItemView(0);
    }

    private TextView createView(String item) {
        TextView tv = new TextView(context);
        tv.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tv.setSingleLine(true);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        tv.setText(item);
        tv.setGravity(Gravity.CENTER);
        int padding = dip2px(15);
        tv.setPadding(padding, padding, padding, padding);
        if (0 == itemHeight) {
            itemHeight = getViewMeasuredHeight(tv);
            views.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight * displayItemCount));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.getLayoutParams();
            this.setLayoutParams(new LinearLayout.LayoutParams(lp.width, itemHeight * displayItemCount));
        }
        return tv;
    }

    ......省略號......

    @Override   //上下直線的自繪
    public void setBackgroundDrawable(Drawable background) {

        if (viewWidth == 0) {
            viewWidth = ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
        }

        if (null == paint) {
            paint = new Paint();
            paint.setColor(Color.parseColor("#83cde6"));
            paint.setStrokeWidth(dip2px(1f));
        }

        background = new Drawable() {
            @Override
            public void draw(Canvas canvas) {
                canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[0], viewWidth * 5 / 6, 

obtainSelectedAreaBorder()[0], paint);

                canvas.drawLine(viewWidth * 1 / 6, obtainSelectedAreaBorder()[1], viewWidth * 5 / 6, 

obtainSelectedAreaBorder()[1], paint);

            }
        };

        super.setBackgroundDrawable(background);
    }

}

2、動態載入佈局,並利用PopupWindow彈窗顯示。

關鍵程式碼:

private void addView(int num){

    ......省略號......

    wheel_layout_view = LayoutInflater.from(this).inflate(R.layout.wheel_view, null);

    ......省略號......

 }

佈局檔案 wheel_view 效果圖

這裡寫圖片描述

private void popupWindows(List<String> list){
    if (wheel_layout_view != null){

        mPopupWindow = null;
        mPopupWindow = new PopupWindow(wheel_layout_view);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        //點選外部,自動消失
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);

        ......省略號......

        mPopupWindow.showAtLocation(ll_weidu_condition, Gravity.BOTTOM, 0, 0);
    }
}

C、TabButton的實現

效果:

這裡寫圖片描述
1、利用.9.png圖示實現(簡單、美觀)

屬性定義attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 自定義的button控制元件,用於日期的選擇-->
    <declare-styleable name="TabButton">
        <attr name="normal_bg_res" format="reference" />
        <attr name="selected_bg_res" format="reference" />
    </declare-styleable>
</resources>

佈局檔案:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"   //宣告自定義屬性空間

    ......省略號......

    android:orientation="vertical">

    ......省略號......

        <xxxxxxxxxxx.customui.TabButton
            style="@style/commonButton"
            android:layout_width="0dp"
            android:layout_margin="0dp"
            android:layout_weight="1"
            android:layout_height="40dp"
            android:text="昨天"
            android:textSize="22sp"
            android:gravity="center"
            android:background="@drawable/btn_left"
            android:textColor="@color/blue"
            custom:normal_bg_res="@drawable/btn_left"
            custom:selected_bg_res="@drawable/btn_left_selected"
            android:id="@+id/bt_yesterday" />

    ......省略號......

</LinearLayout>

關鍵程式碼:

public class TabButton extends Button {
    private int normal_bg_res;
    private int selected_bg_res;

    public TabButton(Context context) {
        super(context);
    }

    public TabButton(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typeArray = context.obtainStyledAttributes(attrs, R.styleable.TabButton);
        normal_bg_res = typeArray.getResourceId(R.styleable.TabButton_normal_bg_res, 0);
        selected_bg_res = typeArray.getResourceId(R.styleable.TabButton_selected_bg_res, 0);

        typeArray.recycle();
    }

    public void setSelected(boolean selected) {
        if (selected) {
            setBackgroundResource(selected_bg_res);
            setTextColor(Color.WHITE);
        } else {
            setBackgroundResource(normal_bg_res);
            setTextColor(getResources().getColor(R.color.blue));
        }
    }
}

2、利用佈局檔案實現(複雜、靈活)。

更多樣式,可以引數官方的SDK(android-sdk-windows\platforms\android-1.5\data\res\)

佈局樣式button_style:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#0d76e1" />
        </shape>
    </item>

    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/Grey" />
        </shape>
    </item>

    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/Grey" />
        </shape>
    </item>
</selector>

樣式應用:

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

3. 蒙板效果的實現

1、不保留標題欄蒙板的實現

效果:

這裡寫圖片描述

原理:

1、彈窗時,設定背景窗體的透明度
2、取消彈窗時,恢復背景窗體的透明度

關鍵程式碼:

private void popupWindows(List<String> list){
    //產生背景變暗效果
    WindowManager.LayoutParams lp=getWindow().getAttributes();
    lp.alpha = 0.4f;
    getWindow().setAttributes(lp);

        ......省略號......

    mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

      ......省略號......

}

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

效果:

這裡寫圖片描述

原理:

1、根據需求,設定蒙板佈局大小。
2、彈窗時,顯示蒙板佈局
2、取消彈窗時,隱藏蒙板佈局

關鍵程式碼:

1、蒙板佈局實現:

<!-- popup蒙板 -->
<LinearLayout
    android:id="@+id/ll_popup_hide"
    android:layout_width="match_parent"
    android:background="@color/hide_bg"
    android:orientation="vertical"
    android:layout_height="match_parent">
</LinearLayout>

<color name="hide_bg">#88323232</color>

2、程式碼處理

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

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

1、Activity的回收

針對多個activity退出的處理

關鍵程式碼:

1、新建活動管理類:

public class ActivityCollector {
    private static List<Activity> activityList = new ArrayList<Activity>();
    public static void addActivity(Activity activity){
        activityList.add(activity);
    }
    public static void removeActivity(Activity activity){
        activityList.remove(activity);
    }

    public static void finishAllButLast(){
        Activity activity = activityList.get(activityList.size()-1);
        removeActivity(activity);

        for (Activity activityItem: activityList){
            if (!activityItem.isFinishing()){
                activityItem.finish();
            }
        }

        activityList.clear();
        activityList.add(activity);
    }

    public static void finishAll(){
        for (Activity activity: activityList){
            if (!activity.isFinishing()){
                activity.finish();
            }
        }

        activityList.clear();
    }
}

2、建立基類BaseActivity,並使所有的activity繼承自該基類 。在建立時,新增到活動管理器,銷燬時,從活動管理器中移除。

public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}

如果需要銷燬所有activity,只需呼叫finishAll()即可

2、操作超時處理

原理:

1、在activity的stop函式中,根據app程式IMPORTANCE_FOREGROUND判斷app在前臺或後臺
2、在activity的onResume函式中,做超時檢查。

關鍵程式碼:

abstract public class TimeOutCheckActivity extends BaseActivity {
    private boolean isLeave = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pref = getSharedPreferences(Constant.CONFIG_NAME, Context.MODE_PRIVATE);
    }

    /**
     * 回撥函式,方便測試
     * @return
    */
    abstract protected String getTag();

    ......省略號......

    /***
     * 當使用者使程式恢復為前臺顯示時執行onResume()方法,在其中判斷是否超時.
     */
    @Override
    protected void onResume() {
//        Log.i("Back",getTag() + ",onResume,是否在前臺:" + isOnForeground());
        super.onResume();
        if (isLeave) {
            isLeave = false;
            timeOutCheck();
        }
    }

    @Override 
    protected void onStop() {
        super.onStop();
        if (!isOnForeground()){
            if (!isLeave && isOpenALP()) {
                isLeave = true;
                saveStartTime();
            }
        }
    }

    public void timeOutCheck() {
        long endtime = System.currentTimeMillis();
        if (endtime - getStartTime() >= Constant.TIMEOUT_ALP * 1000) {
            Util.toast(this, "超時了,請重新驗證");
            String alp = pref.getString(Constant.ALP, null);
            if (alp == null || alp == "") {
            } else {
                Intent intent = new Intent(this, UnlockGesturePasswordActivity.class);
                intent.putExtra("pattern", alp);
                intent.putExtra("login",false); //手勢驗證,不進行登入驗證
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                // 開啟新的Activity
                startActivityForResult(intent, Constant.REQ_COMPARE_PATTERN_TIMEOUT_CHECK);
            }
        }
    }

    public void saveStartTime() {
        pref.edit().putLong(Constant.START_TIME, System.currentTimeMillis()).commit();
    }

    public long getStartTime() {
        long startTime = 0;
        try {
            startTime = pref.getLong(Constant.START_TIME, 0);
        }catch (Exception e){
            startTime = 0;
        }
        return startTime;
    }

    /**
     * 程式是否在前端執行,通過列舉執行的app實現。防止重複超時檢測多次,保證只有一個activity進入超時檢測
     *當使用者按home鍵時,程式進入後端執行,此時會返回false,其他情況引起activity的stop函式的呼叫,會返回true
     * @return
    */
    public boolean isOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();

        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 
                return true;
            }
        }

        return false;
    }
}

補充說明:

可以根據importance的不同來判斷前臺或後臺,RunningAppProcessInfo 裡面的常量IMTANCE就是上面所說的前臺後臺,其實IMOPORTANCE是表示這個app程式的重要性,因為系統回收時候,會根據IMOPORTANCE來回收程式的。具體可以去看文件。

public static final int IMPORTANCE_BACKGROUND = 400//後臺 
public static final int IMPORTANCE_EMPTY = 500//空程式 
public static final int IMPORTANCE_FOREGROUND = 100//在螢幕最前端、可獲取到焦點 可理解為Activity生命週期的OnResume(); 
public static final int IMPORTANCE_SERVICE = 300//在服務中 
public static final int IMPORTANCE_VISIBLE = 200//在螢幕前端、獲取不到焦點可理解為Activity生命週期的OnStart();

相關文章