Bhavesh Jethani
Bhavesh Jethani

Reputation: 3875

Check application is minimized/background

I am so surprised!

Because not able identify application currently in foreground or background,

when i pressed home button and my application is not in foreground. then after i have used to check application running in foreground or not.

public boolean isAppOnForeground()
    {

        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null) { return false; }
        final String packageName = context.getPackageName();
        for (RunningAppProcessInfo appProcess : appProcesses)
        {
            if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; }
        }
        return false;

    }

it will returns always true even if my application actually not in foreground.

Note: My application have 2 services, 1 service will be canceled when application is removed from recent task list( that i have achieved.) 2 service will be canceled when application goes in background. (that is check wifi signal strength.)

how to know app is foreground or background?

how to stop service when application is not in foreground?

Upvotes: 0

Views: 4146

Answers (2)

Egor
Egor

Reputation: 40203

Rely on Activity callback methods, such as onPause(), onStop() and onResume(), that will give you hints on the current state of Activity. The Activity reference gives a very broad explanation of every of those methods.

Upvotes: 3

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

try handling onpause() event of activity class. Onpause is called when activity goes out of focus.

Upvotes: 1

Related Questions