美文网首页android 技术知识
android中判断应用是否在前台

android中判断应用是否在前台

作者: 追梦小乐 | 来源:发表于2018-05-02 19:46 被阅读2次

    文章转载于(内容也是从下面出来)
    https://blog.csdn.net/zhufuing/article/details/53007705

    1、编写MyLifecycleHandler.java文件

    public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
        private static int resumed;
        private static int paused;
        private static int started;
        private static int stopped;
    
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }
    
        @Override
        public void onActivityStarted(Activity activity) {
            ++started;
        }
    
        @Override
        public void onActivityResumed(Activity activity) {
            ++resumed;
        }
    
        @Override
        public void onActivityPaused(Activity activity) {
            ++paused;
            android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
            ++stopped;
            android.util.Log.w("test", "application is visible: " + (started > stopped));
        }
    
        @Override
        public void onActivityDestroyed(Activity activity) {
        }
    
        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
    
        public static boolean isApplicationVisible() {
            return started > stopped;
        }
    
        public static boolean isApplicationInForeground() {
        // 当所有 Activity 的状态中处于 resumed 的大于 paused 状态的,即可认为有Activity处于前台状态中 
            return resumed > paused;
        }
    }
    

    2、自己定义的Application中注册

    registerActivityLifecycleCallbacks(new MyLifecycleHandler());
    

    3、调用方法判断

    boolean inForeground = MyLifecycleHandler.isApplicationInForeground();
    

    相关文章

      网友评论

        本文标题:android中判断应用是否在前台

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