关闭

Android前后台判断

标签: Android前后台判断Android如何判断前台还是后台
217人阅读 评论(0) 收藏 举报
分类:

在开发中来判断前后台,往往用到最多的就是推送,因为奇葩的需求,比如说,手机在前台时,推送的提示弹出一个对话框,在后台时就显示在通知栏中,当然了判断前后台的代码网上有太多太多,有的是定义一个静态的变量,在父类中进行赋值,这样做是可取的,但是如果有很多父类,还有就是,我们应用跳到了别的应用里,打开的不是我们的页面,那么这时的推送就是错误的,下面这种可以完美的判断是否在前后台,而且处于什么样的状态也能判断。

首先呢我们先定义一个枚举类,来定义我们需要的相应的参数:

/**
 * Created by xiaoming.li on 2016/8/30.
 */
public enum ApplicationLifecycle {
    Created, Started, Resumed, Paused, Stopped, SaveInstanceState, Destroyed
}
定义一个类实现Application.ActivityLifecycleCallbacks这个接口来监听各个Activity的运行状态(必须4.0之后方可以用):

/**
 * Created by xiaoming.li on 2016/8/30.
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class MyActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks{
    private int foregroundActivites = 0;
    private boolean isChangingConfiguration;

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (!isChangingConfiguration) {
            foregroundActivites++;
            if (foregroundActivites == 1) {
                MyApplication.setApplicationLifecycle(ApplicationLifecycle.Started);
            }
        }
        isChangingConfiguration = false;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        isChangingConfiguration = activity.isChangingConfigurations();
        if (!isChangingConfiguration) {
            foregroundActivites--;
            if (foregroundActivites == 0) {
                MyApplication.setApplicationLifecycle(ApplicationLifecycle.Stopped);
            }
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
在Application的onCreate方法里进行注册:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
    registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
}

定义一个变量重写get set方法:

private static ApplicationLifecycle mLifecycle = ApplicationLifecycle.Stopped;
public static void setApplicationLifecycle(ApplicationLifecycle lifecycle) {
    mLifecycle = lifecycle;
}
public static ApplicationLifecycle getApplicationLifecycle() {
    return mLifecycle;
}

这样我们在用到的地方就可以直接对各个状态进行判断了

if (MyApplication.getApplicationLifecycle() == ApplicationLifecycle.Started) { }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:33123次
    • 积分:1012
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:2篇
    • 译文:0篇
    • 评论:55条
    更多技术请关注我的微信公众号
    文章分类