SlideShare a Scribd company logo
Background operation
How to handle all your jobs
+RobertoOrgiu
@_tiwiz
+MatteoBonifazi
@mbonifazi
Threading & Background Tasks
Multithreading is essential if you want an Android app
with a great user experience, but how do you know which
techniques can help solve your problem?
Android threads
Android application has at least one main thread
The runtime env manages the UI thread.
Long-running foreground operations can cause problems
and interfere with the responsiveness of your user interface,
which can even cause system errors.
Android offers several classes that help you off-load
operations onto a separate thread that runs in the
background.
AsyncTask
AsyncTask represents a convenient way to
offload work from the main thread.
AsyncTask
Is meant for simple operations
Allows to run instructions in the background and to
synchronize again with the main thread. It also reporting
progress of the running tasks. AsyncTasks should be used
for short background operations which need to update the
user interface.
AsyncTask example
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
OkHttpClient client = new OkHttpClient();
Request request =new Request.Builder().url(urls[0]).build();
Response response = client.newCall(request).execute();
…..
}
@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
Run your code as a callback on UI ThreadRun your code on a new Thread
Parallel execution - AsyncTask
// ImageLoader extends AsyncTask
DownloadWebPageTask imageLoader = new DownloadWebPageTask( imageView );
// Execute in parallel
imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR,
"http://url.com/image.png" );
Intent Service
IntentService provides straightforward
structure for running an operation on a single
background thread.
IntentService
Preferred way to perform simple background
operations
Allows it to handle long-running operations without
affecting your user interface's responsiveness.
It isn't affected by most user interface lifecycle events, so it
continues to run in circumstances that would shut down an
AsyncTask
IntentService
Limitations
● It can't interact directly with your user interface. To put its
results in the UI, you have to send them to an Activity.
● Work requests run sequentially. If an operation is running
in an IntentService, and you send it another request, the
request waits until the first operation is finished.
● An operation running on an IntentService can't be
interrupted.
IntentService lifecycle
public class RSSPullService extends IntentService {
public RSSPullService() {
super(RSSPullService.class.getName());
}
@Override
protected void onHandleIntent(Intent workIntent) {
// Gets data from the incoming Intent
String dataString = workIntent.getDataString();
...
// Do work here, based on the contents of dataString
...
}
Other callbacks of a regular Service
component, such as onStartCommand() are
automatically invoked by IntentService.
Put here your background job
IntentService in the AndroidManifest
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
...
<!--
Because android:exported is set to "false",
the service is only available to this app.
-->
<service
android:name=".RSSPullService"
android:exported="false"/>
...
<application/>
The Activity that sends work requests to
the service uses an explicit Intent
Create a work request to the IntentService
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));
...
// Starts the IntentService
getActivity().startService(mServiceIntent);
Going forward
Youtube Video
https://www.youtube.com/watch?v=jtlRNNhane
https://www.youtube.com/watch?v=9FweabuBi1U
https://www.youtube.com/watch?v=tBHPmQQNiS8
Reference Link
https://developer.android.com/guide/components/processes-and-threads.html
https://developer.android.com/training/run-background-service/index.html
https://developer.android.com/training/multiple-threads/index.html
JobScheduler
Creating a job
public class AwesomeJobService extends JobService {
@Override
public boolean onStartJob(final JobParameters params) {
//AWESOME STUFF HERE
return true; // or false
}
@Override
public boolean onStopJob(JobParameters params) {
//AWESOME CLEANING HERE
return false; //or true
}
}
Scheduling a job
ComponentName component = new ComponentName(context, AwesomeJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(jobId, component)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setRequiresDeviceIdle(true)
...
.setRequiresCharging(false);
builder.setExtras(parameters);
JobScheduler s = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
s.schedule(builder.build());
Going forward - 2
Reference Link
https://developer.android.com/topic/performance/scheduling.html
https://developer.android.com/reference/android/app/job/JobScheduler.html
https://github.com/googlesamples/android-JobScheduler/
+MatteoBonifazi
@mbonifazi
Thank You!
+RobertoOrgiu
@_tiwiz

More Related Content

PDF
Android Networking
PDF
Android Networking
PDF
Chapter 27 Networking - Deitel & Deitel
PDF
Building the Internet of Things with Eclipse IoT - JavaLand 2014
PDF
Android things intro
PDF
どうしてコードはレガシーになるのか
PPTX
Gradle,the new build system for android
PDF
Android thingsやってみた
Android Networking
Android Networking
Chapter 27 Networking - Deitel & Deitel
Building the Internet of Things with Eclipse IoT - JavaLand 2014
Android things intro
どうしてコードはレガシーになるのか
Gradle,the new build system for android
Android thingsやってみた

Similar to Android - Background operation (20)

PPTX
Android Connecting to internet Part 2
PDF
MobileAppDev Handout#4
PDF
Asynchronous Programming in Android
PPTX
Threads handlers and async task, widgets - day8
PPTX
Android service, aidl - day 1
PPTX
Services I.pptx
PDF
Java Svet - Communication Between Android App Components
PDF
Java Svet - Communication Between Android App Components
PDF
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
PDF
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
PDF
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
PPTX
Android session-5-sajib
PPTX
Android Training (Services)
PDF
Not Quite As Painful Threading
PPTX
Background Thread
PDF
Android Best Practices - Thoughts from the Trenches
PDF
Android101
PPTX
Android 101 Session @thejunction32
PDF
[Android] Multiple Background Threads
PPTX
Threading model in windows store apps
Android Connecting to internet Part 2
MobileAppDev Handout#4
Asynchronous Programming in Android
Threads handlers and async task, widgets - day8
Android service, aidl - day 1
Services I.pptx
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
INTRODUCTION TO FORMS OF SERVICES AND ITS LIFE CYCLE
Android session-5-sajib
Android Training (Services)
Not Quite As Painful Threading
Background Thread
Android Best Practices - Thoughts from the Trenches
Android101
Android 101 Session @thejunction32
[Android] Multiple Background Threads
Threading model in windows store apps
Ad

More from Matteo Bonifazi (15)

PDF
Invading the home screen
PDF
Engage user with actions
PDF
Kotlin killed Java stars
PDF
Android JET Navigation
PDF
Firebase-ized your mobile app
PDF
Backendless apps
PDF
Android - Saving data
PDF
Android - Displaying images
PDF
The Firebase tier for your mobile app - DevFest CH
PDF
Engage and retain users in the android world - Droidcon Italy 2016
PDF
UaMobitech - App Links and App Indexing API
PDF
The unconventional devices for the Android video streaming
PDF
Google IO - Five months later
PDF
Video Streaming: from the native Android player to uncoventional devices
PDF
Enlarge your screen
Invading the home screen
Engage user with actions
Kotlin killed Java stars
Android JET Navigation
Firebase-ized your mobile app
Backendless apps
Android - Saving data
Android - Displaying images
The Firebase tier for your mobile app - DevFest CH
Engage and retain users in the android world - Droidcon Italy 2016
UaMobitech - App Links and App Indexing API
The unconventional devices for the Android video streaming
Google IO - Five months later
Video Streaming: from the native Android player to uncoventional devices
Enlarge your screen
Ad

Recently uploaded (6)

PDF
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
PDF
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
PPTX
ASMS Telecommunication company Profile
DOC
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
PDF
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
DOC
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证
6-UseCfgfhgfhgfhgfhgfhfhhaseActivity.pdf
Lesson 13- HEREDITY _ pedSAWEREGFVCXZDSASEWFigree.pdf
ASMS Telecommunication company Profile
证书学历UoA毕业证,澳大利亚中汇学院毕业证国外大学毕业证
heheheueueyeyeyegehehehhehshMedia-Literacy.pdf
Camb毕业证学历认证,格罗斯泰斯特主教大学毕业证仿冒文凭毕业证

Android - Background operation

  • 1. Background operation How to handle all your jobs +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi
  • 2. Threading & Background Tasks Multithreading is essential if you want an Android app with a great user experience, but how do you know which techniques can help solve your problem?
  • 3. Android threads Android application has at least one main thread The runtime env manages the UI thread. Long-running foreground operations can cause problems and interfere with the responsiveness of your user interface, which can even cause system errors. Android offers several classes that help you off-load operations onto a separate thread that runs in the background.
  • 5. AsyncTask represents a convenient way to offload work from the main thread.
  • 6. AsyncTask Is meant for simple operations Allows to run instructions in the background and to synchronize again with the main thread. It also reporting progress of the running tasks. AsyncTasks should be used for short background operations which need to update the user interface.
  • 7. AsyncTask example private class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { OkHttpClient client = new OkHttpClient(); Request request =new Request.Builder().url(urls[0]).build(); Response response = client.newCall(request).execute(); ….. } @Override protected void onPostExecute(String result) { textView.setText(result); } } Run your code as a callback on UI ThreadRun your code on a new Thread
  • 8. Parallel execution - AsyncTask // ImageLoader extends AsyncTask DownloadWebPageTask imageLoader = new DownloadWebPageTask( imageView ); // Execute in parallel imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );
  • 10. IntentService provides straightforward structure for running an operation on a single background thread.
  • 11. IntentService Preferred way to perform simple background operations Allows it to handle long-running operations without affecting your user interface's responsiveness. It isn't affected by most user interface lifecycle events, so it continues to run in circumstances that would shut down an AsyncTask
  • 12. IntentService Limitations ● It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity. ● Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished. ● An operation running on an IntentService can't be interrupted.
  • 13. IntentService lifecycle public class RSSPullService extends IntentService { public RSSPullService() { super(RSSPullService.class.getName()); } @Override protected void onHandleIntent(Intent workIntent) { // Gets data from the incoming Intent String dataString = workIntent.getDataString(); ... // Do work here, based on the contents of dataString ... } Other callbacks of a regular Service component, such as onStartCommand() are automatically invoked by IntentService. Put here your background job
  • 14. IntentService in the AndroidManifest <application android:icon="@drawable/icon" android:label="@string/app_name"> ... <!-- Because android:exported is set to "false", the service is only available to this app. --> <service android:name=".RSSPullService" android:exported="false"/> ... <application/> The Activity that sends work requests to the service uses an explicit Intent
  • 15. Create a work request to the IntentService mServiceIntent = new Intent(getActivity(), RSSPullService.class); mServiceIntent.setData(Uri.parse(dataUrl)); ... // Starts the IntentService getActivity().startService(mServiceIntent);
  • 16. Going forward Youtube Video https://www.youtube.com/watch?v=jtlRNNhane https://www.youtube.com/watch?v=9FweabuBi1U https://www.youtube.com/watch?v=tBHPmQQNiS8 Reference Link https://developer.android.com/guide/components/processes-and-threads.html https://developer.android.com/training/run-background-service/index.html https://developer.android.com/training/multiple-threads/index.html
  • 18. Creating a job public class AwesomeJobService extends JobService { @Override public boolean onStartJob(final JobParameters params) { //AWESOME STUFF HERE return true; // or false } @Override public boolean onStopJob(JobParameters params) { //AWESOME CLEANING HERE return false; //or true } }
  • 19. Scheduling a job ComponentName component = new ComponentName(context, AwesomeJobService.class); JobInfo.Builder builder = new JobInfo.Builder(jobId, component) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setRequiresDeviceIdle(true) ... .setRequiresCharging(false); builder.setExtras(parameters); JobScheduler s = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); s.schedule(builder.build());
  • 20. Going forward - 2 Reference Link https://developer.android.com/topic/performance/scheduling.html https://developer.android.com/reference/android/app/job/JobScheduler.html https://github.com/googlesamples/android-JobScheduler/