Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when an Android application is minimized?

How to detect when an Android app goes to the background? onPause() or onUserLeaveHint() works but are also called when the orientation is changed or another activity is presented.

like image 657
Agshin Huseynov Avatar asked Sep 22 '16 12:09

Agshin Huseynov


People also ask

How do I see which apps are closed on Android?

The "onActivityDestroyed" will get called when the app is closed, so if you can check if the app is in background when it is called (so the app is already closed) you can grep exactly the moment when the app is being closed.

What happens when app goes into background?

An app is running in the background when both the following conditions are satisfied: None of the app's activities are currently visible to the user. The app isn't running any foreground services that started while an activity from the app was visible to the user.


2 Answers

The marked answer is a workaround for the OP's question. For the rest of us that are looking for an answer you can achieve this using Android Architecture Components

import android.arch.lifecycle.LifecycleObserver;

class OurApplication extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onAppBackgrounded() {
        Logger.localLog("APP BACKGROUNDED");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onAppForegrounded() {
        Logger.localLog("APP FOREGROUNDED");
    }
}

and remember to update the manifest file. set the android:name=".OurApplication" attribute for the <application> tag

like image 123
DoruChidean Avatar answered Oct 05 '22 10:10

DoruChidean


If orientation changes the app will call through the life cycle once again that means from oncreate

you can avoid it as well by writing the following to code to the manifest

 <activity
      android:name=""
      android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
      android:label="@string/app_name" />

this tell the system that when orientation changes or keyboardHidden or screenLayout changes I will handle it by myself no need to re create it.

then write your code on on pause

like image 45
Joyal C Joseph Avatar answered Oct 05 '22 10:10

Joyal C Joseph