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

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

    I have created a project on Github app-foreground-background-listen

    Create a BaseActivity for all Activity in your application.

    public class BaseActivity extends Activity {
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    
        public static boolean isAppInFg = false;
        public static boolean isScrInFg = false;
        public static boolean isChangeScrFg = false;
    
        @Override
        protected void onStart() {
            if (!isAppInFg) {
                isAppInFg = true;
                isChangeScrFg = false;
                onAppStart();
            }
            else {
                isChangeScrFg = true;
            }
            isScrInFg = true;
    
            super.onStart();
        }
    
        @Override
        protected void onStop() {
            super.onStop();
    
            if (!isScrInFg || !isChangeScrFg) {
                isAppInFg = false;
                onAppPause();
            }
            isScrInFg = false;
        }
    
        public void onAppStart() {
    
            // Remove this toast
            Toast.makeText(getApplicationContext(), "App in foreground",    Toast.LENGTH_LONG).show();
    
            // Your code
        }
    
        public void onAppPause() {
    
            // Remove this toast
            Toast.makeText(getApplicationContext(), "App in background",  Toast.LENGTH_LONG).show();
    
            // Your code
        }
    }
    

    Now use this BaseActivity as a super class of all your Activity like MainActivity extends BaseActivity and onAppStart will be called when you start your application and onAppPause() will be called when the application goes the background from any screen.

提交回复
热议问题