美文网首页
监听应用的前后台切换

监听应用的前后台切换

作者: 狂奔的_土豆 | 来源:发表于2020-10-19 15:55 被阅读0次
    public class LifecycleCallback implements Application.ActivityLifecycleCallbacks {
        private static final String TAG = "LifecycleCallback";
        private int count; 
        private boolean isForeground; 
    
        public boolean isForeground() {
            return isForeground; 
        }
         
         /**
         * 运行在主线程,如果需要添加一些相对耗时的操作,最好是在子线程操作
         */
        @Override 
        public void onActivityStarted(Activity activity) { 
            count ++; 
             isForeground = false; 
        }
        @Override 
        public void onActivityStopped(Activity activity) { 
            count --; 
            if(count == 0) {
                isForeground = true; 
            }else{
                isForeground = false; 
            }
        }
    
    public class MyApplication extends Application {
        @Override 
        public void onCreate() {
            super.onCreate(); 
            //注册回调
            LifecycleCallback callbacks = new LifecycleCallback();
            registerActivityLifecycleCallbacks(callbacks); 
        }
    }
    

    相关文章

      网友评论

          本文标题:监听应用的前后台切换

          本文链接:https://www.haomeiwen.com/subject/geokmktx.html