Application拆分

2015-12-02  本文已影响207人  EvilsoulM

起因

一个application相关的bug。。。

基类 主要提供和原生application一样的方法

public abstract class BaseMovieApplication {
    private Application application;
    public BaseMovieApplication(Application application) {
        this.application = application;
    }
    public Context getApplicationContext() {
        return this.application.getApplicationContext();
    }
    public Context getContext() {
        return this.application.getApplicationContext();
    }
    public Application getApplication() {        return this.application;
    }
    public abstract void onCreate();
    public void onConfigurationChanged(Configuration newConfig) {
    }
    public void onTerminate() {
    }
    public void onTrimMemory(int level) {
    }
}

主进程

/** *
 Author by mazixuan
 * Data:2015-12-02 15:11
 * Project:aimovie
 * Detail:主进程实例 也就是ui进程 
 */
public class MovieMainProcessApplication extends BaseMovieApplication {
    public MovieMainProcessApplication(Application application) {
        super(application);
    }
    @Override
    public void onCreate() {
        //执行主进程所需要的方法
        //eg 初始化图片库
        // crash 平台等
    }
}

如果要调用application的方法直接调用getApplication()然后再调用你需要的方法即可

getApplication().registerActivityLifecycleCallbacks(new ShowDialogActivityLifecycleCallback());

其他进程一样只要继承BaseMovieApplication即可

Application拆分

public class MovieApplication extends MultiDexApplication {

    private static Context sContext;

    private BaseMovieApplication baseMovieApplication;
    /**
     * 返回当前MovieApplication
     */
    public static Context getContext() {
        return MovieApplication.sContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        MovieApplication.sContext = getApplicationContext();

        if (MtmpManager.isMainProcess(this)) {
            baseMovieApplication = new MovieMainProcessApplication(this);
        } else {
            baseMovieApplication = new MovieSecondProcessApplication(this);
        }

        baseMovieApplication.onCreate();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (baseMovieApplication != null) {
            baseMovieApplication.onTrimMemory(level);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (baseMovieApplication != null) {
            baseMovieApplication.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        if (baseMovieApplication != null) {
            baseMovieApplication.onTerminate();
        }
    }
}

也可以根据进程名进行更多进程的拆分,每个进程实例做对应的初始化操作。这样结构就很清楚了~每个进程执行每个进程的操作,初始化,也不会一个对象因为多个进程,初始化多个。也不需要再担心一个方法会影响别的进程。。。

拆分的好处:
1.避免oncreate等方法调用多次引起的bug
2.减少资源浪费 在一些push进程 可以不初始化 图片库等
3.各尽其职
4.再也不用经常去判断进程

代码
github

上一篇 下一篇

猜你喜欢

热点阅读