What's the difference between extending MultiD

2019-07-31 06:27发布

问题:

From the documentation, I read that there are two ways to support MultiDex in devices below API 21:

  1. Having the Application class extend MultiDexApplication, and
  2. Using MultiDex.install(this) in the Application class's onAttachBaseContext(Context base) function in case the Application extends something else.

Are they basically the same with extending MultiDexApplication calling MultiDex.install(this) in the onAttachBaseContext() by default, or are there differences between both methods?

回答1:

they are two ways to enable multidex for your app and they are completely same

if you want to create a class for application just for enable multidex you can just put MultiDexApplication for application name in AndroidManifest and don't need to do more because in MultiDexApplication overrided attachBaseContext() , look :

public class MultiDexApplication extends Application {
    public MultiDexApplication() {
    }

    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

and if you have application class end it extends just Application you also can change extends to MultiDexApplication instead of ovverride attachBaseContext() method , otherwise you have application class that it doesn't extends from Application, so you have to override attachBaseContext() and your custom Application class



回答2:

Like you mentioned it's a two "different" approach to solve a "single" problem

The problem with the first approach (i.e extending MultiDexApplication) might be not possible in some cases. like you want to extend your application with some other base class from some library. Since multiple Inheritance is not supported in Java, Android provided the other way to solve the issue and that is "MultiDex.install(this)"



回答3:

In some projects you may do not have possibility to do Application class extends MultiDexApplication (for example if your Application already extends some other class). In that case you steel can use MultiDex.install(this) in your Application class.