Xutils source parsing "turn"

Source: Internet
Author: User
Tags name database

Original: http://my.oschina.net/u/1538627/blog/395098

Catalogue [-]

  • 1. Function Introduction
  • 2. Detailed design
  • 2.1 View Module
  • 2.1.1 Overall design
  • 2.1.2 Flowchart
  • 2.1.3 Core class Function Introduction
  • Please understand the annotations first, the dynamic agent can help you, if already understand please ignore.
  • 1.viewutils.java
  • (1) Main function
  • 2.viewfinder.java
  • (1) Main function
  • 3.resloader.java
  • 4.eventlistenermanager.java
  • 5. Annotation Classes
  • 2.2 DB Module
  • 2.2.1 Overall Design
  • 2.2.2 Flowchart
  • 2.2.3 Core class Function Introduction
  • 1.dbutils.java
  • 2.daoconfig.java
  • 3.findtempcache.java
  • 4.sqlinfobuilder.java
  • 5.sqlinfo.java
  • 6.table.java
  • 7.column.java
  • 8.id.java
  • 9.selector.java
  • 10.wherebuilder.java
  • 2.3 HTTP Module
  • 2.3.1 Overall Design
  • 2.3.2 Flowchart
  • 2.3.3 Class Diagram
  • 1.httputils.java
  • 2.httprequest.java
  • 3.requestcallback.java
  • 4.httphandler.java
  • 5.httpcache.java
  • 6.stringdownloadhandler.java
  • 7.filedownloadhandler.java
  • 8.httpexception.java
  • 2.4 Bitmap Module
  • 2.4.1 Overall Design
  • 2.4.2 Flowchart
  • 2.4.3 Class Diagram
  • 1.bitmaputils.java
  • 2.bitmaploadtask.java
  • 3.bitmapcache.java
  • (1) Main function
  • 4.bitmapglobalconfig.java
  • 5.bitmapdisplayconfig.java
  • 6.defaultdownloader.java
  • 7.defaultbitmaploadcallback.java
  • 3. Talk
  • Same point:
  • Different points:
1. Function Introduction

Xutils an Android Common library framework that consists of four parts: View,db, Http, Bitmap four modules.

    • The main function of the view module is to bind UI, resources, and events through annotations.
    • The DB module is a database ORM framework, and simple statements are able to manipulate the data.
    • The HTTP module mainly accesses the network, supports synchronous, asynchronous requests, and supports the download of files.
    • The bitmap module is the processing of loading pictures and pictures, supports loading local, network pictures. It also supports image memory and local cache.
2. Detailed Design 2.1 View Module 2.1.1 Overall design

There are fewer processes and relationships, see the detailed analysis below

2.1.2 Flowchart

2.1.3 Core class Function Introduction Please understand the annotations first, the dynamic agent can help you, if already understand please ignore.

Annotation and reflection knowledge is the main content of this module

1.viewutils.java

View and the injection of various events and the injection of resources.

(1) Main function
private static void Injectobject (Object handler, viewfinder Finder)

The first parameter, object handler, represents the objects that need to be injected, and the second parameter is the view or activity wrapper object that needs to be injected into the view (the view is the member variable of the handler). This method completes the injection of view and various events and the injection of resources. The main principle is through reflection and annotation.

    • Complete the activity Setcontentview.
    • Complete the injection of the view.
    • Complete the injection of the resource.
    • Complete the injection of various events.
2.viewfinder.java (1) Main function
public view Findviewbyid (int id, int pid) public    view Findviewbyid (int id)

If a parent view is present, it is preferred from the parent view, otherwise it is sought from the current view or activity.

3.resloader.java
public static Object Loadres (restype type, context context, int id)

Gets the resource file value. Supports access to multiple resources.

4.eventlistenermanager.java

The injection of events, where the design is through dynamic proxies.

Private final static Doublekeyvaluemap<viewinjectinfo, Class<?>, object> listenercache =            New Doublekeyvaluemap<viewinjectinfo, Class<?>, object> ();

Store the Listener event interface map. Because some interfaces have multiple functions, the agent will determine if the event interface exists, if there is only an increase in the proxy method is enough, to avoid re-setting the Listener event interface.

public static void Addeventmethod (            viewfinder finder,            viewinjectinfo info,            Annotation eventannotation,            Object Handler,            method)

Agent Listener Events

5. Annotation Class 2.2 DB module 2.2.1 Overall design

There are fewer processes and relationships, see the detailed analysis below

2.2.2 Flowchart

2.2.3 Core class Function Introduction

Annotations, reflection, and database operations knowledge the main content of this module

1.dbutils.java

The main function of database creation, database additions and deletions to check.

