Android 开发之ActivityLifecycleCallback

一. 简介

ActivityLifecycleCallbacks是Application里的一个接口,在Android4.0(API level 14)中新加。用于监听应用中所有Activity的生命周期的调用情况,callback中的方法会在Activity回调方法之前调用,可以通过实现这个接口来完成一些特殊需求,比如检测APP是否处于前台。

二. 使用

以检测APP是否处于前台为例介绍使用。

1. 实现ActivityLifecycleCallbacks接口

public class ActivityLifecycleCallbackWrapper implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "LifecycleCallback";
    private int count; 
    private boolean isForeground; 

    public boolean isForeground() {
        return isForeground; 
    }

    @Override 
    public void onActivityCreated(Activity activity, Bundle bundle) {
        //to do 
    }

    @Override 
    public void onActivityStarted(Activity activity) { 
        count ++; 
    }

    @Override 
    public void onActivityResumed(Activity activity) {
        //to do 
    }

    @Override 
    public void onActivityPaused(Activity activity) {
        //to do 
    }

    @Override 
    public void onActivityStopped(Activity activity) { 
        count --; 
        if(count == 0) {
            isForeground = true; 
        }
    }

    @Override 
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
        //to do 
    }

    @Override 
    public void onActivityDestroyed(Activity activity) {
        //to do 
    }
}

2. 创建自定义Application,并在Application中注册callback。

public class MyApplication extends Application {
    ActivityLifecycleCallbacks callbacks; 

    @Override 
    public void onCreate() {
        super.onCreate(); 
        callbacks = new ActivityLifecycleCallbackWrapper();

        registerActivityLifecycleCallbacks(callbacks);  // 注册Callback
    }
}

你可能感兴趣的:(Android 开发之ActivityLifecycleCallback)