Android Framework Design

Source: Internet
Author: User
Tags finally block

The main content of this article is from a PPT document I mentioned earlier. Now I will organize it as follows. Thank you for your correction. The following content is based on my own experience. You are welcome to give more suggestions.

1. Concepts

Mode definition:

Each mode describes a problem that is constantly emerging in our environment, and then describes the core of the solution to the problem. In this way, you can use existing solutions countless times without repeating the same work.

What is the design model?

The design pattern is a typical and common solution to a specific problem under certain special circumstances.

We need to properly understand and learn some design patterns. In the process of program development, there will always be something like Framework Design and module design. If we can understand and run the design pattern well, the modules or frameworks you have designed will be much more stable, because these design patterns are all common solutions that have gained practical experience.

For example, in a program, there may be a notification module. Module A's data changes and Module B needs to be notified. For such a requirement, you may think of broadcasting ", the methods of "message" or "Callback" can indeed be solved by the three methods I mentioned earlier. However, these three methods all have some disadvantages, such as broadcast, it is very difficult to use intent to transmit data. For "messages", it cannot be well tracked. For "Callback", it is possible that modules A and B cannot access each other at all. At this time, if you useObserverThis problem can be easily solved.

Of course, we need to analyze specific problems here. I mainly mean that we should use the mode appropriately and we cannot use the mode to use it, we need to use the pattern to solve our actual problems.

Conceptual integrity

I have elaborated on the concept integrity in the book man-month myth. Here I will write my understanding and share it with you.

1) conceptual integrity is the most important factor in system design. The larger your system, the more obvious it is.

2) In order to gain conceptual integrity, the design must be completed by one person or a small team with consensus. This is easy to understand. design can involve everyone, but the decision is in the hands of a few people. If everyone wants to participate in the design, there is no way to ensure that the system design is unified and complete.

3) to gain conceptual integrity, someone must control these concepts, similar to the authoritarian regime of the nobility. Here, the Project Manager or architect in the team must have absolute authority for the project. Otherwise, the project cannot have a uniform order.

4) conceptual integrity:

-Consistency of requirements, designs, and codes during development
-The entire program has a uniform style, such as the dialog box style, button style, tone, and other UI elements.
-The specific and unified structure of the entire program. For example, different modules access the network and their calling methods are the same. For example, asynchronous access uses callback to notify the results. The same functions should be extracted into common modules.
-Developers can execute the intent of the requirement personnel and the designer well.
-Complete documents, Requirement documents, design documents, test documents, and process documents are provided.

How to maintain conceptual integrity

-The system guarantees that the product owner must establish absolute technical authority.
-The technical personnel (SE, SL) must strictly implement the project requirements, design the project, and go deep into the coding details.
-Maintain continuous communication with all personnel at different stages and encourage developers to provide comments.
-Involve developers in the design without deciding on the Design
-Achieve module reuse through continuous feedback and communication

2. What should I do before design?

2.1 Design of common categories

2.1.1 widget Design

  • Textview
  • Edittext
  • Button
  • Title Bar
  • Tool bar
  • ...

Why do we provide these common controls?

  • Unified font size. For example, the app Font does not change with the system font.
  • Unified UI style, such as button and edittext with the same background
  • Reuse code

2.1.2 adapter items

  • Extract the items to be displayed in adapterview according to the style
  • Simple compound layout
  • Auto-draw to improve sliding performance
    -Improves the uplink/downlink slide performance when adding Gallery in listview.
    -Optimize rendering as much as possible

Data-driven

  • Adapter items provides core methods
    -Setdata (Object Data)
    -Getdata ();
  • Adapter # getview implementation is simpler
    -Simple implementation
    -The UI will not change.

The following code demonstrates the implementation of the adapter # getview () method, which returns bookview. bookview provides a method to receive data. As for the display of bookview, it is displayed based on the set data, this is the data-driven UI.

@Overridepublic View getView(int position, View convertView, ViewGroup parent) {    if (null == convertView) {        convertView = new BookView(getContext());        convertView.setLayoutParameter(new AbsListView.LayoutParameter(150, 150));    }    Book book = m_bookList.get(position);    BookView bookView = (BookView)convertView;    bookView.setBook(book);    return convertView;}

2.1.3 Dialog

  • Extended to the dialog class
  • Provide the dialog closed event
  • The dialog height varies with the content.
  • You can set the text, visibility, and font of buttons.
  • Set the listener of the button click event
  • Three attributes of the dialog box should be considered: title, content area, action buttons

