Checking if an Android application is running in the background

前端 未结 30 2840
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  情歌与酒
    2020-11-21 07:13

    The only one correct solution:

    MainActivity.java:

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            MyApp.mainActivity = this;
            super.onCreate(savedInstanceState);
            ...
        }
    

    MyApp.java:

    public class MyApp extends Application implements LifecycleObserver {
    
        public static MainActivity mainActivity = null;
    
        @Override
        public void onCreate() {
            super.onCreate();
            ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        void onAppBackgrounded() {
            // app in background
            if (mainActivity != null) {
                ...
            }
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        void onAppForegrounded() {
            // app in foreground
            if (mainActivity != null) {
                ...
            }
        }
    
    }
    

提交回复
热议问题