Android Modular Routing Practice

Source: Internet
Author: User

It is a good choice to implement a jump routing between the various component pages of Android app. This article will implement a relatively lightweight routing component that involves the following knowledge:

    • Annotation (declaring routing destination information)
    • Annotationprocessor (Handling Annotations)
    • Javapoet (Generate Java file)
    • Urimatcher (Match URI)

This article will use Java annotations to implement a simple routing component, which is mainly explained in the following ways:

    1. annotation definition and use
    2. Annotation Jump Service
    3. Using Annotationprocessor to process annotations, generate files
    4. Matching of URIs
    5. Security parameters
    6. Development of Annotation Jump service

Because of the use of Annotationprocessor, the entire route can be divided into the following modules:

    • Lib-component-router (Android Engineering)
    • Lib-component-router-annotation (Storage notes)
    • Lib-component-router-compiler (annotation processing)
Annotation definition

Because our routing components are relatively simple, we mainly define the following annotations:

    • Uridestination (declaring routing destination information)
    • Destinationuri (define URI path)
    • Destinationargument (Parameter Declaration)
Declaring destination Route annotations
@Retention(RetentionPolicy.SOURCE)@Target(ElementType.TYPE)public @interface UriDestination {    String name();    DestinationUri uri();    DestinationArgument[] out() default {};    DestinationArgument[] in() default {};}

This annotation is mainly used to annotate the activity, declaring a route target information, each parameter description is as follows:

    • Authority (match URI authority)
    • Scheme (match URI scheme)
    • Path (matching URI path)
    • Out (output parameter)
    • In (input parameter)
Route URI annotations
@Retention(RetentionPolicy.SOURCE)@Target(ElementType.ANNOTATION_TYPE)public @interface DestinationUri {    String authority() default "imxingzhe.com";    String scheme() default "xingzhe";    String path() default "";}

The route is primarily used to declare the URI information for the routing destination, and the parameters are described as follows:

    • Authority (match Android.net.Uri authority)
    • Scheme (Match Android.net.Uri scheme)
    • Path (matching routing path information)
Routing parameter Annotations
@Retention(RetentionPolicy.SOURCE)@Target(ElementType.ANNOTATION_TYPE)public @interface DestinationArgument {    String key();    boolean require() default false;    Class<?> type();}

This annotation is mainly used to declare the input and output parameter information of the route, and the parameters are described as follows:

    • Key (the name of the parameter)
    • require (whether it is a required parameter)
    • Type (types of parameters)
Routing component functionality implements the target action
public interface DestinationAction {    Context getContext();    int getFlags();    int getRequestCode();    boolean getUriOnly();    Bundle getArguments();}

ActionCan be understood as a jump action, the use of the end of the builder mode to generate Action instances, and then by DestinationService executing a given action.

Jump Service Logic
public interface DestinationService {    void start(DestinationAction destinationAction);}

This interface contains only one start method for executing the DestinationAction logic. The main way to achieve the jump is ContentProvider to use the class-urimatcher way to achieve. First, declare an abstract service:

public abstract class AbstractUriDestinationService implements DestinationService {    private final static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);    private static boolean isDestinationDefinitionResolved;    @Override    public void start(DestinationAction ){        ...    }    ...        protected abstract List<DestinationDefinition> getDestinationDefinitions();}

The method is getDestinationDefinitions implemented by subclasses and provides information about this routing target primarily, DestinationDefinition as follows:

public class Destinationdefinition {private final String name;    Private final class<?> destination;    Private final list<destinationargumentdefinition> inargumentdefinitions;    Private final list<destinationargumentdefinition> outargumentdefinitions; Public Destinationdefinition (String name, class<?> destination, list<destinationargumentdefinition>        Inargumentdefinitions, list<destinationargumentdefinition> outargumentdefinitions) {this.name = name;        This.destination = destination;        This.inargumentdefinitions = inargumentdefinitions;    This.outargumentdefinitions = outargumentdefinitions;    } public String GetName () {return name;    } public class<?> Getdestination () {return destination;    } public list<destinationargumentdefinition> Getinargumentdefinitions () {return inargumentdefinitions; } public list<destinationargumentdefinition> GetoutargumentdefinitioNS () {return outargumentdefinitions; }}

The Start method in the

Abstracturidestinationservice class implements the true jump logic:

Public abstract class Abstracturidestinationservice implements Destinationservice {private final static Urimatcher mat    Cher = new Urimatcher (urimatcher.no_match);    private static Boolean isdestinationdefinitionresolved; @Override public void Start (Destinationaction destinationaction) {list<destinationdefinition> destination        Definitions = Getdestinationdefinitions ();        Resolvedestinationdefinition (destinationdefinitions);        Context context = Destinationaction.getcontext ();        if (context = = null) {throw new IllegalArgumentException ("content = = null");        } Packagemanager Packagemanager = Context.getpackagemanager (); if (destinationaction instanceof uridestinationaction) {uri uri = ((uridestinationaction) destinationaction). G            Eturi ();            int index = Matcher.match (URI); if (Urimatcher.no_match = = Index | | index >= destinationdefinitions.size ()) {throw new Illegalstateexce PtIon ("Not Found destination for:" + URI);            } destinationdefinition destinationdefinition = Destinationdefinitions.get (index); List<destinationargumentdefinition> destinationargumentdefinitions =            Destinationdefinition.getinargumentdefinitions (); for (Destinationargumentdefinition argumentdefinition:destinationargumentdefinitions) {Bundle args = des                Tinationaction.getarguments (); if (Argumentdefinition.isrequire () &&!args.containskey (Argumentdefinition.getkey ())) {Throw n                EW illegalargumentexception ("No such key:" + Argumentdefinition.getkey ());            }} Intent Intent = new Intent (Intent.action_view);            Intent.setdata (URI);                    if (packagemanager.resolveactivity (intent, 0) = = null) {if (Destinationaction.geturionly ()) {           throw new IllegalStateException ("Not Found activity for:" + URI);     } else {intent = new Intent (context, destinationdefinition.getdestination ()); if (packagemanager.resolveactivity (intent, 0) = = null) {throw new IllegalStateException ("Not Foun                    D activity for: "+ uri");            }}} intent.addflags (Destinationaction.getflags ());            Bundle args = Destinationaction.getarguments ();            if (args! = null) {Intent.putextras (args); If (context instanceof activity) {(activity) context). Startactivityforresult (Intent, Destina            Tionaction.getrequestcode ());            } else {context.startactivity (intent);        }} else {throw new IllegalStateException ("not operate");        }} private static void Resolvedestinationdefinition (List<destinationdefinition> destinationdefinitions) { if (isdestinationdefinitionresolved) {return;        } int index = 0; for (Destinationdefinition destinationdefinition:destinationdefinitions) {if (destinationdefinition instance                of uridestinationdefinition) {uri uri = ((uridestinationdefinition) destinationdefinition). GetURI ();                String Stringforuri = uri.tostring ();                String path = Uri.getpath ();                int pathindex = stringforuri.indexof (path);                            if (pathindex! =-1) {path = Stringforuri.substring (Pathindex,                Stringforuri.length ());            } Matcher.adduri (Uri.getauthority (), Path, index++);    }} isdestinationdefinitionresolved = true; } protected abstract list<destinationdefinition> getdestinationdefinitions ();}

In this way, by implementing the AbstractUriDestinationService class, providing the corresponding DestinationDefinition jump function can be implemented, because of the use of registration we can use AnnotationProcessor to process the annotation generated DestinationService by the implementation class.

SOURCE Download: Https://github.com/yjwfn/AndroidRouterSample

Android Modular Routing Practice

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.