How to detect when an Android app goes to the background and come back to the foreground

后端 未结 30 1891
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

I am trying to write an app that does something specific when it is brought back to the foreground after some amount of time. Is there a way to detect when an app is sent to

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 01:06

    This appears to be one of the most complicated questions in Android since (as of this writing) Android doesn't have iOS equivalents of applicationDidEnterBackground() or applicationWillEnterForeground() callbacks. I used an AppState Library that was put together by @jenzz.

    [AppState is] a simple, reactive Android library based on RxJava that monitors app state changes. It notifies subscribers every time the app goes into background and comes back into foreground.

    It turned out this is exactly what I needed, especially because my app had multiple activities so simply checking onStart() or onStop() on an activity wasn't going to cut it.

    First I added these dependencies to gradle:

    dependencies {
        compile 'com.jenzz.appstate:appstate:3.0.1'
        compile 'com.jenzz.appstate:adapter-rxjava2:3.0.1'
    }
    

    Then it was a simple matter of adding these lines to an appropriate place in your code:

    //Note that this uses RxJava 2.x adapter. Check the referenced github site for other ways of using observable
    Observable appState = RxAppStateMonitor.monitor(myApplication);
    //where myApplication is a subclass of android.app.Application
    appState.subscribe(new Consumer() {
        @Override
        public void accept(@io.reactivex.annotations.NonNull AppState appState) throws Exception {
            switch (appState) {
                case FOREGROUND:
                    Log.i("info","App entered foreground");
                    break;
                case BACKGROUND:
                    Log.i("info","App entered background");
                    break;
            }
        }
    });
    

    Depending on how you subscribe to the observable, you may have to unsubscribe from it to avoid memory leaks. Again more info on the github page.

提交回复
热议问题