Reprint Please specify source: http://blog.csdn.net/finddreams/article/details/50849385#0-qzone-1-61707-d020d2d2a4e8d1a374a433f596ad1440
Share together and make progress together. finddreams:http://blog.csdn.net/finddreams/article/details/50849385
As we all know, the core of mobile app is to call the background interface, display relevant information, so that we can interact with the outside world on the mobile phone. So the construction of the network framework in the app has always been a concern for our developers, and there are two ways to build a network framework in Android: one that doesn't want to reinvent the wheel using third-party open-source web frameworks, and the second is to build a wheel-like package of its own network framework.
Self-encapsulation implementation of the network framework This behavior is good, but it requires a relatively high capacity, and many times we do not have that ability to encapsulate it well enough. This is not a good thing when we use an open source network framework, and GitHub's well-known network framework has been validated by many apps, which in a sense is very much in line with our actual project development needs.
There are several well-known open-source network frameworks in Android development, such as Android-async-http,volley,okhttp, and the Xutils rapid development framework developed by the Chinese people is also more popular. Android-async-http is a very old-style network framework, very classic. Volley the official recommendation, needless to say. Okhttp can be said to be a rising star, now very popular, Android system underlying API are useful, so is very niubility.
Many of our developers are in small companies, don't understand how big companies do Android Web frameworks, and want to know what technologies are used by millions of apps, and here are two images that let's look at what technology the Android version of American and Uber uses.
Uber in the United States
After reading you will find that these users of billions of apps have also used a lot of open-source framework, and most of these open source framework is in fact we usually in the development of commonly used, not unfamiliar. Perhaps most people to retrofit,rxjava these are not too familiar with, that words do not say, today we talk about how to use Retrofit2.0+rxjava+dragger2 to achieve the Android network architecture, to provide a way for everyone to reference.
Retrofit2.0 Github:https://github.com/square/retrofit
Square developed a type-safe rest Android client request library, and the network request is okhttp by default, please see the tutorial for details.
RxJava +rxandroid GitHub Address: Https://github.com/ReactiveX/RxJava
Rxjava is a responsive programming framework that employs observer design patterns. The core is the observables (the Observer, the event source) and the Subscribers (Observer) of these two things, Rxandroid is Rxjava on Android implementation.
Dragger2
is a dependency injection framework, can greatly save our code volume, easy to maintain.
Here I will not pay too much ink to introduce three things, today's topic is to provide a way to build a different network framework of ideas. If the reader is not familiar with these three frameworks, you can make a self-Google brain repair.
First of all, we started to introduce these frameworks into our project as a dependent library and add them to the App/build.gradle file.
Apply plugin: ' com.android.application ' Apply plugin: ' Com.neenbedankt.android-apt ' Android {compilesdkversion ' Bui Ldtoolsversion "23.0.2" defaultconfig {applicationid "Com.finddreams.retrofit" minsdkversion Argetsdkversion Versioncode 1 Versionname "1.0"} buildtypes {release {Minifyen abled false Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '}}}de pendencies {compile filetree (include: [' *.jar '], dir: ' Libs ') Testcompile ' junit:junit:4.12 ' compile ' com.androi d.support:appcompat-v7:23.1.1 '//retrofit compile ' com.squareup.retrofit2:retrofit:2.0.0-beta4 '//gson parsing compi Le ' com.squareup.retrofit2:converter-gson:2.0.0-beta4 '//rxjava compile ' io.reactivex:rxandroid:1.1.0 ' compile ' C Om.squareup.retrofit2:adapter-rxjava:2.0.0-beta4 '//dragger2 provided ' org.glassfish:javax.annotation:10.0-b28 ' a PT ' Com.google.dagger:dagger-compiler:2.0.2 ' compile ' com.google.dagger:dagger:2.0.2 '}
Because Dragger2 is annotation-based, it will pre-generate some class files, so you need to add apt tools to the/build.gradle file for the entire project:
buildscript { repositories { jcenter() } dependencies { classpath ‘com.android.tools.build:gradle:2.0.0-beta6‘ classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘ // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }}allprojects { repositories { jcenter() }}task clean(type: Delete) { delete rootProject.buildDir}
Then start writing a singleton class that provides retrofit:
/** * Retrofit entity class */public class Restapiadapter {private static Retrofit Retrofit = null; public static Retrofit getinstance () {if (Retrofit = = null) {gsonconverterfactory gsonconverterfactory = Gsonconverterfactory.create (); Okhttpclient okhttpclient = new Okhttpclient (); Okhttpclient.builder Builder = Okhttpclient.newbuilder (); Builder.retryonconnectionfailure (TRUE); Retrofit = new Retrofit.builder (). Client (okhttpclient). BASEURL (Constantapi.baiduurl) . Addconverterfactory (Gsonconverterfactory). Addcalladapterfactory (Rxjavacalladapterfactory.create ()) . build (); } return retrofit; }}
Addcalladapterfactory (Rxjavacalladapterfactory.create ()) This method is the key to the combination of Rxjava and retrofit.
Then we provide a service interface for retrofit, declaring API interface address and required parameters, here we use the weather interface provided by the Baidu API, the implementation of the city name to query the weather function, interface address: http://apistore.baidu.com/ The apiworks/servicedetail/112.html code is as follows:
/** * 天气接口Api */public interface WeatherApiService { /** * 查询天气 */ @GET("apistore/weatherservice/cityname") Observable<WeatherResultBean> queryWeather(@Header("apikey") String apikey, @Query("cityname") String cityname);}
Returning a observable the Observer/event source means handing over to Rxjava.
Then we write a basesubsribe observer to manage the network request beginning to end, success and failure:
/** * 观察者 * * @author finddreams * @address http://blog.csdn.net/finddreams */public abstract class BaseSubsribe<T> extends Subscriber<T> { private static final String TAG = "BaseSubsribe"; @Override public void onStart() { super.onStart(); Log.i(TAG, "onStart"); } @Override public void onNext(T t) { Log.i(TAG, "response" + t.toString()); onSuccess(t); } @Override public void onCompleted() { Log.i(TAG, "onCompleted"); } public abstract void onSuccess(T result); @Override public void onError(Throwable e) { e.printStackTrace(); Log.i(TAG, "onError" + e.getMessage()); }}
Then we write a weatherinteractor interface to connect the service class:
/** * 获取天气信息接口 * * @author finddreams * @address http://blog.csdn.net/finddreams */public interface WeatherInteractor { Subscription queryWeather(String apikey, String cityname, BaseSubsribe<WeatherResultBean> subsribe);}
Then there is the implementation class for this interface:
/** * 获取天气信息实现类 */public class WeatherInteractorImpl implements WeatherInteractor { private final WeatherApiService api; @Inject public WeatherInteractorImpl(WeatherApiService myApi) { this.api = myApi; } @Override public Subscription queryWeather(String apikey, String cityname, BaseSubsribe<WeatherResultBean> subsribe) { Observable<WeatherResultBean> observable = api.queryWeather(apikey, cityname); Subscription subscribe = observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subsribe); return subscribe; }}
Next is how to use Dragger2, know that Dragger2 know there are several concepts, one is module: mainly provide dependent objects such as context, REST API ... ; one is @inject: annotations, used where the dependent objects are needed, and the other is componet: Used to connect module and @inject
First define a module class that provides the objects that need to be injected:
/** * Module类 * 提供需要注入的类 * * @author finddreams * @address http://blog.csdn.net/finddreams */@Modulepublic class InteractorModule { @Provides public Retrofit provideRestAdapter() { return RestApiAdapter.getInstance(); } @Provides public WeatherApiService provideHomeApi(Retrofit restAdapter) { return restAdapter.create(WeatherApiService.class); } @Provides public WeatherInteractor provideHomeInteractor(WeatherApiService myApi) { return new WeatherInteractorImpl(myApi); }}
Next is to write a componet class:
/** * 声明AppComponent组件 * * @author finddreams * @address http://blog.csdn.net/finddreams */@Singleton@Component( modules = { InteractorModule.class, })public interface AppComponent { void inject(App app); WeatherInteractor getWeatherInteractor();}
Then we initialize this appcomponent in application:
/** * Application类 * * @author finddreams * @address http://blog.csdn.net/finddreams */public class App extends Application { private AppComponent component; @Override public void onCreate() { super.onCreate(); setDraggerConfig(); } public AppComponent component() { return component; } public static App get(Context context) { return (App) context.getApplicationContext(); } /** * 初始化Dragger,DaggerAppComponent是自动生成,需要Rebuild */ private void setDraggerConfig() { component = DaggerAppComponent.builder().interactorModule(new InteractorModule()) .build(); component.inject(this); }}
It is important to note that because Dagger2 is precompiled to generate a class, we need to rebuild the project before generating the Daggerappcomponent class. If it appears in development
import com.finddreams.retrofit.api.config.DaggerAppComponent;找不到这个类的错误
Then you need to re-rebuild the project.
This is the class file generated after the Rebuild project,
We can start using it in the activity:
/** * Home * * @author finddreams * @address http://blog.csdn.net/finddreams */public class Mainactivity extends Appcompatac tivity {private AppComponent component; Private Weatherinteractor Weatherinteractor; Private EditText City; Private TextView QueryResult; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); City = (EditText) Findviewbyid (r.id.city); QueryResult = (TextView) Findviewbyid (R.id.queryresult); Gets the Appcomponent component component = App.get (this). Component (); Get Weatherinteractor weatherinteractor by appcomponent = Component.getweatherinteractor (); Findviewbyid (r.id.query). Setonclicklistener (New View.onclicklistener () {@Override public void oncli CK (View v) {queryweatherdata (); } }); } public void Queryweatherdata () {String content = City.gettexT (). toString (); Method of invoking the query weather interface Subscription Subscription = Weatherinteractor.queryweather (constantapi.baidukey, content, new basesub Sribe<weatherresultbean> () {@Override public void onsuccess (Weatherresultbean Result) {weatherresultbean.retdataentity retdata = Result.getretdata (); Queryresult.settext (retdata.getcity () + ":" + retdata.getweather () + ":" + retdata.getdate ()); } @Override public void OnError (Throwable e) {super.onerror ( e); Queryresult.settext ("Query failed"); } } ); Cancellation request//Subscription.unsubscribe (); }}
我们看下项目运行的结果图:
Attach the source code to a friend in need of reference, compare with the source code to understand more thoroughly, github:https://github.com/finddreams/retrofit2_rxjava_dagger2
Build Android network architecture based on RETROFIT2.0+RXJAVA+DRAGGER2 (reprint)