1. Componentized architecture diagram
During the development process, our app may contain many modules. In this case, we should break each module into components.
App relies on all component layers, which are independent of each other, and all components depend on the common layer. If the network layer is abstracted, the common layer relies on the Network layer, and the Network layer relies on the Base layer. Implementation and API are flexibly used in the dependency. The dependency cannot be reversed, but can be cross-layer. The dependency relationship is shown in the following figure.
Graph TD APP --> Component A APP --> Component B APP --> Component C APP --> Component D component A --> Common Component B --> Common component C --> Common component D --> Common common --> network network --> base
2. Autoservice implements componentized development
Let’s assume that instead of componentializing development, we start each component module in the main app module by calling startActivity directly with the Intent. We need to display the name of the Activity class that uses the component module, so we need to introduce the Activity of the component module. In this way, the coupling degree between each module is high; Here we use the official AutoService provided by Google to implement componentized development, to eliminate this high coupling;
1. Interface sinking
We define the interface to start the Activity in the Common layer and implement it in the required Module.
public interface IWebViewService {
void startWebViewActivity(Context context);
}
Copy the code
2. Interface implementation
We are putting interface implementations in modules; And then add the @autoService annotation;
@AutoService(IWebViewService.class) public class WebViewServiceImpl implements IWebViewService { @Override public void startWebViewActivity(Context context) { if (context ! = null) { Intent intent = new Intent(context, WebViewActivity.class); context.startActivity(intent); }}}Copy the code
3. Interface call
In the main app module, we can use ServiceLoader to find the implementation of the interface, and then find the implementation is a collection, so generally we use one implementation for each interface, so that it is convenient to use;
IWebViewService webviewService = ServiceLoader.load(IWebViewService.class).iterator().next(); if(webviewService ! = null) { webviewService.startWebViewActivity(MainActivity.this); }Copy the code