android 应用前后台判断

我在补一个判断的方法。

View.onDetachFromWindow()

重载这个方法,当窗口不可见的时候,在WMS中会

public void setAppVisibility(IBinder token, boolean visible) {
    ...
    if (wtoken.clientHidden) {
        // In the case where we are making an app visible
        // but holding off for a transition, we still need
        // to tell the client to make its windows visible so
        // they get drawn.  Otherwise, we will wait on
        // performing the transition until all windows have
        // been drawn, they never will be, and we are sad.
        wtoken.clientHidden = false;
        wtoken.sendAppVisibilityToClients();
    }
    ...
}

binder调用发到用户进程之后,View的onDetachFromWindow就会被调用,这个时候,窗口已经不可见了。


下面是笔记


前后台的判断主要有几种方法,我上面提到的是一种,还有其他几种

registerActivityLifecycleCallbacks

OsApp.getIns().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    @Override
    public void onActivityStarted(Activity activity) {
        notifyActivityCountChange(1);
    }

    @Override
    public void onActivityResumed(Activity activity) {
    }

    @Override
    public void onActivityPaused(Activity activity) {
    }

    @Override
    public void onActivityStopped(Activity activity) {
        notifyActivityCountChange(-1);
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
});

private int appCount = 0;

private void notifyActivityCountChange(int del) {
    appCount += del;
    Log.e("LifecycleCallbacks", "is front :" + (appCount > 0));
}

监听activity生命周期的回调,最简单,也是最有效的方法

onPause

和上面一种类似,不过是每个onPause都要手动处理

getRunningAppProcesses

public boolean checkRunningAppProcesses(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
    assert activityManager != null;
    List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
    if (runningAppProcessInfoList != null) {
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            if (processInfo.processName.equals(context.getPackageName()) &&
                    processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

                return true;
            }
        }
    }
    return false;
}

RunningTask

public boolean checkRunningTask(Context context) {
    ActivityManager activityManager = (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
    assert activityManager != null;
    ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
    String currentPackageName = cn.getPackageName();
    return !TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName());
}

check file proc

public boolean checkProc() {
    return ProcessManager.isMyProcessInTheForeground();
}

ProcessManager.java

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import com.jaredrummler.android.processes.models.AndroidAppProcess;
import com.jaredrummler.android.processes.models.AndroidProcess;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


public class ProcessManager {

    private static final String TAG = "AndroidProcesses";

    public static void log(String message, Object... args) {
        Log.d(TAG, args.length == 0 ? message : String.format(message, args));
    }

    public static void log(Throwable error, String message, Object... args) {
        Log.d(TAG, args.length == 0 ? message : String.format(message, args), error);
    }

    public static List<AndroidProcess> getRunningProcesses() {
        List<AndroidProcess> processes = new ArrayList<>();
        File[] files = new File("/proc").listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                int pid;
                try {
                    pid = Integer.parseInt(file.getName());
                } catch (NumberFormatException e) {
                    continue;
                }
                try {
                    processes.add(new AndroidProcess(pid));
                } catch (IOException e) {
                    log(e, "Error reading from /proc/%d.", pid);
                    // System apps will not be readable on Android 5.0+ if SELinux is enforcing.
                    // You will need root access or an elevated SELinux context to read all files under /proc.
                }
            }
        }
        return processes;
    }

    private static List<AndroidAppProcess> getRunningAppProcesses() {
        List<AndroidAppProcess> processes = new ArrayList<>();
        File[] files = new File("/proc").listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                int pid;
                try {
                    pid = Integer.parseInt(file.getName());
                } catch (NumberFormatException e) {
                    continue;
                }
                try {
                    processes.add(new AndroidAppProcess(pid));
                } catch (AndroidAppProcess.NotAndroidAppProcessException ignored) {
                } catch (IOException e) {
                    log(e, "Error reading from /proc/%d.", pid);
                    // System apps will not be readable on Android 5.0+ if SELinux is enforcing.
                    // You will need root access or an elevated SELinux context to read all files under /proc.
                }
            }
        }
        return processes;
    }


    public static List<AndroidAppProcess> getRunningForegroundApps(Context ctx) {
        List<AndroidAppProcess> processes = new ArrayList<>();
        File[] files = new File("/proc").listFiles();
        PackageManager pm = ctx.getPackageManager();
        for (File file : files) {
            if (file.isDirectory()) {
                int pid;
                try {
                    pid = Integer.parseInt(file.getName());
                } catch (NumberFormatException e) {
                    continue;
                }
                try {
                    AndroidAppProcess process = new AndroidAppProcess(pid);
                    if (process.foreground
                            // ignore system processes. First app user starts at 10000.
                            && (process.uid < 1000 || process.uid > 9999)
                            // ignore processes that are not running in the default app process.
                            && !process.name.contains(":")
                            // Ignore processes that the user cannot launch.
                            && pm.getLaunchIntentForPackage(process.getPackageName()) != null) {
                        processes.add(process);
                    }
                } catch (AndroidAppProcess.NotAndroidAppProcessException ignored) {
                } catch (IOException e) {
                    log(e, "Error reading from /proc/%d.", pid);
                    // System apps will not be readable on Android 5.0+ if SELinux is enforcing.
                    // You will need root access or an elevated SELinux context to read all files under /proc.
                }
            }
        }
        return processes;
    }


    public static boolean isMyProcessInTheForeground() {
        List<AndroidAppProcess> processes = getRunningAppProcesses();
        int myPid = android.os.Process.myPid();
        for (AndroidAppProcess process : processes) {
            if (process.pid == myPid && process.foreground) {
                return true;
            }
        }
        return false;
    }


    public static List<RunningAppProcessInfo> getRunningAppProcessInfo(Context ctx) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            List<AndroidAppProcess> runningAppProcesses = ProcessManager.getRunningAppProcesses();
            List<RunningAppProcessInfo> appProcessInfos = new ArrayList<>();
            for (AndroidAppProcess process : runningAppProcesses) {
                RunningAppProcessInfo info = new RunningAppProcessInfo(process.name, process.pid, null);
                info.uid = process.uid;
                // TODO: Get more information about the process. pkgList, importance, lru, etc.
                appProcessInfos.add(info);
            }
            return appProcessInfos;
        }
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        return am.getRunningAppProcesses();
    }

    private ProcessManager() {
        throw new AssertionError("no instances");
    }

    public static final class ProcessComparator implements Comparator<AndroidProcess> {

        @Override
        public int compare(AndroidProcess p1, AndroidProcess p2) {
            return p1.name.compareToIgnoreCase(p2.name);
        }

    }

}

build.gradle

dependencies {
    ...
    compile 'com.jaredrummler:android-processes:1.1.1'
}
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页