ºÝºÝߣ

ºÝºÝߣShare a Scribd company logo
Android Pro Recipes

Gabriel Dogaru
gdogaru@gmail.com
Iasi-JUG, December 11, 2013
Topics
¡ñ App Lifecycle
¡ñ AsyncTask problems
¡ñ Some frameworks
¡ð Otto
¡ð Tape
¡ð Dagger
Credits
¡ñ Android App Anatomy - Eric Burke
¡ñ Concurrency in Android - G. Blake Meike
¡ñ infoq.com
Where it all starts - lifecyle
Install

Uninstall

App runs forever
Process 1

¡­¡­.

App runs forever

Pn
Activity

Activity
Process 1

Activity

Activity

¡­¡­.

App runs forever

Pn
Activity
Fragment

Fragment

Activity

Activity
Process 1

Activity

¡­¡­.

App runs forever

Pn
RIP

Fragment

Fragment

Activity

Activity
Process 1

Activity

¡­¡­.

App runs forever

Pn
RIP
¡ñ
¡ñ
¡ñ

Fragment

Fragment

Activity

Terminates application process
Managed by oom_adj
RIP Static Variables

Activity
Process 1

Activity

¡­¡­.

App runs forever

Pn
Android Pro Recipes
RIP
¡ñ

Garbage collection

Fragment

Fragment

Activity

Activity
Process 1

Activity

¡­¡­.

App runs forever

Pn
RIP

Fragment

Fragment

Activity

Activity
Process 1

Activity

¡­¡­.

App runs forever

Pn
Android Pro Recipes
Why Care?
What about that background task?

AsyncTask
¡ñ enables proper and easy use of the UI thread.
¡ñ

should ideally be used for short operations (a few
seconds at the most.)
AsyncTask
private class SomeTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//do some stuff
return result;
}
protected void onProgressUpdate(Integer... progress) {
//update progress if needed
}
protected void onPreExecute(Long result) {
//before
}
protected void onPostExecute(Long result) {
//after
}
}
AsyncTask
Activity

Activity

Activity
Process 1

¡­¡­.

App runs forever

Pn
AsyncTask
Activity

Activity

Activity
Process 1

¡­¡­.

App runs forever

Pn
Some AsyncTask
public static class BgTask extends AsyncTask<String, Void, String> {
private final Activity act;
public BgTask(Activity act) {
this.act = act;
}
@Override protected String doInBackground(String... args) {
// ¡­ doesn't matter what goes here...
}
@Override protected void onPostExecute(String args) {
act.onTaskComplete(args)
}
}
Some AsyncTask 2
public void initButton(Button button) {
button.setOnClickListener(
new View.OnClickListener() {
@Override public void onClick(View v) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... args) {
// ¡­ doesn't matter what goes here...
}
@Override
protected void onPostExecute(String args) {
onTaskComplete(args)
}
} .execute();
}
});
}
What to do?
¡ñ Weak Reference
¡ñ Persistent
¡ñ Cancellable
¡ñ Independent
Weak Reference

¡ñ Just make all references to the Activity weak
Weak Reference

¡ñ Just make all references to the Activity weak

