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

后端 未结 30 1347
独厮守ぢ
独厮守ぢ 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:05

    i know its a little late but i think all these answers do have some problems while i did it like below and that works perfect.

    create a activity life cycle callback like this:

     class ActivityLifeCycle implements ActivityLifecycleCallbacks{
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    
        }
    
        @Override
        public void onActivityStarted(Activity activity) {
    
        }
    
        Activity lastActivity;
        @Override
        public void onActivityResumed(Activity activity) {
            //if (null == lastActivity || (activity != null && activity == lastActivity)) //use this condition instead if you want to be informed also when  app has been killed or started for the first time
            if (activity != null && activity == lastActivity) 
            {
                Toast.makeText(MyApp.this, "NOW!", Toast.LENGTH_LONG).show();
            }
    
            lastActivity = activity;
        }
    
        @Override
        public void onActivityPaused(Activity activity) {
    
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
    
        }
    
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    
        }
    
        @Override
        public void onActivityDestroyed(Activity activity) {
    
        }
    }
    

    and just register it on your application class like below:

    public class MyApp extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new ActivityLifeCycle());
    }
    

提交回复
热议问题