is App Foreground Running - Android App

Android examples for App:App Running

Description

is App Foreground Running

Demo Code


//package com.java2s;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.KeyguardManager;
import android.app.Service;
import android.content.Context;

public class Main {
    public static synchronized boolean isForegroundRunning(Context con) {
        return !isBackgroundRunning(con);
    }/*from  w w w . j  ava2s .c o  m*/

    public static synchronized boolean isBackgroundRunning(Context con) {

        ActivityManager activityManager = (ActivityManager) con
                .getSystemService(Service.ACTIVITY_SERVICE);
        KeyguardManager keyguardManager = (KeyguardManager) con
                .getSystemService(Service.KEYGUARD_SERVICE);

        if (activityManager == null)
            return false;
        List<RunningAppProcessInfo> processList = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo process : processList) {

            if (process.processName.equals(con.getPackageName())) {
                boolean isBackground = process.importance != RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        && process.importance != RunningAppProcessInfo.IMPORTANCE_VISIBLE;
                boolean isLockedState = keyguardManager
                        .inKeyguardRestrictedInputMode();
                if (isBackground || isLockedState) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        return false;
    }
}

Related Tutorials