Android 监测APP是否处于前台


/**
 * 监测APP是否处于前台
 */
public class ActivityLifecycleService extends Service {

    private int count = 0;

    public boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    if (count > 10) {
                    //处于后台40s后重启APP
                        Intent newIntent = context.getPackageManager().
                                getLaunchIntentForPackage(PackageName);
                        context.startActivity(newIntent);
                    } else {
                        count++;
                    }
                    return true;
                } else {
                    count = 0;
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        executeFixedRate();
    }

    /**
     * 以固定周期频率执行任务
     */
    public void executeFixedRate() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(
                new EchoServer(),
                0,
                1000 * 4,
                TimeUnit.MILLISECONDS);
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    class EchoServer implements Runnable {
        @Override
        public void run() {
            isBackground(TApplication.getInstance());
        }
    }


}

猜你喜欢

转载自blog.csdn.net/d38825/article/details/80582385