MobAppDev: Asynchronous Tasks & Started Services

974
-1

Published on

Asynchronous Tasks & Started Services

Published in: Software, Design
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
974
On Slideshare
0
From Embeds
0
Number of Embeds
49
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

MobAppDev: Asynchronous Tasks & Started Services

  1. 1. Android MobAppDev Asynchronous Tasks & Started Services Vladimir Kulyukin www.vkedco.blogspot.com
  2. 2. Outline ● ● Asynchronous Tasks Started Services & Threads
  3. 3. Asynchronous Tasks
  4. 4. When to Use AsyncTask ● ● ● Asynchronous tasks (AsyncTask) allow developers to get long-running computations off the main UI thread AsyncTasks are best suited for long one-time computations (downloads, initializaitons, etc) If repeated computations are required, threads, background services and other tools in java.util.concurrent should be considered
  5. 5. AsyncTask<Param, Progress, Result> ● ● ● ● ● AsyncTask is defined by three generic parameters: Param, Progress, and Result Param, Progress, and Result must be legal Java data types Param is the input type Progress is the progress type Result is the output type
  6. 6. AsyncTask Execution An AsyncTask is executed in four stages, each of which is done in the corresponding overriden method given below ● These methods should not be invoked automatically ●  1) onPreExecute()  2) doInBackground(Param... input_params)  3) onProgressUpdate(Progress... progress_params)  4) onPostExecute(Result rslt)
  7. 7. AsyncTask.onPreExecute() onPreExecute() is executed on the main UI thread ● This method is used to do the setup and can complement the constructor ● If you application, for example, needs a progress bar, this method is the place to do it ●
  8. 8. AsyncTask.doInBackground() This method is invoked off the main UI thread ● This method is used to perform all background computation ● This method returns the Result type ●
  9. 9. AsyncTask.onProgressUpdate() The onProgressUpdate() method is invoked on the main UI thread ● The timing of execution is undefined in the documentation ● This method is executed while the background computation is still in progress ●
  10. 10. AsyncTask.onPostExecute() The onPostExecute() method is invoked on the main UI thread ● The method is executed after the background computation is done ● The result of the background computation is passed to this method ●
  11. 11. Implementation of AsyncTasks An implementation class must extend AsyncTask ● An implementation must, at the very least, implement doInBackground() ● Many implementations also implement onPostExecute() ●
  12. 12. AsyncTask Cancelation An AsyncTask can be canceled at any time by invoking cancel() ● You can check if an AsyncTask has been canceled via isCanceled() ● It is a good best practice to check if the task is canceled in doInBackground() ●
  13. 13. Threading & AsyncTasks An AsyncTask is created on the UI thread ● An AsyncTask must do execute(Param...) on the main UI thread ● An AsyncTask guarantees that all callback calls are synchronized ●
  14. 14. Cloud-Based Barcode Scanning Service
  15. 15. Problem Implement an application that uses a started service to download randomly chosen barcode images from the cloud, upload them to a closedbased barcode reading service, and using notifications to display barcode strings on the status bar. When the user clicks on the notification in the notification tray, the nutrition label of the corresponding product is displayed. Details are here
  16. 16. Sample Screenshots
  17. 17. Sample Images
  18. 18. Solution Outline The started service implements two st asynchronous tasks: 1 task downloads nd images from the cloud, 2 task uploads images to the cloud ● The started service implements a worker thread that uses both asynchronous tasks to manipulate images ●
  19. 19. DownloadImageTask private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { File mFile = null; public DownloadImageTask(File fn) { mFile = fn; } protected Bitmap doInBackground(String... urls) { Bitmap map = null; for (String url : urls) { map = downloadImage(url); } if (!mFile.exists()) { this.saveBitmapToFile(map, mFile); } return map; } … } Details are here
  20. 20. DownloadImageTask private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { File mFile = null; public DownloadImageTask(File fn) { mFile = fn; } protected void onPostExecute(Bitmap result) { if (mDownloadedBitmap != null) { mDownloadedBitmap.recycle(); mDownloadedBitmap = null; } mDownloadedBitmap = result; } Details are here
  21. 21. UploadImageTask private class UploadImageTask extends AsyncTask<File, Void, String> { protected String doInBackground(File... urls) { String nl = ""; for (File url : urls) { nl = uploadFile(url); } return nl; } ... } Details are here
  22. 22. UploadImageTask private class UploadImageTask extends AsyncTask<File, Void, String> { protected void onPostExecute(String result) { String barcode = getBarcode(result); File nlTxtFile = new File(Environment.getExternalStorageDirectory() + "/" + barcode + ".txt"); if (!nlTxtFile.exists()) { PrintWriter pw; try { pw = new PrintWriter(nlTxtFile); pw.write(result); pw.flush(); pw.close(); pw = null; } catch (FileNotFoundException e) { e.printStackTrace(); } } ImageUploadService.this.postBarcodeNotification(barcode); } } Details are here
  23. 23. Service Worker Thread int file_num = mRandomNumberGenerator.nextInt(9); File imageFile = new File( Environment.getExternalStorageDirectory() + "/" + Integer.toString(file_num) + ".jpg"); // Create and execute a DownloadImageTask DownloadImageTask downTask = new DownloadImageTask(imageFile); downTask.execute(new String[] { BARCODE_IMAGE_URLS[file_num] }); // Create and execute an UploadImageTask UploadImageTask upTask = new UploadImageTask(); upTask.execute(new File[] { imageFile }); Details are here

×