private static hashmap<string, dbutils> Daomap = new hashmap<string, dbutils> ();

The map that holds the Dbutils instance object, one instance for each database, and key for the database name.

Private synchronized static dbutils getinstance (Daoconfig daoconfig)

Take a singleton pattern, create a database based on daoconfig, and also involve a database upgrade in the middle.

delete;    findAll;    FindByID;    saveorupdate;//When the database is not saved, it is modified when it is present.    Update;

Additions and deletions to check.

2.daoconfig.java
Private String DbName = "xutils.db"; Default DB name database names    private int dbversion = 1;//database version    private dbupgradelistener dbupgradelistener;//Upgrade Listener Event

The database configuration class.

3.findtempcache.java

In the query data of Dbutils

@SuppressWarnings ("unchecked") public    <T> list<t> findAll (Selector Selector) throws Dbexception {        ....        String sql = selector.tostring ();        Long seq = CursorUtils.FindCacheSequence.getSeq ();        Findtempcache.setseq (seq);        Object obj = findtempcache.get (sql);//priority read from cache        if (obj! = null) {            return (list<t>) obj;        }        ...    }

The cache of database query data. The data in the cache is called first in the query

4.sqlinfobuilder.java

A combination of SQL-built tables, add-and-revise statements.

public static Sqlinfo Buildcreatetablesqlinfo (Dbutils db, class<?> entityType) public  static Sqlinfo Builddeletesqlinfo (dbutils db, class<?> EntityType, Object idvalue) public static Sqlinfo Builddeletesqlinfo ( Dbutils db, Class<?> EntityType, Wherebuilder wherebuilder) public static Sqlinfo Builddeletesqlinfo (Dbutils db, Object entity) public static Sqlinfo Buildinsertsqlinfo (Dbutils db, Object entity) public static Sqlinfo Buildupdatesqlinfo (Dbutils db, Object entity, String ... updatecolumnnames) public static Sqlinfo Buildupdatesqlinfo ( Dbutils db, Object entity, Wherebuilder Wherebuilder, String ... updatecolumnnames)
5.sqlinfo.java

The SQL statement and value wrapper object.

6.table.java

The Table object.

7.column.java

The Column object in the table.

8.id.java

The primary key object that corresponds to the table.

9.selector.java

A combination of SQL query statements.

10.wherebuilder.java

A combination of SQL conditional statements.

2.3 HTTP Module 2.3.1 Overall design

2.3.2 Flowchart

2.3.3 Class Diagram

1.httputils.java

Support asynchronous synchronous access to network data, breakpoints to download files.

Caching of network data. Public    final static HttpCache Shttpcache = new HttpCache ();    Access to the httpclient of the network.    private Final defaulthttpclient httpClient;     Private final HttpContext httpcontext = new Basichttpcontext ();    The thread pool.    private final static priorityexecutor EXECUTOR = new Priorityexecutor (default_pool_size);
Public httputils (int conntimeout, String useragent) {//config timeout time, useragent, HTTP version Information protocol, etc...//will be configured The parameters are uniformly put into httpClient httpClient = new Defaulthttpclient (new Threadsafeclientconnmanager (params, schemeregistry), para        MS); ....///below this key, set the Interceptor. Default plus GIZP compression.        The data transfer efficiency is much higher when compressed by GIZP. Httpclient.addrequestinterceptor (New Httprequestinterceptor () {@Override public void process (Org.ap                Ache.http.HttpRequest HttpRequest, HttpContext HttpContext) throws Org.apache.http.HttpException, IOException { if (!httprequest.containsheader (header_accept_encoding)) {Httprequest.addheader (header_accept_en                CODING, Encoding_gzip);        }            }        }); Httpclient.addresponseinterceptor (New Httpresponseinterceptor () {@Override public void process (Http Response Response, HttpContext HttpContext) throws Org.apache.http.HttpException, IOException {final httpentity entity = response.getentity ();                if (entity = = null) {return;                } final Header encoding = entity.getcontentencoding (); if (encoding! = null) {for (HeaderElement element:encoding.getElements ()) {I                            F (Element.getname (). Equalsignorecase ("gzip")) {//Here determine whether data transferred from the server needs to be decompressed via gzip.                             Response.setentity (New Gzipdecompressingentity (Response.getentity ()));                        Return    }                    }                }            }        }); }
Access network data    private <T> httphandler<t> sendrequest (HttpRequest request, requestparams params, Requestcallback<t> callBack);    Download network files public    httphandler<file> Download (Httprequest.httpmethod method, string URL, string target,                                      Requestparams params, Boolean autoresume, Boolean autorename, Requestcallback<file> callback);
2.httprequest.java

The wrapper class for the network request. Includes URLs, access request methods, parameter values, and so on.

3.requestcallback.java

Completes the data request callback interface.

4.httphandler.java

Gets the implementation of the network data logic. This can be understood as the internal asynctask of the system. Accessing the Network data processing flowchart

5.httpcache.java

Cache of network data, internally containing Lrumemorycache. When data is obtained, it is determined whether it expires.

6.stringdownloadhandler.java

Handleentity () Streams network io to string.

7.filedownloadhandler.java

Handleentity () turns network IO into file.

8.httpexception.java

Unified exception

2.4 Bitmap Module 2.4.1 Overall design

2.4.2 Flowchart

Please view the HTTP module

2.4.3 Class Diagram

1.bitmaputils.java

Images of the asynchronous loading, support local and network pictures, image compression processing, the image of the memory cache has been cached locally.

Private Bitmapglobalconfig GlobalConfig; Thread pool, cache, and network configuration    private bitmapdisplayconfig defaultdisplayconfig;//Picture Display configuration
/**     * @param container represents the view * @param uri picture that needs to display the image of the     URI     * @param displayconfig Picture Display configuration     * @param callBack Image loading Callback Interface     *    /public <t extends view> void display (T container, String URI, Bitmapdisplayconfig displayconf IG, bitmaploadcallback<t> CallBack)

Set up picture flowchart

Detailed flowchart

2.bitmaploadtask.java

The asynchronous task that loads the picture. Reading a picture resource in Doinbackground

3.bitmapcache.java
Private Lrudiskcache Mdisklrucache; Flash cache    Private lrumemorycache<memorycachekey, bitmap> mmemorycache;//Storage cache
(1) Main function
Download the network picture, then compress the picture according to the configuration and cache the picture. Public    Bitmap Downloadbitmap (String uri, Bitmapdisplayconfig config, final bitmaputils.bitmaploadtask<?> Task)    //Read Bitmap from the storage cache to determine if the public    Bitmap Getbitmapfrommemcache (String URI, Bitmapdisplayconfig Config)    //read from the Flash cache Bitmap public    Bitmap getbitmapfromdiskcache (String uri, bitmapdisplayconfig config)
4.bitmapglobalconfig.java

configuration, including the thread pool, the size of the cache.

The path of the flash cache private String diskcachepath;//The maximum value of the stored cache private int memorycachesize = 1024 * 1024 * 4; 4mb//maximum value of the flash cache private int diskcachesize = 1024x768 * 1024x768 *;  50m//the thread pool that loads data from the network private final static priorityexecutor Bitmap_load_executor = new Priorityexecutor (default_pool_size )///The thread pool that reads the data from the Flash memory private final static priorityexecutor Disk_cache_executor = new Priorityexecutor (2);// Bitmap cached Time private long Defaultcacheexpiry = 1000L * 60 * 60 * 24 * 30; Days//bitmap Cache private Bitmapcache Bitmapcache;
5.bitmapdisplayconfig.java
The picture shows the size of    private bitmapsize bitmapmaxsize;    The animation of the picture    private Animation Animation;    Picture loading process of display pictures    private drawable loadingdrawable;    Picture loading failed to display picture    private drawable loadfaileddrawable;    The picture shows the configuration color    private Bitmap.config bitmapconfig = Bitmap.Config.RGB_565;
6.defaultdownloader.java

Get bitmap, support three kinds of get paths, local files, asset files, and network pictures.

7.defaultbitmaploadcallback.java

The callback that the picture loaded completes, and the default callback passes the obtained bitmap value to the view.

3. Talk

Compared to the volley framework

Same point:
    • 1. The network data caching mechanism is adopted.
    • 2. Thread communication via Handler
Different points:
      1. Volley's HTTP request was passed through HttpClient before the Android 2.3 release, and the later version was passed Urlhttpconnection. Xutils are all via HttpClient request Network (bitmap module picture download is via Urlhttpconnection). Urlhttpconnection supports gzip compression by default, and the API is simple to operate.
    • 2.Volley caches HTTP request data first into byte[], and then assigns to different requests the format that is required. Xutils is converted directly to the desired format. Volley: Good extensibility, but no big data requests, or OOM. Xutils: Do not cache into byte[] support big data requests, faster than volley, but the scalability is low.
    • 4.Volley access network data directly open a fixed number of threads to access the network, in the Run method to execute a dead loop, blocking waiting for the request queue. Xutils is to turn on the thread pool to manage threads.
      1. Cache invalidation policy, volley all network data supports the control of cache and read cache expiration times from the HTTP response header, and each request can control whether the cache and cache expiration times. Xutils network data requests are unified custom cache expiration times.

Xutils source parsing "turn"

Related Article

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.