is Application In Foreground - Android App

Android examples for App:App Running

Description

is Application In Foreground

Demo Code


//package com.java2s;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;

import android.content.Context;
import android.os.Build;

import java.util.List;

public class Main {

    @SuppressWarnings("deprecation")
    public static boolean isApplicationInForeground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final List<RunningAppProcessInfo> processInfos = activityManager
                    .getRunningAppProcesses();
            for (RunningAppProcessInfo processInfo : processInfos) {
                if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    if (processInfo.processName.equals(context
                            .getPackageName())) {
                        return true;
                    }//from  ww w. ja v a  2 s  . co m
                }
            }
            return false;
        } else {
            List<RunningTaskInfo> tasksInfo = activityManager
                    .getRunningTasks(1);
            if (tasksInfo != null && !tasksInfo.isEmpty()) {
                if (context.getApplicationInfo().packageName
                        .equals(tasksInfo.get(0).topActivity
                                .getPackageName())) {
                    return true;
                }
            }
            return false;
        }
    }
}

Related Tutorials