Android AsyncTask Tutorial

1,329 views

Published on

Almost every Android app has some tasks that need to be executed in the background, such as network operations and CPU intensive operations. Many times these tasks are required by the UI thread, however executing them in the UI the will compromise the responsiveness of the app.

The AsyncTask class is is a convenience generic abstract class for executing relatively short tasks in a background thread and updating the UI thread. AsyncTask has 3 type parameters:

Params - the class of the params array that is passed to the execute() method which is called in the UI thread and received in the doInBackground() method which is called in the background thread.
Progress - the class of the values array that is passed by the publishProgress() method which is called in the background thread and returned by the onProgressUpdate() method which is called in the UI thread.
Result - the class of the result that is passed returned by the execute() method and returned by the onPostExecute() method which is called in the UI thread.
The doInBackground() method is an abstract method that defines the actual background task.

Published in: Software, Technology
  • Be the first to comment

Android AsyncTask Tutorial

  1. 1. Android AsyncTask Perfect APK
  2. 2. Android AsyncTask Tutorial Almost every Android app has some tasks that need to be executed in the background, such as network operations and CPU intensive operations. Many times these tasks are required by the UI thread, however executing them in the UI the will compromise the responsiveness of the app. The AsyncTask class is is a convenience generic abstract class for executing relatively short tasks in a background thread and updating the UI thread. AsyncTask has 3 type parameters: ● Params - the class of the params array that is passed to the execute() method which is called in the UI thread and received in the doInBackground() method which is called in the background thread. ● Progress - the class of the values array that is passed by the publishProgress() method which is called in the background thread and returned by the onProgressUpdate() method which is called in the UI thread. ● Result - the class of the result that is passed returned by the execute() method and returned by the onPostExecute() method which is called in the UI thread. The doInBackground() method is an abstract method that defines the actual background task.
  3. 3. Updating an adapter from a background thread In this tutorial we will use an AsynTask for loading data for a GridView. The example in this tutorial is based on the GridView Tutorial, only this time the view will be created using an empty data-set, and the data set will be updated using an AsyncTask. The data that is loaded for this GridView is the icons and labels of the applications that are installed on the device. This data is loaded using the PackageManager. The list of installed applications is obtained by calling the getInstalledApplications() method, and the icon and label of each application is obtained by calling the getApplicationIcon()and getApplicationLabel() methods. The example in this tutorial includes the following components: ● AsyncAppInfoLoader - the base class used for loading the application info. ● GridViewAdapter - the adapter used in the GridView Tutorial. ● Item Layout File - a GridView item XML layout file to be used by the adapter. It is similar to the file used in the GridView Tutorial with some minor changes. ● Fragment View Layout File - the file used in the GridView Tutorial. ● AsyncTaskDemoFragment - the fragment that contains the GridView.
  4. 4. AsyncAppInfoLoader The base class used for loading the application info. This class extends the AsycTask class, with the following type parameters: ● Params - the PackageManager class. Used for loading the application info. ● Progress - the GridViewItem class used in the GridView tutorial. ● Result - Integer representing for the number of loaded items. Below is code for AsyncAppInfoLoader class: 1. public class AsyncAppInfoLoader extends AsyncTask<PackageManager, GridViewItem, Integer> { 2. 3. @Override 4. protected Integer doInBackground(PackageManager... params) { 5. // this method executes the task in a background thread 6. PackageManager packageManager = params[0]; // the PackageManager for loading the data 7. List<ApplicationInfo> appInfoList = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); 8. int index = 0; 9.
  5. 5. Item Layout File The item view is described in the res/layout/gridview_item.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <!-- the parent view --> 3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 4. android:layout_width="match_parent" 5. android:layout_height="match_parent" 6. android:layout_gravity="center" 7. android:gravity="center" 8. android:padding="5dp" > 9. 10. <!-- the ImageView for the icon --> 11. <ImageView android:id="@+id/ivIcon" 12. android:layout_width="50dp"
  6. 6. AsyncTaskDemoFragment The fragment that contains the GridView. This class also includes the GridViewAppInfoLoader class below which extends the AsyncAppInfoLoader class and overrides the onProgressUpdate() and onPostExecute()methods for updating the adapter in the UI thread: 1. public class AsyncTaskDemoFragment extends Fragment implements OnItemClickListener { 2. private List<GridViewItem> mItems; // GridView items list 3. private GridViewAdapter mAdapter; // GridView adapter 4. private Activity mActivity; // the parent activity 5. private GridViewAppInfoLoader mLoader; // the application info loader 6. 7. @Override 8. public void onAttach(Activity activity) { 9. super.onAttach(activity); 10. mActivity = activity; 11.
  7. 7. AsyncTaskDemoFragment 1. @Override 2. public View onCreateView(LayoutInflater inflater, ViewGroup container, 3. Bundle savedInstanceState) { 4. // inflate the root view of the fragment 5. View fragmentView = inflater.inflate(R.layout.fragment_gridview, container, false); 6. 7. // initialize the adapter 8. mAdapter = new GridViewAdapter(getActivity(), mItems); 9. 10. // initialize the GridView 11. GridView gridView = (GridView) fragmentView.findViewById(R.id.gridView); 12. gridView.setAdapter(mAdapter); 13. gridView.setOnItemClickListener(this); 14. 15. // start loading 16. mLoader = new GridViewAppInfoLoader(); 17. mLoader.execute(mActivity.getPackageManager()); 18. 19. return fragmentView; 20. }
  8. 8. AsyncTaskDemoFragment 1. @Override 2. public void onItemClick(AdapterView<?> parent, View view, int position, 3. long id) { 4. // retrieve the GridView item 5. GridViewItem item = mItems.get(position); 6. 7. // do something 8. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show(); 9. } 10. 11. private class GridViewAppInfoLoader extends AsyncAppInfoLoader { 12. @Override 13. protected void onProgressUpdate(GridViewItem... values) { 14. 15. // check that the fragment is still attached to activity 16. if(mActivity != null) { 17. // add the new item to the data set 18. mItems.add(values[0]); 19. 20. // notify the adapter 21. mAdapter.notifyDataSetChanged(); 22. } 23. }
  9. 9. AsyncTaskDemoFragment 1. As@Override 2. protected void onPostExecute(Integer result) { 3. // check that the fragment is still attached to activity 4. if(mActivity != null) { 5. Toast.makeText(mActivity, getString(R.string.post_execute_message, result), Toast.LENGTH_SHORT).show(); 6. } 7. } 8. } 9. } yncTaskDemoFragment

×