Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A utility class to keep track if your app is in the foreground or background
package com.pantos27.hamburgersforbreakfast
import android.app.Activity
import android.os.Bundle
/**
* A utility class to keep track if your app is in the foreground or background
* without any special permission or API restrictions
* Note that if your app has any activities that run on a different
* process (through the process attribute in your manifest) this utility might not be persistent
*
*/
object ApplicationWatcher : android.app.Application.ActivityLifecycleCallbacks {
private var started : Int? = null
private var resumed : Int? = null
interface StateChangedListener{
fun onForeground()
fun onBackground()
}
var listener: StateChangedListener? = null
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
override fun onActivityStarted(activity: Activity) {
started ?: listener?.onForeground()
started = activity.hashCode()
}
override fun onActivityResumed(activity: Activity) {
started ?: listener?.onForeground()
started = activity.hashCode()
resumed = activity.hashCode()
}
override fun onActivityPaused(activity: Activity) {
if (resumed==activity.hashCode()){
resumed=null
}
}
override fun onActivityStopped(activity: Activity) {
if (started==activity.hashCode()){
started=null
listener?.onBackground()
}
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
}
override fun onActivityDestroyed(activity: Activity) {
}
public fun isAppStarted() = started!=null
public fun isAppResumed() = resumed!=null
}
package com.pantos27.hamburgersforbreakfast
public class MyApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
//register watcher
registerActivityLifecycleCallbacks(ApplicationWatcher.INSTANCE);
ApplicationWatcher.INSTANCE.setListener(new ApplicationWatcher.StateChangedListener() {
@Override
public void onForeground() {
//you're on!
}
@Override
public void onBackground() {
//you're off!
}
});
}
@Override
public void onTerminate() {
super.onTerminate();
//unregister watcher
unregisterActivityLifecycleCallbacks(ApplicationWatcher.INSTANCE);
}
}
@Alarees

This comment has been minimized.

Copy link

@Alarees Alarees commented Jan 27, 2020

hi can you convert this utility ApplicationWatcher.kt only to a java, because am using react native and i want to use this code in android source code

@whalemare

This comment has been minimized.

Copy link

@whalemare whalemare commented Sep 25, 2020

hi can you convert this utility ApplicationWatcher.kt only to a java, because am using react native and i want to use this code in android source code

You can use Kotlin in react native

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment