android show when the global acquisition activity

Sometimes need to get some tools again in the current instance of activity exhibited operate, afraid of a memory leak, and then find this approach:
listener callbacks from application classes defined in (such as MyApplication.java) registered activity life cycle:

activity lifecycle listener callbacks:

ActivityLifecycleCallbacks callbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            ContextBean.getInstance().setActivity(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) {
           if (activity == ContextBean.getInstance().getActivity()) {
                ContextBean.getInstance().setActivity(null);
            }
        }
    };

Then replication method to register the listener

 @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        registerActivityLifecycleCallbacks(callbacks);
    }

I used here a single example entity class ContextBean class to hold the activity of the current display, static Singleton activity in general should not hold objects, as this can cause a memory leak, however, my single case there is only one activity variable, so singleton objects can store only one activity, because each enters an activity, the singleton will call setActivity () to save the activity, it is saved activity always show the current activity. Since the current show activity there is, it is not a memory leak.

In this way, where I need to just call ContextBean.getInstance (). GetActivity () you can get to the current instance of activity show up.

Attach ContextBean.java:

public class ContextBean {
    private static ContextBean contextBean;
    //我们保持跟目前存活的Activity一致的话,可以无视内存泄漏
    private Activity activity;

    public static ContextBean getInstance() {
        if(contextBean == null) {
            contextBean = new ContextBean();
        }
        return contextBean;
    }

    public Activity getActivity() {
        return activity;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43115440/article/details/89956600