Application Level onResume Android

前端 未结 4 798
粉色の甜心
粉色の甜心 2021-01-12 03:54

Problem

The idea is very simple. Whenever an user comes back to my app from the Recents I want to show a simple dialog prompting with the password.<

4条回答
  •  走了就别回头了
    2021-01-12 04:24

    Try below sample

        /**
     * TODO : After update to API level 14 (Android 4.0),
     * We should implement Application.ActivityLifecycleCallbacks
     */
    public class GlobalApplication extends android.app.Application
    {
        private boolean inForeground = true;
        private int resumed = 0;
        private int paused = 0;
    
        public void onActivityResumed( Activity activity )
        {
            ++resumed;
    
            if( !inForeground )
            {
                // Don't check for foreground or background right away
                // finishing an activity and starting a new one will trigger to many
                // foreground <---> background switches
                //
                // In half a second call foregroundOrBackground
            }
        }
    
        public void onActivityPaused( Activity activity )
        {
            ++paused;
    
            if( inForeground )
            {
                // Don't check for foreground or background right away
                // finishing an activity and starting a new one will trigger to many
                // foreground <---> background switches
                //
                // In half a second call foregroundOrBackground
            }
        }
    
        public void foregroundOrBackground()
        {
            if( paused >= resumed && inForeground )
            {
                inForeground = false;
            }
            else if( resumed > paused && !inForeground )
            {
                inForeground = true;
            }
        }
    }
    

    Put below code in your all activities.

      public class BaseActivity extends android.app.Activity
    {
        private GlobalApplication globalApplication;
    
        @Override
        protected void onCreate()
        {
            globalApplication = (GlobalApplication) getApplication();
        }
    
        @Override
        protected void onResume()
        {
            super.onResume();
            globalApplication.onActivityResumed(this);
        }
    
        @Override
        protected void onPause()
        {
            super.onPause();
            globalApplication.onActivityPaused(this);
        }
    
        @Override
        public void onDestroy()
        {
            super.onDestroy();
        }
    }
    

提交回复
热议问题