Android - Background operation

21
Background operation How to handle all your jobs +RobertoOrgiu @_tiwiz +MatteoBonifazi @mbonifazi

Transcript of Android - Background operation

Page 1: Android - Background operation

Background operationHow to handle all your jobs

+RobertoOrgiu@_tiwiz

+MatteoBonifazi@mbonifazi

Page 2: Android - Background operation

Threading & Background TasksMultithreading 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?

Page 3: Android - Background operation

Android threadsAndroid 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.

Page 4: Android - Background operation

AsyncTask

Page 5: Android - Background operation

AsyncTask represents a convenient way to offload work from the main thread.

Page 6: Android - Background operation

AsyncTaskIs 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.

Page 7: Android - Background operation

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

Page 8: Android - Background operation

Parallel execution - AsyncTask

// ImageLoader extends AsyncTaskDownloadWebPageTask imageLoader = new DownloadWebPageTask( imageView );

// Execute in parallelimageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, "http://url.com/image.png" );

Page 9: Android - Background operation

Intent Service

Page 10: Android - Background operation

IntentService provides straightforward structure for running an operation on a single

background thread.

Page 11: Android - Background operation

IntentServicePreferred 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

Page 12: Android - Background operation

IntentServiceLimitations

● 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.

Page 13: Android - Background operation

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

Page 14: Android - Background operation

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

Page 15: Android - Background operation

Create a work request to the IntentService

mServiceIntent = new Intent(getActivity(), RSSPullService.class);mServiceIntent.setData(Uri.parse(dataUrl));...// Starts the IntentServicegetActivity().startService(mServiceIntent);

Page 17: Android - Background operation

JobScheduler

Page 18: Android - Background operation

Creating a job

public class AwesomeJobService extends JobService {

@Override public boolean onStartJob(final JobParameters params) {

//AWESOME STUFF HEREreturn true; // or false

}

@Override public boolean onStopJob(JobParameters params) {

//AWESOME CLEANING HEREreturn false; //or true

}}

Page 19: Android - Background operation

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());

Page 20: Android - Background operation

Going forward - 2

Reference Linkhttps://developer.android.com/topic/performance/scheduling.htmlhttps://developer.android.com/reference/android/app/job/JobScheduler.htmlhttps://github.com/googlesamples/android-JobScheduler/

Page 21: Android - Background operation

+MatteoBonifazi@mbonifazi

Thank You!

+RobertoOrgiu@_tiwiz