Android and architecture

Original author: Android Developers Blog
  • Transfer

The Android operating system provides a powerful foundation for developing applications that work great on a wide variety of devices and form factors. Now, as they say, we heard developers ’complaints: it’s difficult to create“ bug-free ”applications in the context of complex life cycles of objects and the lack of a recommended application architecture.


We, the creators of Android, need to make writing sustainable applications simple and fun in order to translate the efforts of developers into the areas in which innovation can be created. Today we are announcing an Android application architecture guide and Architecture Components library previews. Instead of reinventing the wheel, we acknowledge the work done by the authors of popular third-party Android libraries (approx. Transl .: WAT?).




Tips and not prescriptions


It is clear that there are many ways to create Android applications. We want to offer a set of guidelines that could help develop the application architecture that best matches the behavior of the Android system. There are excellent APIs in the SDK for interacting with the OS, such as activations, but these are just common ground, not architecture bricks; SDK components do not require separating the data model from the UI components and do not provide normal ways to store data regardless of the life cycle.


Building blocks


Architecture Components together help implement intelligent architecture, although individually they solve individual “popolobi” developers. The first version of the components helps:


  • Automatically manage life cycles of activity and fragments to avoid memory and resource leaks.
  • Store Java data model objects in SQLite.

Life cycle management components


New components provide constructs for binding the application core to life-cycle events, eliminating explicit dependencies. A typical observer model should start tracking at onStart()and stop at onStop(). It sounds simple enough, but often you have several simultaneous asynchronous calls, and all of them handle the life cycles of their components. You can easily skip any boundary case. And here new components can help.


Lifecycle, LifecycleOwner and LifecycleObserver


The main class for all this is Lifecycle. Himinside neonka there is ENUM for the current state of the life cycle, and ENUM for a set of events, and it uses them to track the life cycle of the component associated with it.


States and Events


LifecycleOwner- the interface that the object returns Lifecyclewhen called getLifecycle(), and LifecycleObserver- this is the class that can track component life cycle events if a couple of annotations are added to the component methods. By putting all this together, we can create components that automatically track life cycle events and can request the current lifecycle state.


public class MyObserver implements LifecycleObserver {
  public MyObserver(Lifecycle lifecycle) {
    // Starts lifecycle observation
    lifecycle.addObserver(this);
   ...
  }
  public void startFragmentTransaction() {
     // Queries lifecycle state
     if (lifecycle.getState.isAtLeast(STARTED)) {
        // perform transaction
     }
  }
  // Annotated methods called when the associated lifecycle goes through these events
  @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  public void onResume() {
  }
  @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
  public void onPause() {
  }
}
MyObserver observer = new MyObserver(aLifecycleOwner.getLifecycle());

Livedata


LiveData- a wrapper class for data that tracks the life cycle. And she knows how to "observable". Your UI can subscribe to changes to the data associated with LifecycleOwner, and LiveDatamake sure that observer:


  • Gets data updates while the component is in an active state ( STARTEDor RESUMED).
  • It is deleted when LifecycleOwnerdestroyed.
  • Gets current data when it LifecycleOwnerrestarts due to a configuration change or when returning from the back stack.

This helps eliminate a bunch of ways to get memory leaks and reduces the chance of crashes by preventing events from being sent to stopped activity.


On LiveDatamay be signed several listeners, each of which is fastened on the life cycle of a fragment or aktiviti.


ViewModel


ViewModel- an auxiliary class that contains user interface data for an activity or fragment and which serves to separate data management in the interface from the logic of the UI controller. The ViewModel is maintained as long as the habitat of its activity or fragment is alive, including situations where the activity or fragment is destroyed and recreated due to a configuration change. This allows the ViewModel to make UI data available to recreated activity or fragments without the need for manual recovery. Wrapping UI data stored in the ViewModel into a LiveData object creates for the datawarm cozyhouse with life cycle support and observers (observable). LiveData monitors change notification mechanisms, and ViewModel ensures that data is saved and restored at the right time.


Data persistence


Architecture Components also simplifies data storage with the Room library .


The "room" provides an object-mapping abstracion layer, which allows easy access to the database along with all the power of SQLite. The Android SDK provides native support for working with raw SQL content. Although this is a powerful API, it is quite low-level and requires a lot of time and effort:


  • There is no validation of raw SQL queries at compile time.
  • If you change the data schema, you must manually update the affected SQL queries. This process can be lengthy and error prone.
  • You need to write a bunch of boilerplate code to convert between SQL and Java data model objects.

Room takes on all of these responsibilities, providing a layer of abstraction over SQLite.


Database, Entity, and DAO


The Room library has three main components:


  • Entity represents data for a single row of the database and is created using an annotated Java data model object. Each Entity is stored in its own table.
  • The DAO (Data Access Object) defines methods that access the database, using annotations to bind SQL to each method.
  • Database is the custodian of one database, which uses annotations to determine the list of entities and the version of the database. The contents of the class defines a DAO list. Database is also the main way to access the database connection under the hood.

Room Architecture Diagram


To use Room, you need to annotate the Java objects that you want to store as entities, create a database containing these entities and define a DAO class with SQL code to access and modify tables in the database.


@Entity
public class User {
    @PrimaryKey
    private int uid;
    private String name;
    // Getters and Setters - required for Room
    public int getUid() { return uid; }
    public String getName() { return name; }
    public void setUid(int uid) { this.uid = uid; }
    public void setName(String name) { this.name = name; }
}
@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List getAll();
    @Insert
    void insertAll(User... users);
}
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

Application Architecture Guide


Architecture Components are designed for individual use, but they are most effective when used in an efficient application architecture.
Today we are launching the “Application Architecture Guide” , which shows how to create robust, modular, and testable applications using Architecture Components. This guide serves three main purposes:


  • Defines principles that are suitable for developing Android applications.
  • Describes the architecture of an application that runs on these principles.
  • Shows how to implement this architecture using Architecture Components.

We recommend that all developers who have to deal with these problems read the "Guide"; even if you are happily married to your current architecture, you will find useful principles and tips in the Guidebook.


This is just the beginning.


We are going to be stubborn and continue to develop new parts of Architecture Components to make it easier for Android developers to make informed choices when developing the architecture of their applications. We urge you to try the preview and leave feedback about our work, since we are all in the same boat here to make developing sustainable applications easier and more fun. Learn more about Android architecture here:


Only registered users can participate in the survey. Please come in.

Will you use a Google bike for Lifecycle Management?

  • 14.4% Already have [library name], see one more 22
  • 33.5% If it does not stall, I will 51
  • 34.2% Looks nothing, I'll try in a new project 52
  • 4.6% I will translate all my stuff on Android Architecture 7
  • 13.1% What is Lifecycle Management? 20

Will you use a Google bike for Data Persistance?

  • 16.3% Already have [library name], see one more 26
  • 32% If it does not stall, I will 51
  • 38.9% Looks nothing, I'll try in a new project 62
  • 3.1% I will translate all my stuff on Android Architecture 5
  • 9.4% What is Data Persistance? fifteen

Also popular now: