SlideShare uma empresa Scribd logo
1 de 24
Isn’t Android just Java?
≠
Hint: If you know Android well, put
“Android” on your resume.
Key Differences
• Heterogeneous device capabilities
• Limited system resources
• Background tasks periodically killed
• Apps “stack” Activities
• Events handled by the OS
• Background processing common
• Blocking in UI thread yields an ANR
• Homogeneous virtual machine
• Lots of CPU and memory
• Lots of battery power
• Apps run in a dispatch loop
• Events handled within the app
• Background processing unusual
• Blocking in UI events semi-OK.
What happens when you get it wrong?
• Weird behavior when launching app
• App doesn’t function when phone sleeps
• Battery life and network issues
• Now you can’t access locks.
Common Pitfalls: Always Foreground
Problem: Android can kill background apps at any time to free resources.
Naïve solution #1: Ignore this.
“Why did I stop receiving
{mail, notifications, cat pictures} from your app?”
“It was supposed to alert me when ____, but didn’t”
“My music stopped playing in the middle of a song”
xkcd.com/937
When you know you’re doing it wrong
But don’t want to fix it
Can’t close this, ever… “…Or you’ll die in a car crash” So it kills your battery instead
The Right Way
Android apps can be killed any time they’re in the background. Accept this.
“Two hands clap and there is a sound.
What is the sound of one hand?”
The Right Way
Android will start your app again and restore its state when…
1. “Something interesting happens”, or
2. The user launches it again from history
onRestoreInstanceState()The catch: you have to write
The catch: you have to tell it what’s interesting!
Expressing Interest With Intents
PendingIntent
Intent
Intents will start your activity up again if it’s down.
PendingIntents tell Android to send them when certain things happen.
The Bad Way
package example;
import android.app.IntentService;
import android.content.Intent;
import java.util.concurrent.TimeUnit;
/**
* Prints out a message after 5 minutes - how not to do it.
*/
public class BadService extends IntentService {
public BadService() {
super("BadService");
}
@Override protected void onHandleIntent(Intent intent) {
try {
Thread.sleep(TimeUnit.MINUTES.toMillis(5));
} catch (InterruptedException e) {
// Because this is really bad code, we also ignore interrupts.
}
System.out.println("Your eggs are ready!");
}
}
The Right Way: Use Intents to Wake Your App
package example;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import java.util.Calendar;
/**
* Prints out a message after 5 minutes.
*/
public class GoodService extends IntentService {
public GoodService() {
super("GoodService");
}
public static void schedule(Context sender) {
AlarmManager alarmManager = (AlarmManager) sender.getSystemService(Context.ALARM_SERVICE);
Calendar alarmTime = Calendar.getInstance();
alarmTime.add(Calendar.MINUTE, 5);
Intent startGoodService = new Intent(sender, GoodService.class);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(),
PendingIntent.getService(sender, 0, startGoodService, 0));
}
@Override protected void onHandleIntent(Intent intent) {
System.out.println("Your eggs are ready!");
}
}
Common Pitfalls: Work on the UI Thread
Draw! Draw!
I have to find this file first!
The UI thread is busy responding to the user. Never distract it.
Jeff Miracola, Wizards of the Coast – “Frantic Search”
The Bad Waypackage example;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import java.io.InputStream;
import java.net.URL;
/**
* Displays a cat picture to the user, but crashes with a NetworkOnMainThreadException first.
*/
public class CatPictureActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
try {
drawCatPics();
} catch (Exception e) {
Log.e(getClass().getName(), "I haz an exception :(", e);
finish();
}
}
private void drawCatPics() throws Exception {
URL catApi = new URL("http://thecatapi.com/api/images/get");
InputStream catStream = (InputStream) catApi.getContent();
findViewById(R.id.cat_pics).setImageDrawable(Drawable.createFromStream(catStream, "Cats"));
}
}
The Right Way: AsyncTasks / Threads
package example;
import …;
/**
* Displays a cat picture to the user when the download finishes.
*/
public class CatPictureActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall());
catDownloader.addListener(new Runnable() {
@Override public void run() {
try {
findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get());
} catch (Exception e) {
Log.e(getClass().getName(), "I haz an exception :(", e);
finish();
}
}
}, Executors.newSingleThreadExecutor());
}
private class CatCall implements Callable<Drawable> {
@Override public Drawable call() throws Exception {
URL catApi = new URL("http://thecatapi.com/api/images/get");
InputStream catStream = (InputStream) catApi.getContent();
return Drawable.createFromStream(catStream, "Cats");
}
}
}
Common Pitfalls: Assuming Network Reliability
package example;
import …;
/**
* Displays a cat picture to the user when the download finishes.
*/
public class CatPictureActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall());
catDownloader.addListener(new Runnable() {
@Override public void run() {
try {
findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get());
} catch (Exception e) {
Log.e(getClass().getName(), "I haz an exception :(", e);
finish();
}
}
}, Executors.newSingleThreadExecutor());
}
private class CatCall implements Callable<Drawable> {
@Override public Drawable call() throws Exception {
URL catApi = new URL("http://thecatapi.com/api/images/get");
InputStream catStream = (InputStream) catApi.getContent();
return Drawable.createFromStream(catStream, "Cats");
}
}
}
What if Wifi is down?
No cat pics :(
The Right Way: Network State Intents
android.net.ConnectivityManager.CONNECTIVITY_ACTION
Android broadcasts an intent called
When the network state changes
and then you can check
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// Cat pics, here we come!
}
The Right Way
public class CatPictureActivity extends Activity {
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
registerReceiver(new NetReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private void setupTask() {
final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall());
catDownloader.addListener(new Runnable() {
@Override public void run() {
try {
findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get());
} catch (Exception e) {
Log.e(getClass().getName(), "I haz an exception :(", e);
finish();
}
}
}, Executors.newSingleThreadExecutor());
}
private class NetReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
unregisterReceiver(this); // Prevents a second run if the network goes down.
setupTask();
}
}
}
private class CatCall implements Callable<Drawable> {
@Override public Drawable call() throws Exception {
URL catApi = new URL("http://thecatapi.com/api/images/get");
InputStream catStream = (InputStream) catApi.getContent();
return Drawable.createFromStream(catStream, "Cats");
}
}
}
Summary
Android is not Java
≠
Your app is ephemeral
Use Intents, don’t try to keep it running
Don’t block the UI thread
Do work asynchronously on another thread
Check for connectivity
It can go up and down at any time
And if you know Android well,
put it on your resume.

