17 mayo 2017
The Android operating system provides a strong foundation for building apps that run well on a wide range of devices and form factors. That being said, we've listened to developer feedback; Issues like complex lifecycles and the lack of a recommended app architecture make it challenging to write robust apps.
We need to make it easier — and more fun — to write robust apps, empowering developers to focus on areas where they can innovate. Today we're announcing a guide to Android app architecture along with a preview of Architecture Components. Rather than reinventing the wheel, we're also recognizing the work done by popular Android libraries.
We know that there's more than one way to write Android applications. What we're providing is a set of guidelines that can help you architect an Android application to work best with the unique ways that Android interacts. The Android framework has well-defined APIs to handle contact points with the OS, such as Activities, but these are entry points into your application, not building blocks for your application architecture; Framework components don't force you to separate your data model from your UI components, or provide a clear way to persist data independent of the lifecycle.
Android Architecture Components work together to implement a sane app architecture, while they individually address developer pain points. The first set of these components helps you:
Lifecycle Components New lifecycle-aware components provide constructs to tie core components of your applications to lifecycle events, removing explicit dependency paths.
A typical Android observation model would be to start observation in onStart() and stop observation in onStop(). This sounds simple enough, but often times you'll have several asynchronous calls happening at once, all managing the lifecycles of their component. It's easy to miss an edge case. The lifecycle components can help.
Lifecycle, LifecycleOwner, and LifecycleObserver
The core class for all of this is Lifecycle. It uses an enumeration for the current lifecycle state along with an enumeration for lifecycle events to track the lifecycle status for its associated component.
LifecycleOwner is an interface that returns a Lifecycle object from the getLifecycle() method, while LifecycleObserver is a class that can monitor the component's lifecycle events by adding annotations to its methods. Putting this all together, we can create lifecycle-aware components that can both monitor lifecycle events and query 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 is an observable lifecycle-aware data holder class. Your UI code subscribes to changes in the underlying data, tied into a LifecycleOwner, and LiveData makes sure the observer:
This helps to eliminate many pathways for memory leaks, and reduces crashes by avoiding updates to stopped activities.
LiveData can be observed by many listeners, each tied to a lifecycle owner such as a Fragment or Activity.
ViewModel is a helper class that contains UI data for an Activity or Fragment that serves to separate view data ownership from UI controller logic. A ViewModel is retained as long as the scope of its Activity/Fragment is alive, including when the Activity/Fragmentis destroyed and recreated due to a configuration change; This allows ViewModel to make UI data available to the recreated activity or fragment instance. Wrapping UI data stored within the ViewModel with LiveData provides the data an observable lifecycle-aware home. LiveData handles the notification side of things while the ViewModel makes sure that the data is retained appropriately.
The Android Architecture Components also simplify data persistence with the Room library. Room provides an object-mapping abstraction layer that allows fluent database access while harnessing the full power of SQLite.
The core framework provides built-in support for working with raw SQL content. Although these APIs are powerful, they are fairly low-level and require a great deal of time and effort to use:
Room takes care of these concerns for you while providing an abstraction layer over SQLite.
There are three major components in Room:
To use Room, you annotate the Java data objects you wish to persist as entities, create a database containing these entities, and define a DAO class with the SQL to access and modify 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") ListgetAll(); @Insert void insertAll(User... users); } @Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); }
Architecture Components are designed to be standalone, but they're most effective when they're incorporated into an effective app architecture. Today we're launching a Guide to App Architecture that shows how to build a robust, modular, and testable app using Architecture Components. The Guide has three main goals:
We recommend all developers who have had to deal with these problems read the Guide; Even if you're happy with your existing app architecture, the Guide will have useful principles and insights.
We're planning to continue being opinionated, and to continue to introduce new Architecture Components to make it easier for Android developers to make informed choices when architecting their applications. We encourage you to try the preview and provide feedback on what we're doing, because we're all in this together to make robust Android app development easier and more fun.
To learn more about Android Architecture, check out: