Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the characteristics of the mainstream framework of android

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what are the characteristics of the mainstream framework of android". In daily operation, I believe that many people have doubts about the characteristics of the mainstream framework of android. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what are the characteristics of the mainstream framework of android?" Next, please follow the editor to study!

Characteristics

Automatically generate MVP,Dagger2 related classes

Version update

Update log

General framework, suitable for all types of projects, supporting the development of large projects, Demo package structure can be used directly

All managed with Dagger2 (connect all modules using Dagger, not easy to use)

Heavy use of Rxjava

After modifying the package name (do not modify the common package), you can use it directly and quickly access it (please follow the steps below to connect to the old project)

All UI adaption

Picture loading class ImageLoader uses policy mode and builder mode to easily switch between picture loading framework and function extension

The Model layer provides Retrofit API and RxCache, and you can choose whether to use cache or not.

Global http Request (request parameter, headers) Response (result returned by server, headers, time-consuming) information listens. After parsing json, you can perform corresponding global operations according to the status code.

Global Rxjava error handling, automatically retry after the error, capturing all errors of the entire application

Frame structure

Packet structure

Development instructions

Developers need to have certain Android development capabilities.

Developers must have experience in using Dagger2,Rxjava,Retrofit and must understand if they have not used it, otherwise it will be very difficult to use it.

Introduction to Libraries

The official Mvp architecture project of MvpGoogle contains several different architecture branches (this is the Dagger branch).

According to the dependency injection framework produced by Dagger1 of Square, Dagger2Google generates code dynamically through apt, and its performance is better than that of dependency injection framework with reflection technology.

Rxjava provides elegant responsive Api to resolve asynchronous requests.

RxAndroid provides responsive Api for Android.

Rxlifecycle uses a pit known to rxjava on Android, which is lifecycle unsubscribing, which is solved by binding the lifecycle of activity and fragment.

RxbindingJakeWharton God's View binding framework, elegant handling of View response events.

RxCache is a cache that adds secondary caches (memory, disk) for Retrofit using annotations

The network request library produced by RetrofitSquare greatly reduces the code and steps of http requests.

Okhttp is also produced by Square, without much introduction, you should know how to do Android.

Autolayout Hongyang god's Android full-size adaptation frame.

GsonGoogle official Json Convert framework.

View injection framework produced by ButterknifeJakeWharton.

Androideventbus is a lightweight Eventbus using annotations.

TimberJakeWharton produced the Log framework with very little internal code, but the idea is very good.

Glide this library for the default encapsulation of this framework image loading library, can be changed to other libraries with reference to examples, Api and Picasso similar, cache mechanism than Picasso complex, fast, suitable for dealing with large picture stream, support gfit,Fresco is too large!

The speed and cross-platform nature of Realm make it the most popular database today. The only drawback is that the so library is too large.

LeakCanarySquare products are specially used to detect memory leaks in Android and Java, and prompt memory leakage information through the notification bar.

RxErroHandlerRxjava error handling library, which can be retried after an error occurs

1 Development preparation

This framework is suitable for your own customization and modification. All are not uploaded to Jcenter or Maven for the time being. Please download or clone.

1.1 Import frame

Compile project (': arms')

1.2 reference config.build

This framework provides a config.gradle file that references a large number of third-party libraries for version management of third-party libraries, copies config.gradle into the root directory, and references it in the project's * * build.gradle

1.2.1 using config.build

Because it is referenced in * build.gradle, you can use rootProject.xxx to use its contents in all build.gradle throughout the project

You can also use it to manage some project information, so that multiple module can also use one information directly.

1.3 rely on Dagger2

This framework is all managed by Dagger2, so you must rely on Dagger2 to find the build.gradle of app and add the following code

1.4 configure AndroidManifest

1.4.1 add permissions

1.4.2 configuring Autolayout Meta

To use the Autolayout adaptive framework, you must configure Meta properties and the width and height of the design drawing. For more information, please see Autolayout.

1.4.3 referencing Glide Custom Properties