Mais conteúdo relacionado

Mais procurados

Guide to Destroying Codebases The Demise of Clever Code
Guide to Destroying Codebases   The Demise of Clever CodeGuide to Destroying Codebases   The Demise of Clever Code
Guide to Destroying Codebases The Demise of Clever CodeGabor Varadi
 
IoT Fire Starter
IoT Fire StarterIoT Fire Starter
IoT Fire StarterDoug Seven
 
Capacity Management for Web Operations
Capacity Management for Web OperationsCapacity Management for Web Operations
Capacity Management for Web OperationsJohn Allspaw
 
Writing Virtual And Augmented Reality Apps With Web Technology
Writing Virtual And Augmented Reality Apps With Web TechnologyWriting Virtual And Augmented Reality Apps With Web Technology
Writing Virtual And Augmented Reality Apps With Web TechnologyMichaela Lehr
 
Rethink Async With RXJS
Rethink Async With RXJSRethink Async With RXJS
Rethink Async With RXJSRyan Anklam
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Beacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsBeacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsJeff Prestes
 
Meet the Eclipse SmartHome powered Mars Rover
Meet the Eclipse SmartHome powered Mars RoverMeet the Eclipse SmartHome powered Mars Rover
Meet the Eclipse SmartHome powered Mars RoverMichael Vorburger
 
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingIstanbul Tech Talks
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsNicholas Jansma
 
Naive application development
Naive application developmentNaive application development
Naive application developmentShaka Huang
 

Mais procurados (13)

Guide to Destroying Codebases The Demise of Clever Code
Guide to Destroying Codebases   The Demise of Clever CodeGuide to Destroying Codebases   The Demise of Clever Code
Guide to Destroying Codebases The Demise of Clever Code
 
IoT Fire Starter
IoT Fire StarterIoT Fire Starter
IoT Fire Starter
 
Capacity Management for Web Operations
Capacity Management for Web OperationsCapacity Management for Web Operations
Capacity Management for Web Operations
 
Writing Virtual And Augmented Reality Apps With Web Technology
Writing Virtual And Augmented Reality Apps With Web TechnologyWriting Virtual And Augmented Reality Apps With Web Technology
Writing Virtual And Augmented Reality Apps With Web Technology
 
