delhendro

Untitled

May 6th, 2016
4,120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. package com.delhendro.aplikasipertama;
  2.  
  3. import android.os.AsyncTask;
  4. import android.util.Log;
  5. import android.widget.ProgressBar;
  6.  
  7. public class Task extends AsyncTask<String, Integer, Integer> {
  8.  
  9. public interface TaskFinishedListener {
  10. void onTaskFinished(); // If you want to pass something back to the listener add a param to this method
  11. }
  12.  
  13. // This is the progress bar you want to update while the task is in progress
  14. private final ProgressBar progressBar;
  15. // This is the listener that will be told when this task is finished
  16. private final TaskFinishedListener finishedListener;
  17.  
  18. /**
  19. * A Loading task that will load some resources that are necessary for the app to start
  20. * @param progressBar - the progress bar you want to update while the task is in progress
  21. * @param finishedListener - the listener that will be told when this task is finished
  22. */
  23. public Task(ProgressBar progressBar, TaskFinishedListener finishedListener) {
  24. this.progressBar = progressBar;
  25. this.finishedListener = finishedListener;
  26. }
  27.  
  28. @Override
  29. protected Integer doInBackground(String... params) {
  30. Log.i("Tutorial", "Starting task with url: "+params[0]);
  31. if(resourcesDontAlreadyExist()){
  32. downloadResources();
  33. }
  34. // Perhaps you want to return something to your post execute
  35. return 1234;
  36. }
  37.  
  38. private boolean resourcesDontAlreadyExist() {
  39. // Here you would query your app's internal state to see if this download had been performed before
  40. // Perhaps once checked save this in a shared preference for speed of access next time
  41. return true; // returning true so we show the splashbe every time
  42. }
  43.  
  44.  
  45. private void downloadResources() {
  46. // We are just imitating some process thats takes a bit of time (loading of resources / downloading)
  47. int count = 10;
  48. for (int i = 0; i < count; i++) {
  49.  
  50. // Update the progress bar after every step
  51. int progress = (int) ((i / (float) count) * 100);
  52. publishProgress(progress);
  53.  
  54. // Do some long loading things
  55. try { Thread.sleep(1000); } catch (InterruptedException ignore) {}
  56. }
  57. }
  58.  
  59. @Override
  60. protected void onProgressUpdate(Integer... values) {
  61. super.onProgressUpdate(values);
  62. progressBar.setProgress(values[0]); // This is ran on the UI thread so it is ok to update our progress bar ( a UI view ) here
  63. }
  64.  
  65. @Override
  66. protected void onPostExecute(Integer result) {
  67. super.onPostExecute(result);
  68. finishedListener.onTaskFinished(); // Tell whoever was listening we have finished
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment