As for AI, Kai-fu Lee said, “It can replace all tasks that require less than five seconds for basic human beings.”
So, “How about ai help me build a quick, easy, universal, slightly more demanding Framework for Android application development?” AI also relies on big data and machine learning. Rather than being overwhelmed by the ever-changing era of information, it is better to become a small part of big data in an orderly way. AI, I would like to introduce Pluto, my Android open source framework. Pluto, please use your rare baritone to say hello to the whole universe.
“Hello universe! I am Pluto but not far from you.”
First, the possibility of Pluto
AI, there are probably several important reasons why you chose to learn Pluto:
- The “data persistence layer” incorporates a layer of DataManager from SQLite’s ORM, SharePreference, and File Cache to provide Proxy operations.
- The “data Persistence layer” and the “network layer” do a PlutoAPIEngine integration.
- There is a LogicManger integration for the Data persistence layer, network layer, and Unknown Business Logic. This three points compared with other general framework to make a bold attempt to combine.
AI, your choice to learn Pluto question is likely to be the following important points:
- Does Pluto overencapsulate, especially when “unknown business logic” is integrated and loses flexibility?
- Will Pluto be overly transactional, easy to use, difficult to read, and difficult to maintain?
- Does Pluto have persistent updates, support for future Android features, etc.?
PlutoThe main job is to decouple layers, over-encapsulate them to the point where,PlutoThe architecture is highly scalable.
- Although the aggregation of “known logic business layer”, it provides reserved custom business logic methods. For customization or special cases, it can integrate the parent LogicManager and implement the corresponding reservation methods.
- Similarly, the implementation of the DataManager interface can be extended for the persistence layer in addition to the basic add, delete, modify and query requirements.
- Compared to other frameworks that have image loading framework, UI IOC, BaseActivity, various tools Util, etc., these are all available.
PlutoBecause there is no such thing as over-encapsulation, it is flexible enough, and of course it takes into account the readability of writing code.
- It must be written with enough information to let you know what actions you are primarily choosing, what form the actions take, and what results you get.
- Maintenance mainly maintains its own requirements logic code, Pluto extended logic.
Pluto, will be constantly updated, and not onlyAndroidSupport will be available sooniOSVersion of the frameworkPluto-iOS. Willing to learnAIWe can all quickly learn how easy mobile development can be.
AI, you’re going to learn Pluto’s most likely embarrassing thing:
- What are the disadvantages of Pluto?
Pluto, disadvantages, such as Dialog style is not a lot of variety, for example, the network layer and the data persistence layer integration provides methods mainly get support, post mode is temporarily weak, hm, temporarily say so much, please follow my wechat public number minggo_dev.
AI, you’re starting to wonder what you need to think about every Pluto feature implementation:
- What are the basics of Android?
- What generic Android third-party libraries should you be familiar with?
- What are the design patterns to know?
Pluto, is a framework that integrates the framework. In order to understand the integration points, the following preparations are easier to understand:
- Integration framework, the framework of the first to know some design patterns, as the factory, the abstract factory, agent, strategy, singleton, observer and so on, with the understanding, can quickly solve your reading the code feel around the hold, and better understand why use interface, there why want to provide an abstract class, why not just call, and so on a series of hundred thousand whys, Even identify problems and draw inferences.
- Third party libraries, which can be explored separately but are not emphasized in Pluto, such as ButterKnife, FinalBitmap, and FinalDb.
- Android basic knowledge, that is the basic knowledge, the four main components, process communication, Material Design with these can be.
Looking at a framework is primarily about understanding the architecture and knowing what problems the architecture addresses. Of course, in addition to fast, universal, high expansion, there are still many indicators to consider, such as stability, fault tolerance, memory occupancy, operation speed, these contents will be specially sorted out in the future article comparison summary.
2. Outline presentation of framework content
Iii. Implementation and use of various levels of the framework
1. Framework level
1) UIFramework: mainly includes PlutoActivity, PlutoFragment, PlutoDialog, Toast, ButterKnife, UIHandler, FinalBitmap. 2) ServiceFramework: mainly includes LogicManager, PlutoApiEngine, CommonAsyncTask, AsyncTaskManager. 3) NetworkFramework: mainly including ApiClient, HttpClient, StringUtils. 4) DataFramework: mainly includes DataManagerProxy, DataManager, DataManagerStub, FinalDb, SharePreferenceUtil, PlutoFileCache.
2. Framework diagram
3. UI Framework
1) PlutoActivity, which inherits AppCompatActivity as a base class to integrate PlutoDialog, Toast, UIHandler, SoftInputManager, Timer, ActionBar, CommonAsyncTask add and cancel. Subclasses inherit PlutoActivity and use the common methods exposed by the integration. The Pluto framework cannot directly add ButterKnife to Gradle for UI binding outside of the framework. You need to add it in your own project. The sample code is as follows:
public class PlutoActivityExample extends PlutoActivity implements OnClickListener{... loadingDialog.show();// With the LOADING style in PlutoDialog by default
showSoftInput();// Display input method
isNetworkConnected();// Determine the network
mUiHandler.sendEmptyMessage(10000);// The default weak Handler sends Message
cancelAsyncTask(calculator); // Observer cancel current CommonAsyncTask or LogicManager
showHomeAsUp();//ActionBar displays the return icon
// Rewrite the PlutoActivity handleUiMessage to handle messages
@Override
public void handleUiMessage(Message msg) {
super.handleUiMessage(msg); }... }Copy the code
② The effect picture is as follows:
2) PlutoFragment, which inherits ProgressFragment as its base class and integrates Loading View and show Data timing control. PlutoFragment increased FragmentUserVisibleController solved when fragments or ViewPager ViewPager nested child fragments mUserVisibleHint attributes with the father Fragment of mU The serVisibleHint attribute synchronization problem is not repeated with PlutoActivity integration. The sample code is as follows:
public class BlogFragment extends PlutoFragment {...@Override
protected void showData() {// It is loaded by default. You need to specify when to display data
setContentShown(true); }... isVisibleToUser();// Check whether it is on the current screen. }Copy the code
② The effect picture is as follows:
PlutoDialog, PlutoDialog, PlutoDialog, PlutoDialog, PlutoDialog, PlutoDialog, PlutoDialog, PlutoDialog ① Code sample for example:
.// The system defaults to the Dialog style, providing only prompt Settings. This refers to the button callback interface implementation class
new PlutoDialog(this, PlutoDialog.DEFAULT_EXIT, this).show();
// The system default Dialog style, this refers to the button click callback interface implementation class
new PlutoDialog(this,PlutoDialog.DEFAULT,"Title"."Dialog show message"."left button"."right button".this).show();
//Loading prompt dialog box
new PlutoDialog(this,PlutoDialog.LOADING).show();
//TEXT_ONLIY displays only text, without any buttons or other controls
new PlutoDialog(this, PlutoDialog.TEXT_ONLIY, "Text Only").show(); .Copy the code
② The effect picture is as follows:
4) FinalBitmap, which is the image loading framework of Afinal framework, not explained too much here. ① Code sample for example:
finalBitmap = FinalBitmap.create(this);
finalBitmap.configLoadingImage(R.drawable.pluto_corner);
finalBitmap.configLoadfailImage(R.drawable.pluto_corner);
finalBitmap.display(imageView2,"http://m8en.com:8877/content/charmword_thumbnail.png");Copy the code
② The effect picture is as follows:
4. Data Framework
1) DataManagerStub, which implements the DataManager class as a stub class. In addition to meeting the interface specified by the specified DataManager, you can customize empty methods to provide an optional implementation for inherited classes.
public class DataManagerStub implements DataManager {
@Override
public void saveData(Object key, Object object) {}@Override
public <T> T queryData(Object key, Class<T> clazz) {
return null;
}
@Override
public <T> void deleteData(Object key, Class<T> clazz) {}@Override
public void updateData(Object key, Object object) {}}Copy the code
2) FinalBitmap, which is the ROM framework of Afinal Sqlite, inherits DataManagerStub and implements saveData, queryData, deleteData and updateData methods, with some minor changes. For example, you can specify that the primary key is of any type that is not self-growing, and add saveOrUpdate methods like the saveOrUpdate method in the Hibernate framework in JavaEE. 3) SharePreferenceUtil is ORM encapsulation of SharePreference and XML to realize basic types and customized storage and read operations. It also inherits the DataManagerStub and implements the saveData, queryData, deleteData, and updateData methods. 4) PlutoFileCache, is specialized in processing file data storage read encapsulation class, inherit DataManagerStub and implement saveData, queryData, deleteData and updateData methods.
5) DataManagerProxy is a proxy, factory, and adaptation class. Its function is to build different types of instances of DataManager, and the proxy completes data operations, and adapates other feature methods except DataManager’s fixed add, delete, change, and query. It is also a class with functional responsibilities for scalability. The resulting operation is exposed as follows (Sqlite for example) :
.// Build an instance of DataType.SQLITE by proxy
DataManagerProxy dataManagerProxy = DataManagerProxy.getInstance(DataType.SQLITE);
// Save and update if present
dataManagerProxy.saveOrUpdate(user);
// Return model based on primary key
User user = dataManagerProxy.queryData(1000,User.class);
// Update data, save it if it doesn't exist
dataManagerProxy.saveOrUpdate(user);
// Delete data with primary key
dataManagerProxy.deleteData(1000,User.class); .Copy the code
6) The effect picture is as follows:
5. net work Framework parts
1) HttpClient, this is Apache’s official website download common_httpClient. jar class. Pluto uses the HttpClient, GetMethod, PostMethod, and HttpMethodParams classes. 2) ApiClient, which is a network data request management class, including UA, Get and Post method encapsulation, IO read, timeout, reconnect setting and return Result
and Result
> type json and model conversion. 3) StringUtil, the main functions are regular match filter HTML, friendly time prompt conversion, deal with network data content redundancy, etc. This part mainly uses APIClient class to provide PlutoAPIEngine with the acquisition of network data Result original data and the first collation. It is not recommended to use it directly, so no code sample is provided.
6. The Service Framework
1) PlutoApiEngine, which is an integration of Data Framework and Network Framework Data acquisition storage part, provides 12 kinds of general processing methods to obtain Data. Instead, use get to obtain network data and specify the return type as model User. The relationship between the cache and the network is cache first. After obtaining the network, save it to the cache and then return the latest data. CACHE_ADVANCE_AND_NETWORK_RETURN (CACHE_ADVANCE_AND_NETWORK_RETURN is preferred. Data is returned after the network obtains it.) CACHE_EXPIRED_AND_NETWORK_RETURN (cache expires, return when network data is obtained) and ONLY_NETWORK (only network data is obtained), which collates Result data for the second time. 2 x 2 x 3=12. If you need to increase the combination of network and cache relationships, you can extend it yourself.
2) LogicParam, which defines the constant names of the parameters required by LogicManager, including interface URLS, URL parameters, Handler’s What, cache keys, etc. LogicManager gets the values of these constants through reflection.
public class MyParam extends LogicParam {
public static final String DOMAIN = "http://m8en.com/";
public final class LoginParam{
public static final int WHAT = 10000;
public static final String URL = DOMAIN+"charmword/loginUser.action";
public static final String CACHEKEY = "user_info"; }}Copy the code
3) CommonAsyncTask (AsyncTask) implements Observer, which is a custom asynchronous task class, with custom thread pool ThreadPoolExecutor, BlockingQueue, WorkerRunnable, etc. Implement observer, in order to provide AsyncTaskManager to do add cancel all management. CancelAll () This method should not be written in the onDestroy() method so as not to interrupt the asynchronous task of the next Activity. 4) AsyncTaskManager, which inherits Observable, just adds CommonAsyncTasks and removes all CommonAsyncTasks. 5) LogicManager, which inherits CommonAsyncTask, PlutoApiEngine data Result for the third time. We also provide two extension methods: innerDoInBackgroundPre() and innerDoInBackgroundEnd(Object Object). In doInBackground, we use PlutoApiEngine to fetch data before and after the PlutoApiEngine. The entire LogicManager process is bound to an asynchronous thread, CommonAsyncTask. The LogicManager or LogicManager subclass is provided to the PlutoActivity subclass for instantiation, passing in a chain call argument. Pass in the parameters, including data acquisition 12 enumeration, enumeration here has special data format requirements, with “__” as the dividing line, easy to enumerate cutting, dynamic selection of cutting conditions call response processing method. LogicManager is the most efficient part of the whole framework, a single chain of simple chain calls to complete different logical data collation results.
Finally, we need to focus on LogicManager. Example code:
.new LogicManager(mUiHandler.User.class.GET__MODEL__ONLY_NETWORK)
.setParamClass(LoginParam.class)
.setParam(ParamName.PASSWORD, 123456)..setParam(ParamName.EMAIL,"minggo8en@gmail.com")
.setParam(ApiUrl.PASS, pass)
.setArg1(1)
.execute();
new LogicManager(mUiHandler.ServerURL.class.GET__LIST__CACHE_EXPIRED_AND_NETWORK_RETURN)
.setParamClass(ServerUrlParam.class)
.setCacheKey(ServerUrlParam.CACHEKEY)
.setLimitedTime(1)
.setParam(ApiUrl.PASS.pass)
.execute(a); .Copy the code
The renderings are examples of the effects in the UI Framework.
7. PlutoException parts
PlutoException inherits Exception to implement UncaughtExceptionHandler, which is used as the global capture of the application, including two main parts of processing. One part is not written to the errorlog folder for non-crash errors. Part of it is a crash error written to the Crashlog folder. As for whether to pop up a window to remind you to submit to the background or submit error information to the background every time you start the application, you need to expand according to your own project requirements. Sample code:
try{... }catch (IOException e) {
...
throw PlutoException.network(e);
}Copy the code
8. Flexible Utils section
AnimationUtils
BitmapUtil
DateUtil
DisplayUtil
EncryptUtils
FastBlur
FileUtils
LogUtils
NetworkUtils
PhotoUtil
PollingUtils
SharePreferenceUtils
StringUtils
ThreadPoolUtils
Every Util is a tool class that is often used in development. For example, LogUtils is output in Debug mode or not. The output can be a file. DateUtil Date conversion, formatting, optimizing text; DisplayUtil screen unit calculation, conversion. And some tools to help developers quickly complete the development of features.
Four. Frame source code
This is my Android open source framework Pluto, a more complete, faster, more stable MVC open source framework, AI also please laugh.
Years later, when a kid shouted to his pad, “What is Pluto?” “The pad replied: “Pluto is a celestial body in the solar system. But now the most relative knowledge is an architecture of Android, Named Pluto- Android, which enables Everybody to developing App on Android Platform easier…”
From then on, the child began a great ideal – afternoon back to school must be xiaoming’s Lollipop back.
Framework source code, description and Demo download github.com/minggo620/P…