Utility for detecting and notifying when your Android app goes background / becomes foreground

Related tags

Utility Foredroid
Overview

Foredroid

Download

Utility for detecting and notifying when your Android app goes background / becomes foreground.

API-level 14+.

logo

Usage:

Initialise Foreground as early as possible in the startup of your app:

public void onCreate(Bundle savedInstanceState){
  Foreground.init(getApplication());
}

Any time you want to check if you are foreground or background, just ask:

Foreground.get().isForeground();
Foreground.get().isBackground();

Or, if you want to trigger something as soon as possible when you go background or come back to foreground, implement Foreground.Listener and do whatever you want in response to the callback methods:

Foreground.Listener myListener = new Foreground.Listener(){
  public void onBecameForeground(){
    // ... whatever you want to do
  }
  public void onBecameBackground(){
    // ... whatever you want to do
  }
}

... then register your listener:

listenerBinding = Foreground.get().addListener(listener);

Note that in registering the listener we recorded the Binding that was returned, so that we can unbind it again later:

listenerBinding.unbind();

Maven / Gradle

The .aar file is available from the jcenter repository. Check that you have the jcenter repository in your top-level build.gradle like this:

allprojects {
    repositories {
        jcenter()
    }
}

Add the following dependency to your build.gradle:

compile 'com.sjl:Foredroid:1.0.2'
Comments
  • This library is an error implementation. Here is a simple way to achieve.

    This library is an error implementation. Here is a simple way to achieve.

    public class ApplicationListener implements Application.ActivityLifecycleCallbacks {
    
        private int foregroundCount = 0; 
    
        @Override
        public void onActivityStarted(Activity activity) {
            if (foregroundCount <= 0) {
                // TODO becomes foreground
            }
            foregroundCount++;
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
            foregroundCount--;
            if (foregroundCount <= 0) {
                // TODO goes background
            }
        }
    
        /*
         * The following callbacks, we do not need
         */
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}
    
        @Override
        public void onActivityResumed(Activity activity) {}
    
        @Override
        public void onActivityPaused(Activity activity) {}
    
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
    
        @Override
        public void onActivityDestroyed(Activity activity) {}
    
    }
    

    That is.

    If ActivityA go to ActivityB,the callbacks is :

    A.onPause()
    B.onStart()
    B.onResume()
    A.onStop()
    

    If ActivityB return ActivityA, the callbacks is:

    B.onPause()
    A.onStart()
    A.onResume()
    B.onStop()
    

    So, set a counter to statistics onStart() and onStop() callbacks. if the counter is > 0, Application is in foreground, opposite in background.

    opened by TakWolf 8
  • jcenter entry is bad, and mavenCentral is non-existent

    jcenter entry is bad, and mavenCentral is non-existent

    I tried to use the gradle dependency as: compile 'com.sjl:Foredroid:1.0.1' This package doesn't exist in jcenter or maven-central. Per this page: https://bintray.com/steveliles/maven/Foredroid/1.0.1?versionPath=%2Fsteveliles%2Fmaven%2FForedroid%2F1.0.1

    The package that is available is: compile 'Foredroid:Foredroid:unspecified'

    Can you publish 1.0.2 version that fixes these problems? Thanks.

    opened by inder123 5
  • Crash in weak reference iteration

    Crash in weak reference iteration

    In the weak references to call backs, when iterating over the CopyOnWriteArrayList and the weak reference is pointing to a null, remove() is called on the iterator, which is not allowed and throws an illegal operation exception, which is buried and the item is never removed. Removal has to happen after iteration is complete.

    opened by KennyGoers 4
  • Memory Leak

    Memory Leak

    Hi there. I got a memory leak ( from Canary Leak ) coming from Foreground.current I'm only doing this Foreground.get(application).addListener(foregroundListener) in onCreate and unbinding in onDestroy. Any ideas?

    opened by EscapeArtist 4
  • Fixes a memory leak caused by holding onto the current activity reference beyond destruction

    Fixes a memory leak caused by holding onto the current activity reference beyond destruction

    • The leak occurred whenever the current activity was backgrounded, no new activity was started, and the activity was then destroyed (e.g. switching to another app with DKA enabled). This has been resolved by replacing the current Activity strong reference with a currentActivity weak reference

    Resolves issue #8

    opened by AlgoRyan 3
  • removeListener() cannot found

    removeListener() cannot found

    Hi @steveliles, thank you for this helpful class. But i get the error: "Cannot resolve method: removeListener(com.sjl.foreground.Foreground.Listener)" Can fix this please?

    Thank you

    opened by dipici 2
  • report a bug.

    report a bug.

    the old code when it going to "it.remove();",there is a exception ,"java.lang.UnsupportedOperationException" . The CopyOnWriteArrayList doc describe is “Iterators returned by this list and its sub lists cannot modify the

    • underlying list. In particular, {@link Iterator#remove}, {@link
    • ListIterator#add} and {@link ListIterator#set} all throw {@link
    • UnsupportedOperationException}.”. It doesn't impliment "remove" method.

    This is my solution: private List<WeakReference> listeners = new ArrayList<>();

    Please check this issues ,thank you very much for offering so good tool.

    opened by wustwg 1
  • Observe app state using RxJava

    Observe app state using RxJava

    it was a quick implementation to Observe app state using RxJava event bus. hope this could help to support an Rx way for who is already using RxJava and RxAndroid.

    opened by MohamedISoliman 0
  • listeners called Multiple Times

    listeners called Multiple Times

    the onBecameForeground calls multiple times if you have more than one activity on stack, so if you have three activities on stack, the onBecameForeground calls thrice. how to fix that.

    opened by aurangzaibumer777 0
  • onBecameBackground not called

    onBecameBackground not called

    Implemented same as in sample app. onBecameForeground called onBecameBackground never called. At the time of going background listeners becomes empty (due to weak reference) and thus hasn't been called

    opened by LeoDroidCoder 1
  • onBecameBackground() called when a new Activity is started in the onBecameForeground()

    onBecameBackground() called when a new Activity is started in the onBecameForeground()

    Looks like the delayed check in onActivityPaused() is the reason.

    Foreground thinks it is the background, altough it is in the foreground. Thus onBecameForeground() gets called when the started activity has finshed.

    Only happens if I put the app in the background two times or more.

    opened by AppyxDaniel 0
  • App became Background when request permission.

    App became Background when request permission.

    When I request permission, App became Background. screen shot 2017-05-13 at 15 53 04

    package com.sjl.foreground.demo;
    
    import android.Manifest;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.ActivityCompat;
    import android.support.v4.content.ContextCompat;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import com.sjl.foreground.Foreground;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public abstract class DemoActivity extends ActionBarActivity implements Foreground.Listener {
    
        private Foreground.Binding listenerBinding;
    
        protected abstract void startAnotherActivity();
    
        public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Button button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //startAnotherActivity();
                    //composeEmail(new String[]{"asdasd"},"asdas");
                    ActivityCompat.requestPermissions(DemoActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            1);
                }
            });
    
            listenerBinding = Foreground.get(getApplication()).addListener(this);
        }
    
        public void composeEmail(String[] addresses, String subject) {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            intent.setData(Uri.parse("mailto:")); // only email apps should handle this
            intent.putExtra(Intent.EXTRA_EMAIL, addresses);
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
        }
    
        private  boolean checkAndRequestPermissions() {
            int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.SEND_SMS);
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            List<String> listPermissionsNeeded = new ArrayList<>();
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
            return true;
        }
        @Override
        protected void onDestroy() {
            super.onDestroy();
    
            // not strictly necessary as Foreground only holds a weak reference
            // to the listener to defensively prevent leaks, but its always better
            // to be explicit and WR's play monkey with the Garbage Collector
            listenerBinding.unbind();
        }
    
        @Override
        public void onBecameForeground() {
            Log.d(Foreground.TAG, getClass().getName() + " became foreground");
        }
    
        @Override
        public void onBecameBackground() {
            Log.d(Foreground.TAG, getClass().getName() + " went background");
        }
    
    }
    
    
    opened by chihung93 7
  • Don't update the activity status when a popup is closed(stays in

    Don't update the activity status when a popup is closed(stays in "background")

    everything works fine until you open a dialog, when the dialog is showing the status of activity change to "background" , when the dialog is closed don't update the status . . .

    opened by QiiqeAzuara 0