Rethink Async With RXJS
Rethink Async With RXJSRethink Async With RXJS
Rethink Async With RXJS
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Beacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.jsBeacons, Raspberry Pi & Node.js
Beacons, Raspberry Pi & Node.js
 
Meet the Eclipse SmartHome powered Mars Rover
Meet the Eclipse SmartHome powered Mars RoverMeet the Eclipse SmartHome powered Mars Rover
Meet the Eclipse SmartHome powered Mars Rover
 
Angular js meetup
Angular js meetupAngular js meetup
Angular js meetup
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better NetworkingITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
ITT 2014 - Erik Hellmann - Android Programming - Smarter and Better Networking
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance Investigations
 
Naive application development
Naive application developmentNaive application development
Naive application development
 

Destaque

4150415
41504154150415
4150415kombi9
 
Donor voice pretest tool webinar deck_final
Donor voice pretest tool webinar deck_finalDonor voice pretest tool webinar deck_final
Donor voice pretest tool webinar deck_finalDonorVoice
 
BloomCon 2015 - Adrian Sargeant
BloomCon 2015 - Adrian SargeantBloomCon 2015 - Adrian Sargeant
BloomCon 2015 - Adrian SargeantBloomerang
 
15 Nonprofits #CrushingIt on Social Media
15 Nonprofits #CrushingIt on Social Media15 Nonprofits #CrushingIt on Social Media
15 Nonprofits #CrushingIt on Social MediaEverTrue
 
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...Carmen Holotescu
 
When Disaster Strikes
When Disaster StrikesWhen Disaster Strikes
When Disaster StrikesMary Morgan
 
file_Progress_Note_16_VC_Development_and_the_Poor[1]
file_Progress_Note_16_VC_Development_and_the_Poor[1]file_Progress_Note_16_VC_Development_and_the_Poor[1]
file_Progress_Note_16_VC_Development_and_the_Poor[1]Mary Morgan
 
When new meets old - online research methods for governement
When new meets old - online research methods for governementWhen new meets old - online research methods for governement
When new meets old - online research methods for governementLatitude Insights
 
Process Improvement - 10 Essential Ingredients
Process Improvement - 10 Essential IngredientsProcess Improvement - 10 Essential Ingredients
Process Improvement - 10 Essential IngredientsRichard Ouellette
 
Deja Las Lagrimas Rodar
Deja Las Lagrimas RodarDeja Las Lagrimas Rodar
Deja Las Lagrimas Rodarnimiaazucena
 
I heart presentation design
I heart presentation designI heart presentation design
I heart presentation designIdea Transplant
 
Ecim smart mobility issy 13032014
Ecim smart mobility issy 13032014Ecim smart mobility issy 13032014
Ecim smart mobility issy 13032014Hugo Kerschot
 
Namasmaran And Romance Dr Shriniwas Janardan Kashalikar
Namasmaran And Romance Dr  Shriniwas Janardan  KashalikarNamasmaran And Romance Dr  Shriniwas Janardan  Kashalikar
Namasmaran And Romance Dr Shriniwas Janardan Kashalikarbanothkishan
 
10 Essential Ingredients for Successful Corporate Coaching Programs
10 Essential Ingredients for Successful Corporate Coaching Programs 10 Essential Ingredients for Successful Corporate Coaching Programs
10 Essential Ingredients for Successful Corporate Coaching Programs Chronus
 

Destaque (20)

Test Dependencies and the Future of Build Acceleration
Test Dependencies and the Future of Build AccelerationTest Dependencies and the Future of Build Acceleration
Test Dependencies and the Future of Build Acceleration
 
Static Analysis and Verification of C Programs
Static Analysis and Verification of C ProgramsStatic Analysis and Verification of C Programs
Static Analysis and Verification of C Programs
 
Ontology-based Classification and Faceted Search Interface for APIs
Ontology-based Classification and Faceted Search Interface for APIsOntology-based Classification and Faceted Search Interface for APIs
Ontology-based Classification and Faceted Search Interface for APIs
 
4150415
41504154150415
4150415
 
Donor voice pretest tool webinar deck_final
Donor voice pretest tool webinar deck_finalDonor voice pretest tool webinar deck_final
Donor voice pretest tool webinar deck_final
 
BloomCon 2015 - Adrian Sargeant
BloomCon 2015 - Adrian SargeantBloomCon 2015 - Adrian Sargeant
BloomCon 2015 - Adrian Sargeant
 
