Android--Take you from the source point of view Dagger2 Introduction to give Up (iii)

Source: Internet
Author: User

1, in the first two articles we know how to use the four commonly used tags, now we combine our own projects to simple use

When we build the project, we will usually create our own application, in which some initialization such as some third-party Greendao, SHARESDK, and so on, or provide some common properties initialization: For example, to initialize the width of the screen, initialize the Sputils tool class, etc. , so we can create an app class that inherits from application (here I write only simple app object creation, no other method written)

Package Com.qianmo.rxjavatext;import android.app.application;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */public class app extends application {public    static app instance;    public static synchronized App getinstance () {        return instance;    }    @Override public    void OnCreate () {        super.oncreate ();        instance = this;    }}

 In general, we use the context in many cases, and the context in which the activity is used is prone to a memory leak problem in which the activity should have been destroyed, but because the external class holds a reference to the context object, the activity cannot be recycled. So here we generally use the context of the app, when we want to provide a application context object to all the activity, and then combine the Dagger2 knowledge we learned before, write the code appmodule provide the object first

Package Com.qianmo.rxjavatext.di;import Com.qianmo.rxjavatext.app;import Javax.inject.singleton;import Dagger. Module;import Dagger. provides;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */@Modulepublic class Appmodule {public    final APP application;    Public Appmodule (App application) {        this.application = Application;    }    @Provides    @Singleton    App provideapplicationcontext () {        return application;    }}

  It's easy to pass in the App object when you create the Appmodule object, and then add Provideapplicationcontext to expose the app object and then look at the Appcomponent class

