user3015996
user3015996

Reputation:

repeatedly checking whether the application is in foreground or background

I want to detect when the app comes from back ground to foreground every time. I'm geting the state using the following code

   topActivity.getPackageName().equals(context.getPackageName())

But I need to execute the code repeatedly so that I could detect every time when my app comes to foreground

Upvotes: 0

Views: 82

Answers (2)

Leonidos
Leonidos

Reputation: 10518

It's your app. Activity always knows if it is visible or not. So make every your activity tell someone it's state. You don't need to poll app state. Check this answer.

Upvotes: 1

Siddharth_Vyas
Siddharth_Vyas

Reputation: 10100

Try this :

    public static String isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (topActivity.getPackageName().equals(context.getPackageName())) {
            return "true";
        }
    }

    return "false";
}

Hope this helps.

Upvotes: 0

Related Questions