The framework

The first to introduce

The year 2016 is coming to an end, and Android technology continues to develop, such as HotFix,React-Native,RxJava, etc. It’s also a sign of the transformation of Android since its launch in December 2014 Studio only released the beta version of 0.9, and now the official version of 2.2. The efficiency of plug-ins in development has been constantly improved, from the MVC architecture at the beginning to the MVP and MVVP, so I wrote a “3ROM” framework for everyone to learn and use in the project.

Detailed introduction

What is a Router

The Router is used to control all Activity redirect requests. Why use Router and in what scenarios?

At present, most apps in the market have no login status on their home page. If you do not have a Router, you need to determine whether each clicked module needs to be logged in to use, which makes the code redundant and difficult to maintain. Of course, you said it could be packaged into baseActivity, which is also ok, but it is not perfect.

The Router is more than just a controller. It is also a great tool for team development and collaboration.

When your team assigns everyone to write each module, the Activity may not have been created yet, but this may affect your debugging. If you use the Router, you don’t need to configure the jump rule. If you don’t, it doesn’t affect debugging, etc.

How to Use Router

Just initialize OnCreate in the global APP:

Router.addRouteCreator(new RouterRule()); Private class RouterRule implements RouteCreator {@override public Map createRouteRules() {Map rule = new HashMap<>(); rule.put("Tanck://login", new RouteMap("com.tangce.fastcode.LoginActivity")); // Class name or class, also need to configure the return rule in androidmanifest.xml; }}Copy the code

You can set up Activity interception, which will solve the problem of logging in to the required module and pass data to the required module.

Router.setGlobalRouteCallback(new RouteCallback() { @Override public boolean interceptOpen(Uri uri, Context context, ActivityRouteBundleExtras extras) { Log.d(TAG, "interceptOpen:" + uri.toString()); // TODO GO to LoginActivity return false; } @override public void notFound(Uri Uri, NotFoundException e) {log.d (TAG, "notFound:" + uri.toString()); } @Override public void onOpenSuccess(Uri uri, String clzName) { } @Override public void onOpenFailed(Uri uri, Exception e) { } })Copy the code

I saw how easy it was to use.

What is a RxAndroid

RxAndroid is actually an extension of RxJava, mainly for android thread switching. What’s the use of that?

In fact, is very convenient chain programming, and thread switching is very convenient, here will not do too much introduction, interested can: to Android developers RxJava details

How to use RxAndroid

The main implementation in the framework is Presenter in MVP. How to use it will be explained later.

What is the MVP

MVP(Model View Presenter) abandons the traditional MVC(Model View) Control) mode, mainly to separate the business logic and View, so that there is no need to put a lot of business logic into the Activity to Control, and View is just to update the UI, making the project clear and simple maintenance.

As shown in figure:

How to Use MVP

Inherit BaseActivity from your Activity:

Public class MainActivity extends BaseActivity {//MainPresenter extends BaseActivity {//MainPresenter extends BaseActivity {// Object is a Bean returned by the server  protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override MainPresenter createPresenter() { return new MainPresenter(this); Public void login(View View) {Map param = new HashMap<>(); param.put("userName", "183****3706"); param.put("password", "******"); param.put("imei", "422013"); mPresenter.start(LoginApi.login(param), "1"); // Tag:1 mPresenter.start(LoginApi.login(param), "2"); // Tag:2 mPresenter.start(LoginApi.login(param), "3"); // Tag:3 mPresenter.start(LoginApi.login(param)); // no Tag } }Copy the code

So let’s see what the business logic does.

public class MainPresenter extends BasePresenter { public MainPresenter(BaseView view) { attachView(view); }}Copy the code

It’s easy Nothing, nothing You’re doing everything What are you doing?

In fact, the framework encapsulates some simple methods in BasePresenter. What are they?

protected void start(Observable o) ; // Simply access protected void start(Observable, final String Tag) without a Tag; // Simple access with a Tag, suitable for when a page needs to access different network interface return bean may be different. / / is mainly used to cancel the HTTP request and so on. Protected ProgressDialogCustomListener mCustomListener; // The user implements his own request network dialog boxCopy the code

Next, the Response given by the server is combined with the callback given by RxAndroid to update the corresponding View

public interface BaseView {
    /**
     * request network data success
     *
     * @param data
     */
    void onDataSuccess(String tag, M data);

    /**
     * request network data success
     *
     * @param data
     */
    void onDataSuccess(M data);


    /**
     * request network data fail [note:401 or 404 and so on]
     *
     * @param reason
     */
    void onDataFailed(String reason);

    /**
     * request network data fail [note:401 or 404 and so on]
     *
     * @param tag
     * @param reason
     */
    void onDataFailed(String tag, String reason);

    /**
     * no network
     */
    void onNoNetWork();

    /**
     * no network
     *
     * @param tag
     */
    void onNoNetWork(String tag);

    /**
     * finish
     */
    void onComplete();

    /**
     * finish
     *
     * @param tag
     */
    void onComplete(String tag);

    /**
     * get context
     *
     * @return
     */
    BaseActivity getContextForPresenter();

}Copy the code

If you have special requirements, such as handling tokens every time or filtering data first, RxJava is too easy to use.

/** * The Http resultCode is used for unified processing, and the Data part of the HttpResult is stripped out and returned to subscriber ** @param subscriber which really needs the Data type. */ protected class HttpResultFunc implements Func1, M> { @Override public M call(BaseResponse baseResponse) { // if (baseResponse.getCode().equals("0000")) { // throw new ApiException(100); // } mToken = baseResponse.getToken(); return baseResponse.getData(); }}Copy the code

What is a Retrofit2.0

There are many open source libraries on the web, such as Volley, Okhttp, Retrofit, etc. These three libraries are popular right now. Among them, OkHTTP and Retrofit were developed by the Square team

There’s a sentence in the documentation on the website about what Retrofit is. A type-safe HTTP client for Android and Java,(type-safe code refers to access to authorized memory locations. For example, type-safe code cannot read values from private fields of other objects. It can only be read from a well-defined allowed access type. Type-safe code has well-defined data types.

And mostly RESTful in mind,Retrofit is just a framework, it doesn’t provide access to the web, it still requires OkHttp or other libraries, and Retrofit supports RxJava.

How to use

Create a class that is used exclusively as a NetWork API, such as login:

public class LoginApi { private interface LoginService { @POST("csh-interface/endUser/login.jhtml") Observable> login(@Body Map body); } public static Observable> login(Map body) { return FastHttp.create(LoginService.class).login(body); }}Copy the code

What is a OKHTTP

Self-introduction on the official website:

HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.

OkHttp is an HTTP client that’s efficient by default:

? HTTP/2 support allows all requests to the same host to share a socket.

? Connection pooling reduces request latency (if HTTP/2 isn’t available).

? Transparent GZIP shrinks download sizes.

? Response caching avoids the network completely for repeat requests.

OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.

Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking calls and async calls with callbacks.

OkHttp supportsAndroid2.3 and above. ForJava, the minimum requirement is 1.7.

OkHttp is an excellent HTTP framework that supports GET and POST requests, HTTP-based file uploads and downloads, image loading, transparent GZIP compression of downloaded files, response caching to avoid repeated network requests, and connection pooling to reduce response latency.

How to use

I won’t go into details here, but it’s mainly for use with Retrofit:

/** * init the retrofit and okhttp */ private void init() { OkHttpClient.Builder okClient = getOkHttpClient(); if (DEBUG) // is debug mode show request info okClient.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); LogUtils.d("request url:" + request.url() + "\n" + bodyToString(request.body())); Response response = chain.proceed(request); LogUtils.d("response:" + response.body().string()); return chain.proceed(request); }}); okClient.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); Retrofit.Builder builder = new Retrofit.Builder().client(okClient.build()).baseUrl(HttpUrl.parse(getBaseUrl())); mCallAdapter = getCallAdapter(); mConverter = getConverter(); if (null ! = mCallAdapter) builder.addCallAdapterFactory(mCallAdapter); if (null ! = mConverter) builder.addConverterFactory(mConverter); retrofit = builder.build(); }Copy the code

github:Android-FastCode

Using this library, you can easily and quickly frame your own projects. I hope you can give me a Star, thank you 🙂