Releases(v1.0.0)
Owner
Steve Liles
I'm a bit of a geek.
Steve Liles
[Deprecated] Sexy way to execute async/background tasks on Android

Groundy library for Android @Deprecated Unfortunatenly this library is no longer maintained, we encourage you to use other widely supported solutions

Telly 228 Nov 14, 2022
A logger with a small, extensible API which provides utility on top of Android's normal Log class.

This is a logger with a small, extensible API which provides utility on top of Android's normal Log class. I copy this class into all the little apps

Jake Wharton 9.8k Dec 30, 2022
A small utility to record Android device screen to a GIF

RoboGif A small utility to record Android device screen to an optimized GIF so you can paste it to GitHub or a similar service. Requirements Python 2.

Jernej Virag 526 Dec 9, 2022
A collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android.

requireKTX is a collection of small utility functions to make it easier to deal with some otherwise nullable APIs on Android, using the same idea as requireContext, requireArguments, and other similar Android SDK methods.

Márton Braun 82 Oct 1, 2022
Small utility used to add Homewizard Energy Socket tiles to Android Quick Settings

TileWizard [Alpha! Unstable!] Settings Result Functionality: Add up to 5 Wi-Fi Energy Sockets to Android Quick Settings. What do you need: Android dev

Niels Masdorp 2 Oct 19, 2021
Small utility to create/restore encrypted backups