15 Nonprofits #CrushingIt on Social Media
15 Nonprofits #CrushingIt on Social Media15 Nonprofits #CrushingIt on Social Media
15 Nonprofits #CrushingIt on Social Media
 
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...
OER and MOOC initiatives in Romania. Scenarios for integrating MOOCs in scho...
 
When Disaster Strikes
When Disaster StrikesWhen Disaster Strikes
When Disaster Strikes
 
Blogger
BloggerBlogger
Blogger
 
file_Progress_Note_16_VC_Development_and_the_Poor[1]
file_Progress_Note_16_VC_Development_and_the_Poor[1]file_Progress_Note_16_VC_Development_and_the_Poor[1]
file_Progress_Note_16_VC_Development_and_the_Poor[1]
 
When new meets old - online research methods for governement
When new meets old - online research methods for governementWhen new meets old - online research methods for governement
When new meets old - online research methods for governement
 
Process Improvement - 10 Essential Ingredients
Process Improvement - 10 Essential IngredientsProcess Improvement - 10 Essential Ingredients
Process Improvement - 10 Essential Ingredients
 
Sentence 1
Sentence 1Sentence 1
Sentence 1
 
Deja Las Lagrimas Rodar
Deja Las Lagrimas RodarDeja Las Lagrimas Rodar
Deja Las Lagrimas Rodar
 
I heart presentation design
I heart presentation designI heart presentation design
I heart presentation design
 
El proceso tecnologico
El proceso tecnologicoEl proceso tecnologico
El proceso tecnologico
 
Ecim smart mobility issy 13032014
Ecim smart mobility issy 13032014Ecim smart mobility issy 13032014
Ecim smart mobility issy 13032014
 
Namasmaran And Romance Dr Shriniwas Janardan Kashalikar
Namasmaran And Romance Dr  Shriniwas Janardan  KashalikarNamasmaran And Romance Dr  Shriniwas Janardan  Kashalikar
Namasmaran And Romance Dr Shriniwas Janardan Kashalikar
 
10 Essential Ingredients for Successful Corporate Coaching Programs
10 Essential Ingredients for Successful Corporate Coaching Programs 10 Essential Ingredients for Successful Corporate Coaching Programs
10 Essential Ingredients for Successful Corporate Coaching Programs
 

Semelhante a Android Apps the Right Way

Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - MonospaceFrank Krueger
 
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...mharkus
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesMichael Galpin
 
Android Wear: A Developer's Perspective
Android Wear: A Developer's PerspectiveAndroid Wear: A Developer's Perspective
Android Wear: A Developer's PerspectiveVin Lim
 
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial DetectionTomomi Imura
 
React Native Error Reporting with Sentry
React Native Error Reporting with SentryReact Native Error Reporting with Sentry
React Native Error Reporting with SentryAmin Yazdani Salekdeh
 
Our Data Ourselves, Pydata 2015
Our Data Ourselves, Pydata 2015Our Data Ourselves, Pydata 2015
Our Data Ourselves, Pydata 2015kingsBSD
 
Discussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source ComponentsDiscussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source ComponentsPVS-Studio
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Alfredo Morresi
 
Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mohammad Shaker
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom componentsJeremy Grancher
 
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...Constantine Mars
 
Bending the IoT to your will with JavaScript
Bending the IoT to your will with JavaScriptBending the IoT to your will with JavaScript
Bending the IoT to your will with JavaScriptAll Things Open
 
[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...BeMyApp
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Building a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfBuilding a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfShaiAlmog1
 

Semelhante a Android Apps the Right Way (20)

Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace
 
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Android Wear: A Developer's Perspective
Android Wear: A Developer's PerspectiveAndroid Wear: A Developer's Perspective
Android Wear: A Developer's Perspective
 
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection
[JS Kongress 2016] KittyCam.js - Raspberry Pi Camera w/ Cat Facial Detection
 
React Native Error Reporting with Sentry
React Native Error Reporting with SentryReact Native Error Reporting with Sentry
React Native Error Reporting with Sentry
 
Our Data Ourselves, Pydata 2015
Our Data Ourselves, Pydata 2015Our Data Ourselves, Pydata 2015
Our Data Ourselves, Pydata 2015
 
Android swedroid
Android swedroidAndroid swedroid
Android swedroid
 
Discussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source ComponentsDiscussing Errors in Unity3D's Open-Source Components
Discussing Errors in Unity3D's Open-Source Components
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)
 
Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.Mobile Software Engineering Crash Course - C04 Android Cont.
Mobile Software Engineering Crash Course - C04 Android Cont.
 