2.1.4 Utility

  • Log
  • Dateformat
  • Bitmap
  • Notification
  • Shared preference
  • Environment
  • Device
  • ...

2.2 Task Management

The thread is just a mechanism to ensure that the tasks we want to complete do not run in the UI thread (that is, do not block the UI). The completed tasks are the core of our attention. Therefore, we can design, encapsulate the thread so that the user does not feel it is a thread. He only needs to care about what he wants to do.
Here, we can design a "Asynchronous chained call" framework to encapsulate threads. You only need to use it like this:

new TaskManager().next(task1).next(task2).next(task3)..execute();

Here, Task 1, Task 2, and task 3 are executed sequentially. For example, to access the network and obtain an image, we need three tasks to use TASKMANAGER,

Task1: displays a progressdialog.

Task2: access the network and create a bitmap.

Task3: closes the dialog box and displays bitmap.

For more information, see the task. taskmanager class in the corelib project.

Note the following for taskmanager:

  • Encapsulated thread
  • Allow callers to focus only on their own business processing
  • Ensure sequential chained execution of a task
  • Output of the previous task as input of the next task
  • Can pause or resume any task

2.3 Cache Design

  • Store objects with large memory usage in the cache, such as bitmap
  • Implemented using the lrucache class
  • The asynctask class is used to load bitmap
  • You do not need to manually release the bitmap memory. This operation is risky.
  • No need to care about the scroll status of abslistview

For more details about cache, refer to [cache package in corelib project].

In this way, there is no need to manually release the bitmap, and this operation is risky because the bitmap has view references. If a view tries to draw a recycled bitmap, an exception is thrown here.

2.4 thread management

Threads without message loops:

new Thread(null, new Runnable() {    public void run() {        // Do you works.    }}, "Thread_name_xxx").start();

When to use this thread:

  • The process ends when you finish one task. The frequency of this task is not high, for example, reading image data from the SD card.
  • No need to reuse threads

When using a thread, it is best to add a name to the thread so that the height and tracking can be used.

Threads with message loops:

Such a thread has a message loop. When there is no message in the message queue, this thread will be suspended. To do one thing, you only need to send a message to it.

This is usually used to reuse threads without frequently creating threads. For example, the music player program starts a thread with a message loop to obtain the album pictures of music.

We usually need to create a handler associated with the message loop of this thread to process messages. Note that this is done in the background thread.

3. How to Design the program framework

Android program structure

  • UI Layer

    • Data presentation and Management
    • User Interaction
    • Draw
    • Adapter
  • Business logic layer
    • Persistent data (in memory, equivalent to global data)
    • Data addition (data at the data layer sometimes needs to be processed into the data required by the UI Layer)
    • Notification mechanism for data changes
  • Data Layer
    • Data Access (dB, file, network, etc)
    • Cache (images, files, etc)
    • Configuration file (shared perference)

Next, I tried to draw an android program structure. If there is something bad, please correct me.




4. Some basic principles

The following lists some common principles that we should follow during the development process. You are welcome to add them and correct them.

4.1 provide the initialize () method

It is called in the activity. oncreate () or view constructor. When you look at the code later, people usually first look for methods like initialize.

4.2 encapsulate click events

In this way, only a method caller is called at the listener. The general event is encapsulated as onxxxclick (view V ).

4.3 design a baseactivity class

Let all activities inherit from the baseactivity class, so that we can do a lot of useful things

  • Define common attributes
  • Show Common Dialog Box (Progress DIALOG)
  • Get top Activity
  • You can manually manage started activities

4.4 design application class

  • Store global data, such as top activity and application context.

4.5 Exception Handling

  • The report function is the essence of exception handling.
  • Clear the finally Block
  • Do not use try-catch-finally to judge the business logic.
  • Consider designing custom exception classes

4.6 usage of Annotation

  • The override method must be added with @ override.
  • Do not delete unused methods. You can mark them as @ deprecated, which is particularly useful in maintenance projects.

4.7 registration and anti-registration

  • Local Broadcast
  • Various listener
  • Service, etc.

4.8 encapsulate bitmap operations

We should encapsulate bitmap operations, such as file loading, storage, network download, and dynamic calculation of sample size. With the encapsulation, We can optimize it in a centralized manner.

4.9 Rendering

Do not create new objects in ondraw ()/ontouchevent.

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.