This framework uses Glide to load pictures by default, but provides a manager ImageLoader to provide a unified interface. You can easily replace the picture loading framework with strategist mode. This framework provides custom cache configuration information of Glide by default. Refer to its custom configuration information before using it.

1.5 confusion

Since this framework relies on a large number of three-party libraries, all the rules have been provided in proguard-rules.pro under arms Module. If you want to use it, copy it to replace proguard-rules.pro in app Module. In case of confusion, you can modify or add rules according to your own needs. Be sure to add Java Bean and custom components to the rules before confusion.

1.6 version UPDAT

! The package name of the common package must not be modified. In the old version, a class with the same name as the common package needs to be found and deleted, and then repeated.

New reference to the class in the common package

If you get this framework through clone or download:

You can pull the version of * * directly from the command line git pull origin master and merge it automatically.

If you change the package name and execute the command git rm-- cache-r app/src/main/java/me/jessyan/mvparms, the contents of Demo will not be pulled the next time you pull

If you get this framework through fork to your own warehouse, clone or download:

Git remote add arms https://github.com/JessYanCoding/MVPArms.git adds a remote warehouse. Arms is the code name of the remote warehouse, which can be customized. Later, the remote warehouse will be operated through this code name.

Git fetch arms pulls the version of remote repository *

Git merge arms/master-- allow-unrelated-histories merges the remote warehouse into the current branch

Later, if there is an update to this framework, you only need to repeat 2Jing 3 steps,-- allow-unrelated-histories is only used to add when * merge.

If you change the package name and execute the command git rm-- cache-r app/src/main/java/me/jessyan/mvparms, the contents of Demo will not be pulled the next time you pull

2 Quick start

2.1 inherit BaseApplication

The Application of the new project inherits from BaseApplication and is declared in AndroidManifest

2.1.1 AppComponent

The Application life cycle is the same as App, so it is suitable to provide some singleton objects. This framework uses Dagger2 management, so use AppComponent to provide all global singleton objects.

Create an AppComponent interface

Construct AppComponent object

Both ServiceModule (providing RetrofitApi) and CacheModule (providing cache) need to be created by yourself. For more information, ServiceModule (2.1.2) and CacheModule (2.1.3)

2.1.2 ServiceModule

ServiceModule provides Service corresponding to RetrofitApi. These Service objects are injected into AppComponent into ServiceManager (need to inherit BaseServiceManager) for unified management.

The self-defined Retrofit Service is as follows. Please ignore the skilled Retrofit.

Public interface CommonService {String HEADER_API_VERSION = "Accept: application/vnd.github.v3+json"; @ Headers ({HEADER_API_VERSION}) @ GET ("/ users") Observable getUsers (@ Query ("since") int lastIdQueried, @ Query ("per_page") int perPage);}

Define ServiceModule, where Service interfaces are instantiated using Retrofit objects (provided by ClientModule), providing all Service objects (multiple Service interfaces can be divided according to different logic)

@ Module public class ServiceModule {@ Singleton @ Provides CommonService provideCommonService (Retrofit retrofit) {return retrofit.create (CommonService.class);}}

AppComponent injects all Service into ServiceManager, and all Model layers can get this object, which means that each Model can request any Api

2.1.3 CacheModule

By default, the Cache layer uses RxCache,CacheModule to provide Cache objects corresponding to RetrofitApi. These Cache objects are injected into AppComponent and managed uniformly in CacheManager (to inherit BaseCacheManager).

The self-defined RxCache Provider is as follows. Please ignore the skilled RxCache.

Public interface CommonCache {@ LifeCache (duration = 2, timeUnit = TimeUnit.MINUTES) Observable getUsers (Observable oUsers, DynamicKey idLastUserQueried, EvictProvider evictProvider);}

Define CacheModule, where all Cache interfaces are instantiated using RxCache objects (provided by ClientModule), providing all Cache objects

@ Module public class CacheModule {@ Singleton @ Provides CommonCache provideCommonService (RxCache rxCache) {return rxCache.using (CommonCache.class);}}

AppComponent injects all Cache into CacheManager, and all Model layers can get all Cache objects

2.2 inheriting BaseActivity