Package Com.qianmo.rxjavatext.di;import Com.qianmo.rxjavatext.app;import Javax.inject.singleton;import Dagger. component;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */@Singleton @component (modules = appmodule.class) public interface AppComponent {    // Provide contextual    App GetContext () to the lower level;

  There may be a question about the app GetContext (), what this code does, and we know that it's possible to use the app context in the activity (although this method is not necessarily available, but we are still ready), here is to provide this object to the lower layer. Then we need to initialize the Appcomponent object in the app.

public class App extends application {public    static app instance;    public static AppComponent AppComponent;    public static synchronized App getinstance () {        return instance;    }    @Override public    void OnCreate () {        super.oncreate ();        instance = this;    }    public static AppComponent Getappcomponent () {        if (AppComponent = = null) {            AppComponent = Daggerappcomponent.builder (). Appmodule (New Appmodule (instance)). Build ();        }        return appComponent;}    }

  Then there are students will have this question what is called "the lower layer", with what represents the upper and lower relations, the explanation given here is when another activity module also want to have our context Application object? Do we still have to think of our appmodule? NoNoNo, this is the module where we use dependencies to create the activity first, and this class is very simple to provide our activity object, so the code is as follows

Package Com.qianmo.rxjavatext.di;import Android.app.activity;import Com.qianmo.rxjavatext.di.scope.ActivityScope; Import Javax.inject.singleton;import Dagger. Module;import Dagger. provides;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */@Modulepublic class Activitymodule {    private Activity mactivity;    Public Activitymodule (Activity mactivity) {        this.mactivity = mactivity;    }    @Provides    @ActivityScope    Activity provideactivity () {        return mactivity;    }}

  Here @activityscope is our last study of the custom scope annotation tag, no hard, and then look at our activitycomponent

Package Com.qianmo.rxjavatext.di;import Android.app.activity;import Com.qianmo.rxjavatext.mainactivity;import Com.qianmo.rxjavatext.di.scope.activityscope;import dagger.component;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email Protected] * * @ActivityScope @component (dependencies = Appcomponent.class,modules = Activitymodule.class) public interface Activitycomponent {    //The current activity is exposed to    activity getactivity ();    void inject (mainactivity mainactivity);}

  The Dependencies keyword is used in this way, such as when we create a student object, we need the object of the app (which, of course, is not true in reality), and we can write the module

Package Com.qianmo.rxjavatext.di;import Android.app.activity;import Android.content.context;import Com.qianmo.rxjavatext.student;import Com.qianmo.rxjavatext.di.scope.activityscope;import Javax.inject.Singleton; Import Dagger. Module;import Dagger. provides;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */@Modulepublic class Activitymodule {    private Activity mactivity;    Public Activitymodule (Activity mactivity) {        this.mactivity = mactivity;    }    @Provides    @ActivityScope    Activity provideactivity () {        return mactivity;    }    @Provides    Student providestudent (APP) {        return new Student (app);}    }

  We press CTRL+F9 compiled, found that our program can be compiled, normal words should not be reported wrong to say the app is not injected object, why here is can run, this is the use of dependencies keyword, Here we use the App object of the GetContext method in Appcomponent.

OK, here we start in activity to try to create a student object to see if we can get the value

Package Com.qianmo.rxjavatext;import Android.support.v7.app.appcompatactivity;import Android.os.Bundle;import Android.util.log;import Android.view.view;import Android.widget.button;import Android.widget.CheckBox;import Android.widget.listview;import Android.widget.textview;import Android.widget.toast;import Com.jakewharton.rxbinding.view.rxview;import Com.jakewharton.rxbinding.widget.rxcompoundbutton;import Com.qianmo.rxjavatext.di.activitycomponent;import Com.qianmo.rxjavatext.di.activitymodule;import Com.qianmo.rxjavatext.di.daggeractivitycomponent;import Java.util.collections;import Java.util.List;import Java.util.concurrent.timeunit;import javax.inject.inject;import Rx. Observable;import Rx. Subscriber;import Rx.android.schedulers.androidschedulers;import Rx.functions.action0;import Rx.functions.Action1 , import Rx.functions.func1;import Rx.schedulers.schedulers;public class Mainactivity extends Appcompatactivity {//requires a    A Student object @Inject Student mstudent; @Override Protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Initinject ();    }//Start annotation public void Initinject () {getactivitycomponent (). inject (this); } protected Activitycomponent Getactivitycomponent () {return Daggeractivitycomponent.builder ().    AppComponent (App.getappcomponent ()). Activitymodule (Getactivitymodule ()). build ();    } protected Activitymodule Getactivitymodule () {return new activitymodule (this); }}

  Run for a look at the print results

04-21 05:36:19.510 2646-2646/com.qianmo.rxjavatext i/system.out: Print Context object Yes [email protected]

  No problem, our program is not a problem, but in the actual project we are to write baseactivity, so we need to write in baseactivity

Public abstract class Baseactivity<t extends Basepresenter> extends appcompatactivity implements Baseview {@Inje    CT protected T mpresenter;        protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (GetLayout ());        Initinject ();        if (mpresenter! = null) Mpresenter.attachview (this);        App.getinstance (). addactivity (this);    Initeventanddata ();    } @Override protected void OnStart () {Super.onstart ();    } @Override protected void OnDestroy () {Super.ondestroy ();    }/** * Add note */protected abstract void initinject ();    protected abstract int getlayout ();    protected abstract void Initeventanddata (); Protected Activitycomponent getactivitycomponent () {return Daggeractivitycomponent.builder (). Appco Mponent (App.getappcomponent ()). Activitymodule (Getactivitymodule ()). BuilD ();    } protected Activitymodule Getactivitymodule () {return new activitymodule (this); }}

Baseview and Basepresenter here are the base classes of our MVP, which is very simple without code, How do we use it in specific activity? First create the mainactivity, where you call the  mpresenter.attachview (new MainView ()) method

Package Com.qianmo.rxjavatext.mvp.view;import Com.qianmo.rxjavatext.r;import Com.qianmo.rxjavatext.base.baseactivity;import com.qianmo.rxjavatext.mvp.presenter.mainpresenterimpl;/** * Created by Administrator on 2017/4/21 0021. * E-mail:[email protected] */public class Secondactivity extends baseactivity<mainpresenterimpl> {    @Override Public    void ShowError (String msg) {    }    @Override public    void Usenightmode (Boolean isnight) {    }    @Override    protected void Initinject () {        getactivitycomponent (). inject (this);    }    @Override    protected int getlayout () {        return r.layout.activity_main;    }    @Override    protected void Initeventanddata () {        Mpresenter.attachview (new MainView ());}    }

  And look at the important Mainpresenterimpl class.

Package Com.qianmo.rxjavatext.mvp.presenter;import Android.content.context;import Android.widget.toast;import Com.qianmo.rxjavatext.app;import Com.qianmo.rxjavatext.base.basepresenter;import Com.qianmo.rxjavatext.mvp.view.mainview;import javax.inject.inject;import Rx. Observable;import Rx. Subscriber;import Rx. subscription;/** * Created by Mvphelper on 2016/11/08 */public class Mainpresenterimpl implements Basepresenter<mainvi ew> {    private context context;    @Inject public    Mainpresenterimpl (app app) {        this.context = app;    }    @Override public    void Attachview (MainView view) {        Toast.maketext (context, "Get to Value", Toast.length_short). Show ( );    }    @Override public    void Detachview () {    }}

  Here the most critical callout of the constructor Mainpresenterimpl, so that we annotate to the presenter object, look at the effect, OK, basically we are in the MVP Project annotated presenter object, the key is the package!!! (If you're well-packaged, it's easy to use it later, and you don't have to write some module or component class separately)

Finally, say the scope of use for small and medium-sized projects really do not need to use Dagger2, and if you are the owner of Android, you have to consider your Android colleagues they get started Dagger2 situation, So here is still to try to develop the situation (feel this piece or not and everyone in the project packaging time to speak clearly ah, hemp eggs, thinking is also chaotic, I wish everyone to drag the pit soon).

Android--Take you from the source point of view Dagger2 Introduction to give Up (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.