1

Hi Friends i am making an application in which i need to show something when user goes in background and again when user comes in foreground. So i Need to get an event when our app goes in background and again when app comes in foreground working in api above 8.

I tried all thing but only able to recognize if my app is foreground or not. I need event when we come again online at application level.

Love Garg
  • 406
  • 1
  • 5
  • 17
  • this [link](http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html) helps in working around my issue... – Love Garg Sep 08 '14 at 21:43

1 Answers1

0

You can define a superclass for all your activities and track the state of the app. If all activities are in stopped state - app in the background, otherwise - in the foreground. In onStart() and onStop() methods of your super activity you can increment and decrement the number of visible activites. Then in onStart() and onStop() check if there was any currently visible activity. If no - app becomes active/inactive and you can call your method:

public class SuperActivity extends Activity {
    private static int sVisibleActivitiesCount;

    @Override
    public void onStart(){
        super.onStart();
        if (SuperActivity.sVisibleActivitiesCount == 0) {
            onAppBecomesActive();
        }
        SuperActivity.sVisibleActivitiesCount++;
    }

    @Override
    public void onStop(){
        super.onStart();
        SuperActivity.sVisibleActivitiesCount--;
        if (SuperActivity.sVisibleActivitiesCount == 0) {
            onAppBecomesInactive();
        }
    }

    private void onAppBecomesActive() {
        // Do some staff
    }

    private void onAppBecomesInactive() {
        // Do some staff
    }
}

The second approach is to use ActivityLifecycleCallbacks (min API 14) for monitoring activities lifecycle and track application state in a single place without having a super class for all activities. So I would rather use this approach if your app has minSdkVersion="14".

makovkastar
  • 5,000
  • 2
  • 30
  • 50
  • could also add a boolean in a custom implementation of Application and edit it in onStart onStop via getApplication() and casting. So don't need the counting. – MikeIsrael Mar 11 '14 at 15:23
  • thanx for your response But i need event only when App becomes foreground and background. But your approach is marvellous @makovkastar – Love Garg Mar 11 '14 at 16:36