React Native custom components
React Native custom componentsReact Native custom components
React Native custom components
 
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...
Android Wear 2.0 - New Level of Freedom for Your Action - GDG CEE Leads Summi...
 
Bending the IoT to your will with JavaScript
Bending the IoT to your will with JavaScriptBending the IoT to your will with JavaScript
Bending the IoT to your will with JavaScript
 
FLAR Workflow
FLAR WorkflowFLAR Workflow
FLAR Workflow
 
[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Building a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfBuilding a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdf
 

Mais de New York City College of Technology Computer Systems Technology Colloquium

Mais de New York City College of Technology Computer Systems Technology Colloquium (9)

Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
 
Data-driven, Interactive Scientific Articles in a Collaborative Environment w...
Data-driven, Interactive Scientific Articles in a Collaborative Environment w...Data-driven, Interactive Scientific Articles in a Collaborative Environment w...
Data-driven, Interactive Scientific Articles in a Collaborative Environment w...
 
Cloud Technology: Virtualization
Cloud Technology: VirtualizationCloud Technology: Virtualization
Cloud Technology: Virtualization
 
Google BigTable
Google BigTableGoogle BigTable
Google BigTable
 
Pharmacology Powered by Computational Analysis: Predicting Cardiotoxicity of ...
Pharmacology Powered by Computational Analysis: Predicting Cardiotoxicity of ...Pharmacology Powered by Computational Analysis: Predicting Cardiotoxicity of ...
Pharmacology Powered by Computational Analysis: Predicting Cardiotoxicity of ...
 
How We Use Functional Programming to Find the Bad Guys
How We Use Functional Programming to Find the Bad GuysHow We Use Functional Programming to Find the Bad Guys
How We Use Functional Programming to Find the Bad Guys
 
Big Data Challenges and Solutions
Big Data Challenges and SolutionsBig Data Challenges and Solutions
Big Data Challenges and Solutions
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
More than Words: Advancing Prosodic Analysis
More than Words: Advancing Prosodic AnalysisMore than Words: Advancing Prosodic Analysis
More than Words: Advancing Prosodic Analysis
 

Último

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Último (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Android Apps the Right Way

  • 1.
  • 3. Hint: If you know Android well, put “Android” on your resume.
  • 4. Key Differences • Heterogeneous device capabilities • Limited system resources • Background tasks periodically killed • Apps “stack” Activities • Events handled by the OS • Background processing common • Blocking in UI thread yields an ANR • Homogeneous virtual machine • Lots of CPU and memory • Lots of battery power • Apps run in a dispatch loop • Events handled within the app • Background processing unusual • Blocking in UI events semi-OK.
  • 5. What happens when you get it wrong? • Weird behavior when launching app • App doesn’t function when phone sleeps • Battery life and network issues • Now you can’t access locks.
  • 6. Common Pitfalls: Always Foreground Problem: Android can kill background apps at any time to free resources. Naïve solution #1: Ignore this. “Why did I stop receiving {mail, notifications, cat pictures} from your app?” “It was supposed to alert me when ____, but didn’t” “My music stopped playing in the middle of a song” xkcd.com/937
  • 7. When you know you’re doing it wrong But don’t want to fix it Can’t close this, ever… “…Or you’ll die in a car crash” So it kills your battery instead
  • 8. The Right Way Android apps can be killed any time they’re in the background. Accept this. “Two hands clap and there is a sound. What is the sound of one hand?”
  • 9. The Right Way Android will start your app again and restore its state when… 1. “Something interesting happens”, or 2. The user launches it again from history onRestoreInstanceState()The catch: you have to write The catch: you have to tell it what’s interesting!
  • 10. Expressing Interest With Intents PendingIntent Intent Intents will start your activity up again if it’s down. PendingIntents tell Android to send them when certain things happen.
  • 11. The Bad Way package example; import android.app.IntentService; import android.content.Intent; import java.util.concurrent.TimeUnit; /** * Prints out a message after 5 minutes - how not to do it. */ public class BadService extends IntentService { public BadService() { super("BadService"); } @Override protected void onHandleIntent(Intent intent) { try { Thread.sleep(TimeUnit.MINUTES.toMillis(5)); } catch (InterruptedException e) { // Because this is really bad code, we also ignore interrupts. } System.out.println("Your eggs are ready!"); } }
  • 12. The Right Way: Use Intents to Wake Your App package example; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import java.util.Calendar; /** * Prints out a message after 5 minutes. */ public class GoodService extends IntentService { public GoodService() { super("GoodService"); } public static void schedule(Context sender) { AlarmManager alarmManager = (AlarmManager) sender.getSystemService(Context.ALARM_SERVICE); Calendar alarmTime = Calendar.getInstance(); alarmTime.add(Calendar.MINUTE, 5); Intent startGoodService = new Intent(sender, GoodService.class); alarmManager.setExact(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(), PendingIntent.getService(sender, 0, startGoodService, 0)); } @Override protected void onHandleIntent(Intent intent) { System.out.println("Your eggs are ready!"); } }
  • 13. Common Pitfalls: Work on the UI Thread Draw! Draw! I have to find this file first! The UI thread is busy responding to the user. Never distract it. Jeff Miracola, Wizards of the Coast – “Frantic Search”
  • 14. The Bad Waypackage example; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.util.Log; import java.io.InputStream; import java.net.URL; /** * Displays a cat picture to the user, but crashes with a NetworkOnMainThreadException first. */ public class CatPictureActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); try { drawCatPics(); } catch (Exception e) { Log.e(getClass().getName(), "I haz an exception :(", e); finish(); } } private void drawCatPics() throws Exception { URL catApi = new URL("http://thecatapi.com/api/images/get"); InputStream catStream = (InputStream) catApi.getContent(); findViewById(R.id.cat_pics).setImageDrawable(Drawable.createFromStream(catStream, "Cats")); } }
  • 15. The Right Way: AsyncTasks / Threads package example; import …; /** * Displays a cat picture to the user when the download finishes. */ public class CatPictureActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall()); catDownloader.addListener(new Runnable() { @Override public void run() { try { findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get()); } catch (Exception e) { Log.e(getClass().getName(), "I haz an exception :(", e); finish(); } } }, Executors.newSingleThreadExecutor()); } private class CatCall implements Callable<Drawable> { @Override public Drawable call() throws Exception { URL catApi = new URL("http://thecatapi.com/api/images/get"); InputStream catStream = (InputStream) catApi.getContent(); return Drawable.createFromStream(catStream, "Cats"); } } }
  • 16. Common Pitfalls: Assuming Network Reliability package example; import …; /** * Displays a cat picture to the user when the download finishes. */ public class CatPictureActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall()); catDownloader.addListener(new Runnable() { @Override public void run() { try { findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get()); } catch (Exception e) { Log.e(getClass().getName(), "I haz an exception :(", e); finish(); } } }, Executors.newSingleThreadExecutor()); } private class CatCall implements Callable<Drawable> { @Override public Drawable call() throws Exception { URL catApi = new URL("http://thecatapi.com/api/images/get"); InputStream catStream = (InputStream) catApi.getContent(); return Drawable.createFromStream(catStream, "Cats"); } } } What if Wifi is down? No cat pics :(
  • 17. The Right Way: Network State Intents android.net.ConnectivityManager.CONNECTIVITY_ACTION Android broadcasts an intent called When the network state changes and then you can check ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // Cat pics, here we come! }
  • 18. The Right Way public class CatPictureActivity extends Activity { @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); registerReceiver(new NetReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } private void setupTask() { final ListenableFutureTask<Drawable> catDownloader = ListenableFutureTask.create(new CatCall()); catDownloader.addListener(new Runnable() { @Override public void run() { try { findViewById(R.id.cat_pics).setImageDrawable(catDownloader.get()); } catch (Exception e) { Log.e(getClass().getName(), "I haz an exception :(", e); finish(); } } }, Executors.newSingleThreadExecutor()); } private class NetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null && info.isConnected()) { unregisterReceiver(this); // Prevents a second run if the network goes down. setupTask(); } } } private class CatCall implements Callable<Drawable> { @Override public Drawable call() throws Exception { URL catApi = new URL("http://thecatapi.com/api/images/get"); InputStream catStream = (InputStream) catApi.getContent(); return Drawable.createFromStream(catStream, "Cats"); } } }
  • 20. Android is not Java ≠
  • 21. Your app is ephemeral Use Intents, don’t try to keep it running
  • 22. Don’t block the UI thread Do work asynchronously on another thread
  • 23. Check for connectivity It can go up and down at any time
  • 24. And if you know Android well, put it on your resume.