Android checking whether the app is closed

后端 未结 6 1532
孤独总比滥情好
孤独总比滥情好 2020-12-03 12:52

I have an android application i need one function or any broadcast receiver that can check if the app is closed.. i don\'t need to call on destroy in every activity (there i

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 13:37

    This answer uses ProcessLifecycleOwner to detect application visibility.

    which is a part of Android Architecture Component .


    1. add this lib to your project

    implementation "android.arch.lifecycle:extensions:1.1.1"

    2. Extend an application class that implements LifecycleObserver

    public class AppController extends Application implements LifecycleObserver {
    
    
    ///////////////////////////////////////////////
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        public void onEnterForeground() {
            Log.d("AppController", "Foreground");
            isAppInBackground(false);
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void onEnterBackground() {
            Log.d("AppController", "Background");
            isAppInBackground(true);
        }
    ///////////////////////////////////////////////
    
    
    
        // Adding some callbacks for test and log
        public interface ValueChangeListener {
            void onChanged(Boolean value);
        }
        private ValueChangeListener visibilityChangeListener;
        public void setOnVisibilityChangeListener(ValueChangeListener listener) {
            this.visibilityChangeListener = listener;
        }
        private void isAppInBackground(Boolean isBackground) {
            if (null != visibilityChangeListener) {
                visibilityChangeListener.onChanged(isBackground);
            }
        }
        private static AppController mInstance;
        public static AppController getInstance() {
            return mInstance;
        }
    
       
       
        @Override
        public void onCreate() {
            super.onCreate();
    
            mInstance = this;
    
            // addObserver
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
    }
    

    And use it like this:

    AppController.getInstance().setOnVisibilityChangeListener(new ValueChangeListener() {
        @Override
        public void onChanged(Boolean value) {
            Log.d("isAppInBackground", String.valueOf(value));
        }
    });
    

    Don't forget to add application name into your manifest

    
    

    Done.


    (Kotlin example)

    https://github.com/jshvarts/AppLifecycleDemo

提交回复
热议问题