1. 程式人生 > >判斷本應用是不是在前臺

判斷本應用是不是在前臺

首先由個比較通用的方法。

Activity切換的時候執行邏輯:

A.onCreate->A.onStart()->A.onResume()->A.onPause()->B.onCreate->B.onStart()->B.onResume()->B啟動完畢->A.onStop()

所以只要統計onStart和onStop的次數就好了。

--------------------------------------------------------------------------------------------------------------------------------------

由於我的專案裡有特殊原因:

引入了另外的工程,包名相同但是和我負責的部分完全獨立,也無法去改,於是使用了下面的方法

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

最近有個需求,在應用中增加一個全域性的懸浮球,擬採用Toast方式實現,但Toast是系統級Alert。

應用後臺執行時也會顯示在桌面上,因此需要在每個Activity的生命週期中判斷當前應用還在不在棧頂(使用者可見、正在執行)。

先貼上實現程式碼吧,程式碼有專案依賴,如果有人需要的話拿去把依賴去掉就好了。

定義一個基類,所有Activity都需要繼承這個基類。重寫onResume( )實現顯示邏輯,重寫onStop( )顯示隱藏邏輯。

package com.ct108.open.Base;

import android.app.Activity;
import android.os.Bundle;

import com.ct108.open.Utils.GetTopInfo;
import com.ct108.open.Utils.fordebug.LogUtil;
import com.ct108.open.thm.test.FloatWindowUtil;

/**
 * Created by thm on 2016/8/22.
 */
public class BaseActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.d("BaseActivity onResume");
        if(FloatWindowUtil.getInstance().getService() == null){
            LogUtil.e("BaseActivity getService() == null");
            return;
        }

        if(FloatWindowUtil.getInstance().getService().isHide()){
            LogUtil.d("BaseActivity showFloat");
            FloatWindowUtil.getInstance().getService().showFloat();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        String pkg = new GetTopInfo(this).getPkgName();
        LogUtil.d("BaseActivity onStop & pkg = "+ pkg);
        if(!pkg.equals("com.uc108.doudizhu")){
            if(FloatWindowUtil.getInstance().getService() == null)
                return;
            FloatWindowUtil.getInstance().getService().hide();
            LogUtil.d("BaseActivity hide");
        }
    }

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


工具類GetTopInfo(),獲取棧頂Acativity的包名。

public class GetTopInfo {
    private final Context context;
    public GetTopInfo(Context context) {
        this.context = context;
    }

    public  String getPkgName(){
        if(CollectionUtils.isNotEmpty(get()))
            return get()[0];
        return "";
    }
    public String[] get() {
        LogUtil.d("GetTopInfo curSDK_INT = "+Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT < 21)
            return getPreLollipop();
        else
            return getLollipop();
    }
    private String[] getPreLollipop() {
        @SuppressWarnings("deprecation")
        List<ActivityManager.RunningTaskInfo> tasks =
                activityManager().getRunningTasks(1);
        ActivityManager.RunningTaskInfo currentTask = tasks.get(0);
        ComponentName currentActivity = currentTask.topActivity;
        return new String[] { currentActivity.getPackageName() };
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private String[] getLollipop() {
        final int PROCESS_STATE_TOP = 2;
        try {
            Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");

            List<ActivityManager.RunningAppProcessInfo> processes =
                    activityManager().getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo process : processes) {
                if (process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                           &&  process.importanceReasonCode == 0) {
                    int state = processStateField.getInt(process);
                    if (state == PROCESS_STATE_TOP)
                        return process.pkgList;
                }
            }
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return new String[] { };
    }

    private ActivityManager activityManager() {
        return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    }

    public  boolean isNotEmpty(Object[] array) {
        if(array == null)
            return false;
        if(array.length == 0)
            return false;
        else
            return true;
    }
}