Quick Backup Choose some files and quickly create a complete encrypted and compressed file. Usage Clone the repository Run gradlew installShadowDist T

Leonardo Colman 5 Sep 18, 2021
Utility tool to make you a computer ninja.

Cmd Window Never spend 6 minutes doing something by hand when you can spend 6 hours failing to automate it - Zhuowej Zhang What is this about? This to

Marcin Radoszewski 3 Feb 1, 2022
Small command-line utility to safely merge multiple WhatsApp backups (msgstore.db) into one.

whatsapp-database-merger A small command-line utility that can be used to merge multiple WhatsApp databases (msgstore.db) into one. A few notes: input

Mattia Iavarone 31 Dec 27, 2022
A command line utility to help you investigate the sensitive data associated with Macie findings.

Macie Finding Data Reveal This project contains a command line utility to help you investigate the sensitive data associated with Macie findings.

AWS Samples 8 Nov 16, 2022
Utility library that utilizes KSP to generate Room type converter classes.

Roomie Roomie is an annotation processing library that utilizes KSP to geaRoomie is an annotation processing library that utilizes KSP to generate TypeConverter classes for Room. TypeConverter classes most often involve same boiler-plate code and Roomie makes it really easy to quickly create them with a single annotation.nerate TypeConverter classes for Room. TypeConverter classes most often invol

Chukwuka Eze 12 Aug 26, 2022
CHAOS - Like a utility knife for discord

CHAOS - Like a utility knife for discord. Currently under development. If you feel inclined, please support me by contributing to this project. Or alt

caffeine.moe 20 Nov 13, 2022
Obsi-bot: the next generation discord utility bot 🔥

obsi-bot obsi-bot is the next generation discord utility bot. It is developed in Kotlin using kordex and kord Help me translating Feel free to help me

mooziii 2 Nov 7, 2022
Small Android library to help you incorporate MVP, Passive View and Presentation Model patterns in your app

DroidMVP About DroidMVP is a small Android library to help you incorporate the MVP pattern along with Passive View and Presentation Model (yes, those

Andrzej Chmielewski 225 Nov 29, 2022
Android Shared preference wrapper than encrypts the values of Shared Preferences. It's not bullet proof security but rather a quick win for incrementally making your android app more secure.

Secure-preferences - Deprecated Please use EncryptedSharedPreferences from androidx.security in preferenced to secure-preference. (There are no active

Scott Alexander-Bown 1.5k Dec 24, 2022
PhotoSync - app to backup photos to your own computer

PeopleInSpace Minimal Kotlin Multiplatform project with SwiftUI, Jetpack Compose

Kyle McBurnett 0 Jan 2, 2022
Simple Mobile Tools 172 Dec 26, 2022
A beautiful set of predefined colors and a set of color methods to make your Android development life easier.

Colours is a port of the Colours Library for iOS made by my good friend Ben Gordon. You can find that project here. Installation Maven Central Colours

Matthew York 634 Dec 28, 2022
Android library to easily serialize and cache your objects to disk using key/value pairs.

Deprecated This project is no longer maintained. No new issues or pull requests will be accepted. You can still use the source or fork the project to

Anup Cowkur 667 Dec 22, 2022
[] Define and render UI specs on top of your Android UI

dspec A simple way to define and render UI specs on top of your Android UI. Usage Enclose the target UI with a DesignSpecFrameLayout, usually the root

Lucas Rocha 561 Dec 16, 2022