Skip to content

A very simple Android way to detect when app go to background/foreground

License

Notifications You must be signed in to change notification settings

khirr/Android-Foreground-Detection

Repository files navigation

Android-Foreground-Detection

A very simple Android way to detect when app go to background/foreground

Detect event when app go to background/foreground Api-level 14+

Usage:

Add the repository to your gradle app

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    compile 'com.github.khirr:Android-Foreground-Detection:1.0.1'
}

Initialize on your Application singleton:

Java

@Override
public void onCreate() {
    super.onCreate();
    //  Initialize
    Foreground.Companion.init(this);
}

Kotlin

override fun onCreate() {
   super.onCreate()
   Foreground.init(this)
}

You can check status anytime

Java

Foreground.Companion.isForeground();
Foreground.Companion.isBackground();

Kotlin

Foreground.isBackground()
Foreground.isForeground()

You can add events to listen when status changes

Java

final Foreground.Listener foregroundListener = new Foreground.Listener() {
    @Override
    public void foreground() {
        Log.e("Foreground", "Go to foreground");
    }

    @Override
    public void background() {
        Log.e("Foreground", "Go to background");
    }
};

Foreground.Companion.addListener(foregroundListener);

Kotlin

val foregroundListener = object: Foreground.Listener {
    override fun background() {
        Log.e("Foreground", "Go to background")
    }

    override fun foreground() {
        Log.e("Foreground", "Go to foreground")
    }
}

Foreground.addListener(foregroundListener)

License

MIT

About

A very simple Android way to detect when app go to background/foreground

Resources

License

Stars

Watchers

Forks

Packages

No packages published