is App On Foreground - Android App

Android examples for App:App Running

Description

is App On Foreground

Demo Code


//package com.java2s;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;

import java.util.List;

public class Main {

    public static boolean isAppOnForeground(Context context) {
        return !isApplicationBroughtToBackground(context);
    }//from w  ww . jav  a2 s. c  om

    public static boolean isApplicationBroughtToBackground(
            final Context context) {
        try {
            ActivityManager am = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am
                    .getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (!topActivity.getPackageName().equals(
                        context.getPackageName())) {
                    return true;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}

Related Tutorials