SlideShare une entreprise Scribd logo
1  sur  40
Android Architecture Components
July 1, 2017
Architecture
Components
Lifecycles
Lifecycle-aware observables
Lightweight ViewModel
Object mapping for sqlite
2
A New Hero Emerges
3
@Override
protected void onStart() {
super.onStart();
Sensor.observe(...);
requests.observe(...);
expensiveFoo.start(...);
whenDoesThisEnd.pleaseSaveMe
();
}
@Override
protected void onStop() {
super.onStop();
Sensors.removeObserver(...);
request.cancel(...);
expensiveFoo.stop();
}
Lifecycles
whenDoesThisEnd.iForgotThisCall();
4
public abstract class Lifecycle {
@MainThread
public abstract void addObserver(LifecycleObserver observer);
@MainThread
public abstract void removeObserver(LifecycleObserver observer);
@MainThread
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
....
}
@SuppressWarnings("WeakerAccess")
public enum State {
....
}
}
5
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(State state) {
return compareTo(state) >= 0;
}
}
6
7
LifecycleOwner
LifecycleObserver
8
public interface LifecycleOwner {
/**
* Returns the Lifecycle of the provider.
*
* @return The lifecycle of the provider.
*/
Lifecycle getLifecycle();
}
9
public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
public LifecycleActivity() {
}
public LifecycleRegistry getLifecycle() {
return this.mRegistry;
}
}
public class LifecycleFragment extends Fragment implements LifecycleRegistryOwner {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
public LifecycleFragment() {
}
public LifecycleRegistry getLifecycle() {
return this.mLifecycleRegistry;
}
}
10
public class LocationActivity extends LifecycleActivity {
private MyLocationListener myLocationListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myLocationListener = new MyLocationListener(getApplicationContext(),
getLifecycle(), location -> {
});
}
}
No more onStart and onStop
11
public class MyLocationListener implements LifecycleObserver {
private Context context;
private LocationListener locationListener;
private Lifecycle lifecycle;
MyLocationListener(Context context, Lifecycle lifecycle, LocationListener locationListener) {
this.context = context;
this.locationListener = locationListener;
this.lifecycle = lifecycle;
this.lifecycle.addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() {
//Start listener
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() {
//Stop listener
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void cleanUp() {
this.lifecycle.removeObserver(this);
}
interface LocationListener {
void onLocationChange(Location location);
}
}
12
ON_CREATE ON_START addObserver
ON_CREAT
E
ON_START
Activity’s perspective
Observer’s
13
ON_CREATE ON_START addObserver
ON_CREAT
E
ON_START
Activity’s perspective
Observer’s
ON_RESUME
14
ON_RESUME
E ON_START addObserver
ON_CREAT
E
ON_START
Activity’s perspective
Observer’s
ON_RESUME
15
ON_PAUSE
LiveData<T>
An observable data holder
Lifecycle aware
Automatic subscription management
16
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LiveData<Location> locationLiveData = //get from outside the World;
locationLiveData.observe(this, location -> {
});
}
17
This is LifecycleOwner
public class LocationData extends LiveData<Location> {
@Override
protected void onActive() {
super.onActive();
}
@Override
protected void onInactive() {
super.onInactive();
}
}
18
public class LocationData extends LiveData<Location> {
private LocationManager locationManager;
public LocationData(Context context) {
this.locationManager = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
}
private LocationListener locationListener = (location) -> {
this.setValue(location);
};
}
19
public class LocationData extends LiveData<Location> {
private LocationManager locationManager;
public LocationData(Context context) {
this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
private LocationListener locationListener = (location) -> {
this.setValue(location);
};
@Override protected void onActive() {
super.onActive();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);
}
@Override protected void onInactive() {
super.onInactive();
locationManager.removeUpdates(locationListener);
}
}
20
MutableLiveData<Location> mutableLiveData = new
MutableLiveData<>();
public LiveData<Location> getLocation() {
return this.mutableLiveData;
}
21
LiveData<User> userData;
@Override
protected void onCreate(@Nullable Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
userData = webservice.fetchUser(...);
userData.observe(this, user -> {
//update UI
});
}
22
And then configuration change
ViewModel
Data holder for UI Controllers
23
public class MyViewModel extends ViewModel {
private LiveData<User> userData;
public LiveData<User>getUser() {
if (userData == null) {
loadUsers();
}
return userData;
}
private void loadUsers() {
// do async operation to fetch users
}
}
24
@Override
protected void onCreate(@Nullable Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
ViewModelProviders.of(this).get(MyViewModel.class)
.getUser().observe(this, user -> {
//Update UI
});
}
25
public abstract class ViewModel {
/**
* This method will be called when this ViewModel is no
longer used and will be destroyed.
* <p>
* It is useful when ViewModel observes some data and you
need to clear this subscription to
* prevent a leak of this ViewModel.
*/
@SuppressWarnings("WeakerAccess")
protected void onCleared() {
}
}
26
Persistence
27
SQLite
Share Preferences
28
29
Hi
ROOM!
30
@Dao
interface FeedDao {
@Query("SELECT id, tiitle, subTitile FROM feed where title = :keyword")
List<Feed> loadFeed(String keyword);
}
@Entity
class Feed {
int id;
String title;
String subTitle;
}
31
@Database(entities = {Feed.class}, version 1)
abstract class MyDatabase extends RoomDatabase {
abstract FeedDao feedDao();
}
MyDatabase db = Room.databaseBuilder(getApplicationContext(),
MyDatabase.class)
.build();
db.feedDao().loadFeed(“xxxxx”);
32
@Query("SELECT id, tiitle, subTitile FROM Feeds where title = :keyword")
List<Feed> loadFeed(String keyword);
33
[SQLITE_ERROR] SQL error or missing database (no such table: feeds)
@Query("SELECT id, tiitle, subTitile FROM Feed where title = :keyword")
List<String> loadFeed(String keyword);
Error:(16, 18) error: Not sure how to convert a Cursor to this method’s return
type
Android Architecture
34
UI Controller (activities & fragments)
35
View Model
Repository
Data Sources
UI Controller
(activities & fragments)
36
View Model
Repository
Data Sources
● Activities & Fragments
● Observers the ViewModel
● Keeps the UI up-to-date
● Forwards user Actions back to
the ViewModel
● Prepares & keeps the data for the
UI
● Includes LiveData, Observables
etc
● Survives configuration changes
● The gateway for the Ul Controller
● The complete data model for the
App
● Provides simple data modification
& retrieval APIs
● API to the data sources
● E.g Retrofit for a REST API
● Room or Share preferences
UI Controller (activities & fragments)
37
View Model
Repository
Data Sources
Mock View Model
LiveData
Android Instrumentation Test with Espresso
38
ViewModel
Mock Repository
Android JUnit Test
39
Repository
Mock DataSource
Android JUnit Test
THANK YOU ~!
Email : khoatd19192@gmail.com
Skype : khoatd191
40

Contenu connexe

Tendances

Architecture Components
Architecture Components Architecture Components
Architecture Components DataArt
 
Android architecture components
Android architecture componentsAndroid architecture components
Android architecture componentsDiego Figueredo
 
SQLite 周りのテストをしよう
SQLite 周りのテストをしようSQLite 周りのテストをしよう
SQLite 周りのテストをしようussy
 
The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181Mahmoud Samir Fayed
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍louieuser
 
The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 29 of 185
The Ring programming language version 1.5.4 book - Part 29 of 185The Ring programming language version 1.5.4 book - Part 29 of 185
The Ring programming language version 1.5.4 book - Part 29 of 185Mahmoud Samir Fayed
 
The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31Mahmoud Samir Fayed
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
The Ring programming language version 1.5.3 book - Part 29 of 184
The Ring programming language version 1.5.3 book - Part 29 of 184The Ring programming language version 1.5.3 book - Part 29 of 184
The Ring programming language version 1.5.3 book - Part 29 of 184Mahmoud Samir Fayed
 
State of entity framework
State of entity frameworkState of entity framework
State of entity frameworkDavid Paquette
 
MySQL flexible schema and JSON for Internet of Things
MySQL flexible schema and JSON for Internet of ThingsMySQL flexible schema and JSON for Internet of Things
MySQL flexible schema and JSON for Internet of ThingsAlexander Rubin
 
Clustering your Application with Hazelcast
Clustering your Application with HazelcastClustering your Application with Hazelcast
Clustering your Application with HazelcastHazelcast
 
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkZeroTurnaround
 
Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Kevin Octavian
 

Tendances (19)

Architecture Components
Architecture Components Architecture Components
Architecture Components
 
Android architecture components
Android architecture componentsAndroid architecture components
Android architecture components
 
SQLite 周りのテストをしよう
SQLite 周りのテストをしようSQLite 周りのテストをしよう
SQLite 周りのテストをしよう
 
The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181The Ring programming language version 1.5.2 book - Part 28 of 181
The Ring programming language version 1.5.2 book - Part 28 of 181
 
Js 单元测试框架介绍
Js 单元测试框架介绍Js 单元测试框架介绍
Js 单元测试框架介绍
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202
 
The Ring programming language version 1.5.4 book - Part 29 of 185
The Ring programming language version 1.5.4 book - Part 29 of 185The Ring programming language version 1.5.4 book - Part 29 of 185
The Ring programming language version 1.5.4 book - Part 29 of 185
 
The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31The Ring programming language version 1.4.1 book - Part 8 of 31
The Ring programming language version 1.4.1 book - Part 8 of 31
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
The Ring programming language version 1.5.3 book - Part 29 of 184
The Ring programming language version 1.5.3 book - Part 29 of 184The Ring programming language version 1.5.3 book - Part 29 of 184
The Ring programming language version 1.5.3 book - Part 29 of 184
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
 
Drools rule Concepts
Drools rule ConceptsDrools rule Concepts
Drools rule Concepts
 
MySQL flexible schema and JSON for Internet of Things
MySQL flexible schema and JSON for Internet of ThingsMySQL flexible schema and JSON for Internet of Things
MySQL flexible schema and JSON for Internet of Things
 
Clustering your Application with Hazelcast
Clustering your Application with HazelcastClustering your Application with Hazelcast
Clustering your Application with Hazelcast
 
Easy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip OzturkEasy Scaling with Open Source Data Structures, by Talip Ozturk
Easy Scaling with Open Source Data Structures, by Talip Ozturk
 
Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1Windows 8 Training Fundamental - 1
Windows 8 Training Fundamental - 1
 
Drools Ecosystem
Drools EcosystemDrools Ecosystem
Drools Ecosystem
 
Drools
DroolsDrools
Drools
 

Similaire à Android Architecture - Khoa Tran

Architecture Components
Architecture ComponentsArchitecture Components
Architecture ComponentsSang Eel Kim
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT TalkConstantine Mars
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCaelum
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... AgainPedro Vicente
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»SpbDotNet Community
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageDroidConTLV
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
Cloud nativeworkshop
Cloud nativeworkshopCloud nativeworkshop
Cloud nativeworkshopEmily Jiang
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidRodrigo de Souza Castro
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaPratama Nur Wijaya
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture ComponentsBurhanuddinRashid
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3Jieyi Wu
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins buildacloud
 

Similaire à Android Architecture - Khoa Tran (20)

Architecture Components
Architecture ComponentsArchitecture Components
Architecture Components
 
Architecture components - IT Talk
Architecture components - IT TalkArchitecture components - IT Talk
Architecture components - IT Talk
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Don't Make Android Bad... Again
Don't Make Android Bad... AgainDon't Make Android Bad... Again
Don't Make Android Bad... Again
 
Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»Слава Бобик «NancyFx для самых маленьких»
Слава Бобик «NancyFx для самых маленьких»
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, Vonage
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Cloud nativeworkshop
Cloud nativeworkshopCloud nativeworkshop
Cloud nativeworkshop
 
A evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no androidA evolução da persistência de dados (com sqlite) no android
A evolução da persistência de dados (com sqlite) no android
 
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta IndonesiaAndroid architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
 
Design pattern - part 3
Design pattern - part 3Design pattern - part 3
Design pattern - part 3
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins
 

Plus de Tu Le Dinh

Deep dive into Google Cloud for Big Data
Deep dive into Google Cloud for Big DataDeep dive into Google Cloud for Big Data
Deep dive into Google Cloud for Big DataTu Le Dinh
 
Progressive web apps - Linh Nguyen
Progressive web apps  - Linh NguyenProgressive web apps  - Linh Nguyen
Progressive web apps - Linh NguyenTu Le Dinh
 
Introduction to reinforcement learning - Phu Nguyen
Introduction to reinforcement learning - Phu NguyenIntroduction to reinforcement learning - Phu Nguyen
Introduction to reinforcement learning - Phu NguyenTu Le Dinh
 
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...Tu Le Dinh
 
The potential of chatbot - Why NLP is important for chatbot - Duc Nguyen
The potential of chatbot - Why NLP is important for chatbot - Duc NguyenThe potential of chatbot - Why NLP is important for chatbot - Duc Nguyen
The potential of chatbot - Why NLP is important for chatbot - Duc NguyenTu Le Dinh
 
UI, UX: Who Does What? Where?-Vu Hoang
UI, UX: Who Does What? Where?-Vu HoangUI, UX: Who Does What? Where?-Vu Hoang
UI, UX: Who Does What? Where?-Vu HoangTu Le Dinh
 
Welcome remark from GDG mien trung
Welcome remark from GDG mien trungWelcome remark from GDG mien trung
Welcome remark from GDG mien trungTu Le Dinh
 
Google developer experts program - Hieu Hua
Google developer experts program - Hieu HuaGoogle developer experts program - Hieu Hua
Google developer experts program - Hieu HuaTu Le Dinh
 
Zero to one with Android Things - Hieu Hua
Zero to one with Android Things - Hieu HuaZero to one with Android Things - Hieu Hua
Zero to one with Android Things - Hieu HuaTu Le Dinh
 

Plus de Tu Le Dinh (9)

Deep dive into Google Cloud for Big Data
Deep dive into Google Cloud for Big DataDeep dive into Google Cloud for Big Data
Deep dive into Google Cloud for Big Data
 
Progressive web apps - Linh Nguyen
Progressive web apps  - Linh NguyenProgressive web apps  - Linh Nguyen
Progressive web apps - Linh Nguyen
 
Introduction to reinforcement learning - Phu Nguyen
Introduction to reinforcement learning - Phu NguyenIntroduction to reinforcement learning - Phu Nguyen
Introduction to reinforcement learning - Phu Nguyen
 
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...
How to build virtual assistant like Jarvis (in Ironman) with Google Assistant...
 
The potential of chatbot - Why NLP is important for chatbot - Duc Nguyen
The potential of chatbot - Why NLP is important for chatbot - Duc NguyenThe potential of chatbot - Why NLP is important for chatbot - Duc Nguyen
The potential of chatbot - Why NLP is important for chatbot - Duc Nguyen
 
UI, UX: Who Does What? Where?-Vu Hoang
UI, UX: Who Does What? Where?-Vu HoangUI, UX: Who Does What? Where?-Vu Hoang
UI, UX: Who Does What? Where?-Vu Hoang
 
Welcome remark from GDG mien trung
Welcome remark from GDG mien trungWelcome remark from GDG mien trung
Welcome remark from GDG mien trung
 
Google developer experts program - Hieu Hua
Google developer experts program - Hieu HuaGoogle developer experts program - Hieu Hua
Google developer experts program - Hieu Hua
 
Zero to one with Android Things - Hieu Hua
Zero to one with Android Things - Hieu HuaZero to one with Android Things - Hieu Hua
Zero to one with Android Things - Hieu Hua
 

Dernier

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Dernier (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Android Architecture - Khoa Tran

  • 3. A New Hero Emerges 3
  • 4. @Override protected void onStart() { super.onStart(); Sensor.observe(...); requests.observe(...); expensiveFoo.start(...); whenDoesThisEnd.pleaseSaveMe (); } @Override protected void onStop() { super.onStop(); Sensors.removeObserver(...); request.cancel(...); expensiveFoo.stop(); } Lifecycles whenDoesThisEnd.iForgotThisCall(); 4
  • 5. public abstract class Lifecycle { @MainThread public abstract void addObserver(LifecycleObserver observer); @MainThread public abstract void removeObserver(LifecycleObserver observer); @MainThread public abstract State getCurrentState(); @SuppressWarnings("WeakerAccess") public enum Event { .... } @SuppressWarnings("WeakerAccess") public enum State { .... } } 5
  • 6. public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast(State state) { return compareTo(state) >= 0; } } 6
  • 7. 7
  • 9. public interface LifecycleOwner { /** * Returns the Lifecycle of the provider. * * @return The lifecycle of the provider. */ Lifecycle getLifecycle(); } 9
  • 10. public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner { private final LifecycleRegistry mRegistry = new LifecycleRegistry(this); public LifecycleActivity() { } public LifecycleRegistry getLifecycle() { return this.mRegistry; } } public class LifecycleFragment extends Fragment implements LifecycleRegistryOwner { LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); public LifecycleFragment() { } public LifecycleRegistry getLifecycle() { return this.mLifecycleRegistry; } } 10
  • 11. public class LocationActivity extends LifecycleActivity { private MyLocationListener myLocationListener; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); myLocationListener = new MyLocationListener(getApplicationContext(), getLifecycle(), location -> { }); } } No more onStart and onStop 11
  • 12. public class MyLocationListener implements LifecycleObserver { private Context context; private LocationListener locationListener; private Lifecycle lifecycle; MyLocationListener(Context context, Lifecycle lifecycle, LocationListener locationListener) { this.context = context; this.locationListener = locationListener; this.lifecycle = lifecycle; this.lifecycle.addObserver(this); } @OnLifecycleEvent(Lifecycle.Event.ON_START) void onStart() { //Start listener } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) void onStop() { //Stop listener } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) void cleanUp() { this.lifecycle.removeObserver(this); } interface LocationListener { void onLocationChange(Location location); } } 12
  • 14. ON_CREATE ON_START addObserver ON_CREAT E ON_START Activity’s perspective Observer’s ON_RESUME 14 ON_RESUME
  • 15. E ON_START addObserver ON_CREAT E ON_START Activity’s perspective Observer’s ON_RESUME 15 ON_PAUSE
  • 16. LiveData<T> An observable data holder Lifecycle aware Automatic subscription management 16
  • 17. @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); LiveData<Location> locationLiveData = //get from outside the World; locationLiveData.observe(this, location -> { }); } 17 This is LifecycleOwner
  • 18. public class LocationData extends LiveData<Location> { @Override protected void onActive() { super.onActive(); } @Override protected void onInactive() { super.onInactive(); } } 18
  • 19. public class LocationData extends LiveData<Location> { private LocationManager locationManager; public LocationData(Context context) { this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); } private LocationListener locationListener = (location) -> { this.setValue(location); }; } 19
  • 20. public class LocationData extends LiveData<Location> { private LocationManager locationManager; public LocationData(Context context) { this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); } private LocationListener locationListener = (location) -> { this.setValue(location); }; @Override protected void onActive() { super.onActive(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener); } @Override protected void onInactive() { super.onInactive(); locationManager.removeUpdates(locationListener); } } 20
  • 21. MutableLiveData<Location> mutableLiveData = new MutableLiveData<>(); public LiveData<Location> getLocation() { return this.mutableLiveData; } 21
  • 22. LiveData<User> userData; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); userData = webservice.fetchUser(...); userData.observe(this, user -> { //update UI }); } 22 And then configuration change
  • 23. ViewModel Data holder for UI Controllers 23
  • 24. public class MyViewModel extends ViewModel { private LiveData<User> userData; public LiveData<User>getUser() { if (userData == null) { loadUsers(); } return userData; } private void loadUsers() { // do async operation to fetch users } } 24
  • 25. @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewModelProviders.of(this).get(MyViewModel.class) .getUser().observe(this, user -> { //Update UI }); } 25
  • 26. public abstract class ViewModel { /** * This method will be called when this ViewModel is no longer used and will be destroyed. * <p> * It is useful when ViewModel observes some data and you need to clear this subscription to * prevent a leak of this ViewModel. */ @SuppressWarnings("WeakerAccess") protected void onCleared() { } } 26
  • 29. 29
  • 31. @Dao interface FeedDao { @Query("SELECT id, tiitle, subTitile FROM feed where title = :keyword") List<Feed> loadFeed(String keyword); } @Entity class Feed { int id; String title; String subTitle; } 31 @Database(entities = {Feed.class}, version 1) abstract class MyDatabase extends RoomDatabase { abstract FeedDao feedDao(); }
  • 32. MyDatabase db = Room.databaseBuilder(getApplicationContext(), MyDatabase.class) .build(); db.feedDao().loadFeed(“xxxxx”); 32
  • 33. @Query("SELECT id, tiitle, subTitile FROM Feeds where title = :keyword") List<Feed> loadFeed(String keyword); 33 [SQLITE_ERROR] SQL error or missing database (no such table: feeds) @Query("SELECT id, tiitle, subTitile FROM Feed where title = :keyword") List<String> loadFeed(String keyword); Error:(16, 18) error: Not sure how to convert a Cursor to this method’s return type
  • 35. UI Controller (activities & fragments) 35 View Model Repository Data Sources
  • 36. UI Controller (activities & fragments) 36 View Model Repository Data Sources ● Activities & Fragments ● Observers the ViewModel ● Keeps the UI up-to-date ● Forwards user Actions back to the ViewModel ● Prepares & keeps the data for the UI ● Includes LiveData, Observables etc ● Survives configuration changes ● The gateway for the Ul Controller ● The complete data model for the App ● Provides simple data modification & retrieval APIs ● API to the data sources ● E.g Retrofit for a REST API ● Room or Share preferences
  • 37. UI Controller (activities & fragments) 37 View Model Repository Data Sources Mock View Model LiveData Android Instrumentation Test with Espresso
  • 40. THANK YOU ~! Email : khoatd19192@gmail.com Skype : khoatd191 40

Notes de l'éditeur

  1. kkkkkkk