Let the project's base class Activity inherit BaseActivity,BaseActivity and inject Presenter by default, so if you want to use Presenter, you must specify the corresponding paradigm and provide the Component needed to inject Presenter.

2.3 inherit BaseFragment

Let the project's base class Fragment inherit BaseFragment,BaseFragment and inject Presenter by default, so if you want to use Presenter, you must specify the corresponding paradigm and provide the Component needed to inject Presenter.

2.4 MVP actual combat

Define the business logic MVP and inherit the respective base classes of MVP. Here, you can define the MVP class slightly, that is, instead of defining a different MVP class for each Fragment and Activity (each page), you can use a set of MVP classes according to the same business logic.

2.4.1 Contract

According to the official MVP project of Google, the interface of MVP can be defined in Contract for easy management. This framework does not need to define the interface of Presenter, so Contract only defines the interface of Model and View.

2.4.2 View

Generally, let Activity or Fragment implement the View interface defined in Contract for Presenter to call the corresponding method operation UI,BaseActivity to inject Presenter by default. If you want to use Presenter, you must specify the paradigm of Presenter and implement setupActivityComponent to provide the Component and Module required by Presenter.

2.4.3 Model

Model implements the Model interface of Contract, inherits BaseModel, specifies the ServiceManager and CacheManager defined above, and then gets the required Service and Cache through two Manager to provide Presenter with the required data (choose whether to use cache or not)

2.4.4 Presenter

Most of the functions of Presenter in MVP are to obtain data from the Model layer interface and display the data by calling the View layer interface. First, implement BasePresenter and specify the paradigm of Model and View. Be sure to specify the interface defined in Contract. Model and View required by Presenter use Dagger2 injection, so it is not only decoupled but also easy to test, how to inject it?

2.4.5 MVP Module

The Module here provides the implementation classes of the View and Model interfaces (the interfaces defined in Contract) corresponding to the current business logic. Model needs the ServiceManager and CacheManager provided in AppComponent to implement network requests and caches, so you need to get these two Manager through Component relying on AppComponent

2.4.6 MVP Component

It should be noted that this Component must rely on AppComponent in order to provide the ServiceManager and CacheManager needed by Model. By providing the inject () method, the objects provided in Module and AppComponent can be injected into the corresponding classes. The parameters in inject () cannot be interfaces, how can they be injected?

@ ActivityScope @ Component (modules = UserModule.class,dependencies = AppComponent.class) public interface UserComponent {void inject (UserActivity activity);}

2.4.7 Dagger Scope

In the above code, a large number of ActivityScope appears in Module and Component. Dagger2 uses Scope to limit the life of objects provided in each Module. By default, Dagger2 only provides a @ SingletonScope, that is, a singleton. This framework provides @ ActvityScope and @ FragmentScope. If you have other requirements, please implement them by yourself. After Module and Component define the same Scope, the life cycle of the objects provided in Module will be the same as in Component (that is, during the Component life cycle, if you need to use the objects provided in Moudle. The @ Provide annotated method will only be called once to get this object)

2.4.8 MVP Summary

In the future, each business logic will repeatedly construct these classes, just changing the name. It is worth noting that when MVP is first used, it does feel that there are many more classes for no reason, which is very tedious and troublesome, but when the logic of the page code becomes more and more, you will find the advantages, such as clear logic, decoupling, easy teamwork, easy testing, and easy positioning of errors. So now this framework provides Template automatic code generation to solve this pain point, so that developers can use the framework more happily.

3 function use

3.1 App global configuration information (using Dagger injection)

GlobeConfigModule uses builder mode to encapsulate the global configuration information of App into Module (using Dagger injection where configuration information is needed), you can configure CacheFile,InterCeptor, etc., because you are using builder mode, if you have other configuration information that needs to be injected with Dagger, you can directly add it to Builder without affecting other places.

/ / if you need to add a Boolean field to the Log utility class to determine whether to print Log @ Module public class GlobeConfigModule {private Boolean isLog; private GlobeConfigModule (Buidler buidler) {this.isLog = builder.isLog} public static Buidler buidler () {return new Buidler ();} public static final class Buidler {private Boolean isLog Private Buidler () {} / / 1. Add a method to Builder to accept the isLog field public Buidler isLog (Boolean isLog) {this.isLog = isLog; return this;} public GlobeConfigModule build () {return new GlobeConfigModule (this);}} / / 2. Use @ Provides to return isLog for Dagger to inject into the Log utility class @ Singleton @ Provides Boolean provideIsLog () {return isLog;}}

3.2 globally capture Http requests and responses

Pass in GlobeHttpHandler through the GlobeConfigModule.globeHttpHandler () method

@ Override protected GlobeConfigModule getGlobeConfigModule () {return GlobeConfigModule .buidler () .baseurl (Api.APP_DOMAIN) .globeHttpHandler (new GlobeHttpHandler () {/ / A processing class that handles the results of http responses globally can be provided here. / / you can get the results returned by the server one step ahead of the client, and you can do some operations. For example, if token times out, retrieve @ Override public Response onHttpResultResponse (String httpResult, Interceptor.Chain chain, Response response) {/ /. Here, the client can get the result of each http request first, parse it into json, and do some operations, such as / / re-request token after detecting the expiration of token. And re-execute the request try {if (! TextUtils.isEmpty (httpResult)) {JSONArray array = new JSONArray (httpResult) JSONObject object = (JSONObject) array.get (0); String login = object.getString ("login"); String avatar_url = object.getString ("avatar_url") Timber.tag (TAG) .w ("result->" + login + "| | avatar_url- >" + avatar_url);} catch (JSONException e) {e.printStackTrace () Return response } / / if you find that the token expires, you can request the * token first, and then re-request it before putting the new token into the request. / / Note that proceed has been called before this callback, so you must set up the network request yourself. If you use okhttp, use the new request to request / / create a new request and modify it accordingly using the new token / / Request newRequest = chain.request () .newBuilder () .header ("token", newToken) / / .build () / retry the request / response.body () .close () / / if you use okhttp to send a new request, the returned response return can be sent out after the request is successful. / / if you do not need to return a new result, return the response parameter to return response directly. } / / you can get the request before requesting the server, and do some operations such as adding token to request or header @ Override public Request onHttpRequestBefore (Interceptor.Chain chain, Request request) {/ / if you need to request the server again. Then return a requeat that has been operated again. If you add header and do nothing, you will return request / / return chain.request () .newBuilder () .header ("token", tokenId) / / .build (). Return request;}}) .build ();}

3.3 Global error handling and re-execution when an error occurs

If you need to use the global error handling of Rxjava, you need to pass in ResponseErroListener through the GlobeConfigModule.responseErroListener () method, and each time you call subscribe with Rxjava, use ErrorHandleSubscriber and pass in the RxErrorHandler provided in AppComponent. This Subscribe has already implemented the OnError method by default. You can override the OnError method if you want to customize

Use in Rxjava

3.4 Toggle picture request framework

This framework uses Glide to load images by default, uses ImagerLoader to provide a unified interface, ImagerLoader uses policy mode and builder mode, and can dynamically switch picture frames (for example, switch to Picasso), and the parameters passed when loading pictures can also be extended at will (loadImage method does not need to change when the extension parameters are needed, all through Builder expansion, for example, you want internal images to load the framework. To clear the cache, you only need to define a boolean field. Internally, according to this field, if | else, other operations are the same)

To use ImageLoader, you must pass in a picture loading implementation class that implements the BaseImageLoaderStrategy interface to achieve dynamic switching, so first of all, to implement BaseImageLoaderStrategy, you must specify an implementation class that inherits from ImageConfig. Using the builder mode, you can store some information, such as URL, ImageView,Placeholder, etc., which can be constantly extended to be used by the image loading framework.

Implement ImageCofig using the builder pattern

Public class PicassoImageConfig extends ImageConfig {private PicassoImageConfig (Buidler builder) {this.url = builder.url; this.imageView = builder.imageView; this.placeholder = builder.placeholder; this.errorPic = builder.errorPic;} public static Buidler builder () {return new Buidler ();} public static final class Buidler {private String url; private ImageView imageView; private int placeholder; protected int errorPic Private Buidler () {} public Buidler url (String url) {this.url = url; return this;} public Buidler placeholder (int placeholder) {this.placeholder = placeholder; return this;} public Buidler errorPic (int errorPic) {this.errorPic = errorPic; return this } public Buidler imagerView (ImageView imageView) {this.imageView = imageView; return this;} public PicassoImageConfig build () {if (url = = null) throw new IllegalStateException ("url is required"); if (imageView = = null) throw new IllegalStateException ("imageview is required"); return new PicassoImageConfig (this);}

You can pass PicassoImageLoaderStrategy () when ImageLoader is constructed, or after you get the ImageLoader object through AppComponent, setLoadImgStrategy (new PicassoImageLoaderStrategy) replaces the previous implementation (default uses Glide)

3.***ndroidEventBus Tag

This framework uses AndroidEventBus to implement the event bus. This framework uses the annotation mark target method to write the constants of Tag into the EventBusTag interface, which is easy to manage. If you want to use AndroidEventBus in the current object, please rewrite useEventBus () in the Activity,Fragment,Presenter you need to use. Return true for use, and return true by default.

3.6 AutoLayout components

This framework uses the AutoLayout framework to achieve control adaptation. In order to make the component adaptive, it must let its parent control, re-measure, and rewrite LayoutParams. Officially, only three ViewGroup,AutoRelativeLayout,AutoLinearLayout,AutoFrameLayout are provided by default to achieve these operations. In order to facilitate developers to use, this framework provides some commonly used AutoLayout components. In the autolayout package under the framework's widget package, the child controls can be adapted by referencing it in xml. It also provides a Template (on the * side) to generate the Auto series View needed for self-adaptation. If you need to make the child controls of ScrollView adaptive, input ScrollView using this Template to generate AutoScrollView, which can be referenced in xml.

3.7Custom PopupWindow

The framework provides a custom PopupWindow component CustomPopupWindow of the builder pattern. After you implement the layout, you can directly use this implementation PopupWindow, use the builder pattern, and expand the custom parameters at will

3.8Quick implementation of RecycleView

This framework provides DefaultAdapter and BaseHolder base classes for fast implementation of Recycleview.

BaseHolder initializes ButterKnife and AutoLayout by default. After inheritance, not only View can be directly injected, but also the layout can be adapted to the screen.

RecycleView does not provide click events for Item by default. You can use DefaultAdapter to call setOnItemClickListener to realize click events for Item.

3.9Privileges management (adapts to Android6.0 privilege management)

This framework uses RxPermissions for rights management (adapting to android6.0), and provides PermissionUtil tool class with one line of code to realize permission request. Detailed explanation of Rights Management of adaptation Android6.0

PermissionUtil.launchCamera (new RequestPermission () {@ Override public void onRequestPermissionSuccess () {launchCapture (); / / do some actions after the permission request is successful}}, mRxPermissions, mRootView, mErrorHandler)

3.10 Gradle configuration starts DeBug mode

Configure debugging tools such as whether to turn on printing Log or to use LeakCanary in the build.gradle of the main project (app)

Configure in build.gradle

Use in code (such as making some initialization settings in application)

3.11 AppManager (manage all Activity)

AppManager is used to manage all Activity, with a List containing all the surviving Activity (without calling onDestroy) and a currently front-end Activity (without calling onPause). AppManager encapsulates a variety of methods that can be easily operated on them, or all its methods can be remotely controlled by EventBus without holding AppManager, so that we can globally operate on any Activity anywhere in the entire app. For example, when app requests network timeout, let the front-end Activity display the interaction page with connection timeout (this logic does not have to be written into the current request Activity, but can be operated globally in a singleton class, because the current Activity can be obtained at any time through AppManager)

Remote control is realized through EventBuspost Message. Different what distinguishes different methods from Handler. You can add corresponding methods to AppManager according to your own needs.

At this point, the study on "what are the characteristics of the mainstream framework of android" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report