ActivityLifecycleCallbacks管理Activity栈(监听home键)

Android在API14之后添加了用于监听应用Activity生命周期的回调接口ActivityLifecycleCallbacks,使用时需要在Application中进行注册。


ActivityLifecycleCallbacks管理Activity栈(监听home键)_第1张图片
image

可以看到ActivityLifecycleCallbacks中的方法跟Activity生命周期方法基本是一致的。

注册与取消注册

public class MyApplication extends Application {
    public static final String TAG = MyApplication.class.getSimpleName();

    /** Activity监听回调 */
    private ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        ....
    };

    @Override
    public void onCreate() {
        super.onCreate();

        //可注册多次,注册多个生命周期回调
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        //Activity管理
        registerActivityLifecycleCallbacks(ActivityManager.getInstance());
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //Android API中没有对此方法的过多解释,不过通常此方法会在app退出是被调用(并不是100%)

        unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks);
    }
}

需要注意的是Android允许注册多个ActivityLifecycleCallbacks,并且同时生效。

优雅的管理Activity

实现ActivityLifecycleCallbacks接口,并创建Activity的任务栈,通过监听回调实现Activity的进栈和出栈。需要在Application中进行注册。

/**
 * Activity管理类
* 需要在Application中调用registerActivityLifecycleCallbacks注册 */ public class ActivityManager implements Application.ActivityLifecycleCallbacks { //Activity栈 private Stack activities = new Stack<>(); private static ActivityManager activityManager; private ActivityManager(){ } /** * 单例 * @return activityManager instance */ public static ActivityManager getInstance(){ if(activityManager == null){ synchronized (ActivityManager.class){ if(activityManager == null){ activityManager = new ActivityManager(); } } } return activityManager; } /** * 获取Activity任务栈 * @return activity stack */ public Stack getActivityStack(){ return activities; } /** * Activity 入栈 * @param activity Activity */ public void addActivity(Activity activity){ activities.add(activity); } /** * Activity出栈 * @param activity Activity */ public void removeActivity(Activity activity){ if(activity != null){ activities.remove(activity); } } /** * 结束某Activity * @param activity Activity */ public void finishActivity(Activity activity){ if(activity != null){ removeActivity(activity); activity.finish(); } } /** * 获取当前Activity * @return current activity */ public Activity getCurrentActivity(){ return activities.lastElement(); } /** * 结束当前Activity */ public void finishActivity(){ finishActivity(activities.lastElement()); } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { addActivity(activity); } @Override public void onActivityStarted(Activity activity) { } @Override public void onActivityResumed(Activity activity) { } @Override public void onActivityPaused(Activity activity) { } @Override public void onActivityStopped(Activity activity) { } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { removeActivity(activity); } }

通过上面的Activity管理栈可以扩展实现如下需求:

  • 监听应用中集成的第三方SDK中的Activity的启动。
  • 可以控制应用中某个Activity被初始化的数量,如商城应用中的商品详情页,避免无限制的创建Activity。
  • 判断应用是否处于前台可见状态,通过onActivityResumed和onActivityPaused回调方法实现。

监听Home键

我们在开发过程中有时候会碰到一些特殊需求需要监听home键,释放一些资源或者销毁activity等。但Home键事件不同于其他普通按键可以通过OnKeyDown、dispatchKeyEvent等按键监听方法捕获处理,Android系统并没有提供直接监听Home键的方法。但是,当按下Home键是系统会发送Intent.ACTION_CLOSE_SYSTEM_DIALOGS广播(多任务键也会发送此广播)。我们可以通过监听此广播,来间接的监听Home键事件。

public class HomeKeyListenerBroadcast extends BroadcastReceiver {
    private Context context;
    private OnHomeKeyPressListener onHomeKeyPressListener;

    private boolean isRegiested = false;

    public HomeKeyListenerBroadcast(Context context){
        this.context = context;
    }

    public HomeKeyListenerBroadcast(Context context, OnHomeKeyPressListener onHomeKeyPressListener){
        this.context = context;
        this.onHomeKeyPressListener = onHomeKeyPressListener;
    }

    public void setOnHomeKeyPressListener(OnHomeKeyPressListener onHomeKeyPressListener){
        this.onHomeKeyPressListener = onHomeKeyPressListener;
    }

    /**
     * 广播注册
     */
    public void registerSelf(){
        if(context != null){
            IntentFilter filter = new IntentFilter();
            filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.registerReceiver(this, filter);
            isRegiested = true;
        }
    }

    /**
     * 广播UnRegister
     */
    public void unRegisterSelf(){
        if(isRegiested){
            context.unregisterReceiver(this);
            isRegiested = false;
        }
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
            String reason = intent.getStringExtra("reason");
            if ("homekey".equals(reason)) {
                // 按下HOME健
                if (onHomeKeyPressListener != null) {
                    onHomeKeyPressListener.onHomeKeyPress();
                }
            } else if ("recentapps".equals(reason)) {
                // 长按HOME键
                if (onHomeKeyPressListener != null) {
                    onHomeKeyPressListener.onRecentAppsKeyLongPress();
                }
            }
        }
    }

    /**
     * 事件回调接口
     */
    public interface OnHomeKeyPressListener{
        void onHomeKeyPress();
        void onRecentAppsKeyLongPress();
    }
}

代码很简单,不做过多解释了。需要注意的是此广播肯定是动态注册的,在需要的Activity中进行注册并监听按键事件,记得要在onDestroy中取消注册。

你可能感兴趣的:(ActivityLifecycleCallbacks管理Activity栈(监听home键))