DON¡¯T
Persistent AsyncTask
¡ñ Best effort completion
¡ñ Hold a reference to the task in static or Application
¡ñ Manage references to Activities (onPause,
onResume)
¡ñ Preserving ¡°single delivery¡± AsyncTask semantics
requires some fancy state management
Persistent AsyncTask
public class SafeHeavyweightAsyncTaskActivity
extends Activity implements HeavywightSafeTask.CompletionHandler{
static HeavywightSafeTask task;
@Override
public void onTaskComplete(String result) {
task = null;
((TextView) findViewById(R.id.display)).setText(result);
}
@Override
protected void onResume() {
super.onResume();
if (null != task) {
task.registerCompletionHdlr(this);
}}
@Override
protected void onPause() {
super.onStop();
if (null != task) {
task.registerCompletionHdlr(null);
}}
}
Persistent AsyncTask
public final class HeavywightSafeTask extends AsyncTask<String, Void, String> {
public static interface CompletionHandler { void onTaskComplete(String result);
}
private enum State { EXECUTING, FINISHED, NOTIFIED; }
private State state = State.EXECUTING;
private CompletionHandler handler;
private String result;
public void registerCompletionHdlr(HeavywightSafeTask.CompletionHandler hdlr) {
handler = hdlr;
notifyHdlr();
}
@Override
protected String doInBackground(String... params) {
// . . .
}
@Override
protected void onPostExecute(String res) {
result = res;
state = State.FINISHED;
notifyHdlr();
}
// . . .
Persistent AsyncTask
// . . .
private void notifyHdlr() {
if (null == handler) {
return;
}
switch (state) {
case EXECUTING:
break;
case FINISHED:
state = State.NOTIFIED;
handler.onTaskComplete(result);
break;
case NOTIFIED:
throw new IllegalStateException(
"Attempt to register after notification");
}
}
}
Cancellable
¡ñ Addresses tasks that can be abandoned
¡ñ Implement onCancel
¡ñ Call it from onPause
Cancellable AsyncTask
public class SafeLightweightAsyncTaskActivity
extends Activity implements LightweightSafeTask.CompletionHandler {
LightweightSafeTask task;
// . . .
/**
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
if (null != task) {
task.cancel(true);
task = null;
}
}
// . . .
Independent
¡ñ Use AsyncTask to submit tasks to a data
layer
¡°If you respect users, persist tasksto disk.¡±
- Jesse Wilson
Tape is a collection of queue-related classes for Android and
Java by Square, Inc.
Client UI

add()

Server

Task Queue
Task

Task

peek()
remove()

Service
How to update the ui?

background task
Activity

Activity

Activity
Process 1

¡­¡­.

App runs forever

Pn
How to update the ui?

background task
Activity

Activity

Activity
Process 1

¡­¡­.

App runs forever

Pn
Events !!!!!

LocalBroadcastManager
¡ñ standard Android way
¡ñ we all read about it
Publish
Intent intent = new Intent(BroadcastIds.LOCATION_UPDATED_ACTION);

intent.putExtra(BroadcastIds.CURRENT_LOCATION_KEY
,getCurrentLocation());

LocalBroadcastManager.getInstance(
getActivity()).sendBroadcast(intent);
Subscribing
// MyActivity
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive(
Context context, Intent intent) {
Location location =
(Location) intent.getParcelableExtra(
BroadcastIds.CURRENT_LOCATION_KEY);
showLocation(location);
}
};
//¡­.
Subscribe ¡­.
IntentFilter locationFilter = new IntentFilter(
BroadcastIds.LOCATION_UPDATED_ACTION);

@Override public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(getActivity())
.registerReceiver(receiver, locationFilter);
}

@Override public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(getActivity())
.unregisterReceiver(receiver);
}
Really?
Otto
*from Square
Registration
public class BaseFragment extends Fragment {
@Inject Bus bus;
@Override public void onResume() {
super.onResume();
bus.register(this);
}
@Override public void onPause() {
super.onPause();
bus.unregister(this);
}
}
Subscribing
@Subscribe
public void onLocationUpdated(Location l) {
showLocation(l);
}
Publishing
bus.post(getCurrentLocation());

//the first time
@Produce
public UserImage produceUserImage() {
return cachedUserImage;
}
Activity
@Subscribe

Bus

bus.post(...)
@Produce

Data Layer (Cache)
Otto API Summary
¡ñ
¡ñ
¡ñ
¡ñ
¡ñ

register(), unregister(), post()
@Subscribe, @Produce
Thread confinement
Compile time errors
Easy to test!
Dependency Injection to the Rescue

Dagger
¡ñ compile time injection
¡ñ based on Google Guice
@Inject
import javax.inject.Inject; // JSR-330
public class PublishFragment extends BaseFragment {
@Inject Bus bus;
@Inject LocationManager locationManager;
¡­
}
Constructor Injection

public class AccountUpdater {
private final Bus bus;
private final AccountService accounts;
@Inject public AccountUpdater(Bus bus,
AccountService accounts) {
this.bus = bus;
this.accounts = accounts;
}
}
Module
@Module(entryPoints = {
MainActivity.class
})
public static class ExampleModule {
Context appContext;
public ExampleModule(Context appContext) {
this.appContext = appContext;
}
@Provides
@Singleton
Bus provideBus() {
return new Bus();
}
}}
Integration 2
public class ExampleApp extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
objectGraph = ObjectGraph.create(new ExampleModule(this));
}
public ObjectGraph objectGraph() {
return objectGraph;
}
public <T> T get(Class<T> clazz) {
return objectGraph.get(clazz);
}
Integration 3
public class MainActivity extends Activity {
@Inject
Bus bus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((ExampleApp) getApplication()).objectGraph().inject(this);
}
}
Conclusions
¡ñ Managing the lifecycle can be tricky
¡ñ Always think of the corner cases
¡ñ Find the right tool to do the job and make
your life easier
¡ñ Event architecture can help
Further studdy
Tape ¡ú square.github.com/tape/
Otto ¡ú square.github.com/otto/
Dagger ¡ú square.github.com/dagger
Android Pro Recipes
Ad

Recommended

Android Loaders : Reloaded
Android Loaders : Reloaded
cbeyls
?
Loaders (and why we should use them)
Loaders (and why we should use them)
Michael Pustovit
?
Advanced android app development
Advanced android app development
Rachmat Wahyu Pramono
?
TDC2016SP - Trilha Node.Js
TDC2016SP - Trilha Node.Js
tdc-globalcode
?
Android architecture component - FbCircleDev Yogyakarta Indonesia
Android architecture component - FbCircleDev Yogyakarta Indonesia
Pratama Nur Wijaya
?
activity_and_fragment_may_2020_lakopi
activity_and_fragment_may_2020_lakopi
Toru Wonyoung Choi
?
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
Mike Nakhimovich
?
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroid
GDG Korea
?
Android Made Simple
Android Made Simple
Gabriel Dogaru
?
WaveMaker Presentation
WaveMaker Presentation
Alexandru Chica
?
Building at a glance
Building at a glance
Gabriel Dogaru
?
Grails
Grails
Gabriel Dogaru
?
Maven beyond hello_world
Maven beyond hello_world
Gabriel Dogaru
?
The Groovy Way
The Groovy Way
Gabriel Dogaru
?
Modern Rapid Application Development - Too good to be true
Modern Rapid Application Development - Too good to be true
WaveMaker, Inc.
?
How to define an api
How to define an api
Alexandru Chica
?
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
Lifeparticle
?
Asynchronous Programming in Android
Asynchronous Programming in Android
John Pendexter
?
Android - Background operation
Android - Background operation
Matteo Bonifazi
?
Android best practices
Android best practices
Jose Manuel Ortega Candel
?
Deep dive into Android async operations
Deep dive into Android async operations
Mateusz Grzechoci¨½ski
?
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
TECOS
?
Performance #6 threading
Performance #6 threading
Vitali Pekelis
?
Android Trainning Session 2
Android Trainning Session 2
Shanmugapriya D
?
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009
Viswanath J
?
Android concurrency
Android concurrency
Ruslan Novikov
?
Efficient Android Threading
Efficient Android Threading
Anders G?ransson
?
Android life cycle
Android life cycle
¬|çý ÁÖ
?
Session #6 loaders and adapters
Session #6 loaders and adapters
Vitali Pekelis
?
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
Anuradha Weeraman
?

More Related Content

Viewers also liked (8)

Android Made Simple
Android Made Simple
Gabriel Dogaru
?
WaveMaker Presentation
WaveMaker Presentation
Alexandru Chica
?
Building at a glance
Building at a glance
Gabriel Dogaru
?
Grails
Grails
Gabriel Dogaru
?
Maven beyond hello_world
Maven beyond hello_world
Gabriel Dogaru
?
The Groovy Way
The Groovy Way
Gabriel Dogaru
?
Modern Rapid Application Development - Too good to be true
Modern Rapid Application Development - Too good to be true
WaveMaker, Inc.
?
How to define an api
How to define an api
Alexandru Chica
?

Similar to Android Pro Recipes (20)

Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
Lifeparticle
?
Asynchronous Programming in Android
Asynchronous Programming in Android
John Pendexter
?
Android - Background operation
Android - Background operation
Matteo Bonifazi
?
Android best practices
Android best practices
Jose Manuel Ortega Candel
?
Deep dive into Android async operations
Deep dive into Android async operations
Mateusz Grzechoci¨½ski
?
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
TECOS
?
Performance #6 threading
Performance #6 threading
Vitali Pekelis
?
Android Trainning Session 2
Android Trainning Session 2
Shanmugapriya D
?
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009
Viswanath J
?
Android concurrency
Android concurrency
Ruslan Novikov
?
Efficient Android Threading
Efficient Android Threading
Anders G?ransson
?
Android life cycle
Android life cycle
¬|çý ÁÖ
?
Session #6 loaders and adapters
Session #6 loaders and adapters
Vitali Pekelis
?
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
Anuradha Weeraman
?
Lecture #4 activities &amp; fragments
Lecture #4 activities &amp; fragments
Vitali Pekelis
?
Android Best Practices
Android Best Practices
Yekmer Simsek
?
Inside the android_application_framework
Inside the android_application_framework
surendray
?
Not Quite As Painful Threading
Not Quite As Painful Threading
CommonsWare
?
Introduction to Android - Session 3
Introduction to Android - Session 3
Tharaka Devinda
?
Anatomy of android application
Anatomy of android application
Nikunj Dhameliya
?
Tech Talk: App Functionality (Android)
Tech Talk: App Functionality (Android)
Lifeparticle
?
Asynchronous Programming in Android
Asynchronous Programming in Android
John Pendexter
?
Android - Background operation
Android - Background operation
Matteo Bonifazi
?
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
TECOS
?
Android Trainning Session 2
Android Trainning Session 2
Shanmugapriya D
?
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009
Viswanath J
?
Session #6 loaders and adapters
Session #6 loaders and adapters
Vitali Pekelis
?
Android Best Practices - Thoughts from the Trenches
Android Best Practices - Thoughts from the Trenches
Anuradha Weeraman
?
Lecture #4 activities &amp; fragments
Lecture #4 activities &amp; fragments
Vitali Pekelis
?
Inside the android_application_framework
Inside the android_application_framework
surendray
?
Not Quite As Painful Threading
Not Quite As Painful Threading
CommonsWare
?
Introduction to Android - Session 3
Introduction to Android - Session 3
Tharaka Devinda
?
Anatomy of android application
Anatomy of android application
Nikunj Dhameliya
?
Ad

Recently uploaded (20)

"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
?
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
?
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
?
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
?
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
?
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
?
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
?
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
?
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
?
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
?
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
?
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
?
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
?
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
?
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
?
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
?
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
?
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
?
Wenn alles versagt - IBM Tape sch¨¹tzt, was z?hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape sch¨¹tzt, was z?hlt! Und besonders mit dem neust...
Josef Weingand
?
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
?
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
?
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
?
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
?
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
?
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
Information Security Response Team Nepal_npCERT_Vice_President_Sudan_Jha.pdf
ICT Frame Magazine Pvt. Ltd.
?
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
?
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
?
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
?
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Powering Multi-Page Web Applications Using Flow Apps and FME Data Streaming
Safe Software
?
9-1-1 Addressing: End-to-End Automation Using FME
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
?
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
?
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
?
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
?
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
?
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
?
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
?
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
?
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
?
Wenn alles versagt - IBM Tape sch¨¹tzt, was z?hlt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape sch¨¹tzt, was z?hlt! Und besonders mit dem neust...
Josef Weingand
?
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik - Passionate Tech Enthusiast
Raman Bhaumik
?
Ad

Android Pro Recipes