Witek
Witek

Reputation: 6472

How to determine, if Android app is currently in use?

My app uses a lot of memory when it is used. I would like to free the memory when the app is not used.

I have implemented Application.onTrimMemory(). But this method is called even if my app is currently in use (an activity is presented to the user). How to determine if any activity of my app is currently active?

minSdkVersion="9"

Upvotes: 2

Views: 88

Answers (1)

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

Use this simple method to check whether the app is running on foreground or not!

public boolean isAppForground() {

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
        Iterator<RunningAppProcessInfo> i = l.iterator();
        while (i.hasNext()) {
            RunningAppProcessInfo info = i.next();

            if (info.uid == getApplicationInfo().uid && info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

Upvotes: 1

Related Questions