SlideShare a Scribd company logo
Android
AsyncTask
Perfect APK
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.
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.
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.
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"
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.
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. }
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. }
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

More Related Content

PPTX
Android async task
PPT
Android - Thread, Handler and AsyncTask
PDF
Android development training programme , Day 3
PPTX
BroadcastReceivers in Android
PDF
Android Threading
ODP
Android App Development - 07 Threading
PDF
Learn Drupal 8 Render Pipeline
PPTX
Android Database Tutorial
Android async task
Android - Thread, Handler and AsyncTask
Android development training programme , Day 3
BroadcastReceivers in Android
Android Threading
Android App Development - 07 Threading
Learn Drupal 8 Render Pipeline
Android Database Tutorial

What's hot (20)

PDF
Java.NET: Integration of Java and .NET
PPTX
React hooks
PPTX
IT talk: Как я перестал бояться и полюбил TestNG
PDF
Identifing Listeners and Filters
PPTX
Servlets - filter, listeners, wrapper, internationalization
PDF
Lab 5-Android
DOC
New Microsoft Word Document.doc
PPTX
Types of MessageRouting in Mule
PDF
Java servlet technology
PPTX
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
PPTX
Exceptions
PDF
Concurrency and parallel in .net
PPT
Programming Server side with Sevlet
PDF
Servlet Filter
PDF
Usage Note of Microsoft Dependency Walker
PDF
Java 8 new features
PPTX
PPTX
Servlet session 9
PPTX
Databases in Android Application
PPTX
Java.NET: Integration of Java and .NET
React hooks
IT talk: Как я перестал бояться и полюбил TestNG
Identifing Listeners and Filters
Servlets - filter, listeners, wrapper, internationalization
Lab 5-Android
New Microsoft Word Document.doc
Types of MessageRouting in Mule
Java servlet technology
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
Exceptions
Concurrency and parallel in .net
Programming Server side with Sevlet
Servlet Filter
Usage Note of Microsoft Dependency Walker
Java 8 new features
Servlet session 9
Databases in Android Application
Ad

Viewers also liked (20)

PPT
Sandbox Introduction
PPTX
Security threats in Android OS + App Permissions
ODP
Android training day 4
PPTX
Tips dan Third Party Library untuk Android - Part 1
PDF
Web Services and Android - OSSPAC 2009
PDF
Anatomizing online payment systems: hack to shop
ODP
Android permission system
ODP
Android permission system
ODP
Android(1)
PPTX
Android secuirty permission - upload
ODP
Json Tutorial
PDF
Android 6.0 permission change
PDF
Basic Android Push Notification
PDF
Android new permission model
PPTX
JSON overview and demo
PDF
Simple JSON parser
PDF
App Permissions
PDF
Android webservices
ODP
Android porting for dummies @droidconin 2011
PPTX
Android json parser tutorial – example
Sandbox Introduction
Security threats in Android OS + App Permissions
Android training day 4
Tips dan Third Party Library untuk Android - Part 1
Web Services and Android - OSSPAC 2009
Anatomizing online payment systems: hack to shop
Android permission system
Android permission system
Android(1)
Android secuirty permission - upload
Json Tutorial
Android 6.0 permission change
Basic Android Push Notification
Android new permission model
JSON overview and demo
Simple JSON parser
App Permissions
Android webservices
Android porting for dummies @droidconin 2011
Android json parser tutorial – example
Ad

Similar to Android AsyncTask Tutorial (20)

PPTX
layout and UI.pptx
ODP
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
PDF
PPT
Tech talk
PDF
Don't Make Android Bad... Again
PPTX
Adapter and adapter views that are used in android
PPTX
Android Chapter 4 part2 Types of View and View group
PDF
Android best practices
PPT
Android classes in mumbai
PDF
Android Best Practices
PDF
Grid View- GridView is a ViewGroup that displays items in a two d.pdf
PPTX
Android Training Session 1
PDF
Android TV: Building apps with Google’s Leanback Library
PPTX
Binding data with the AdapterView class.pptx
PPTX
05 content providers - Android
PDF
Java Svet - Communication Between Android App Components
PDF
Java Svet - Communication Between Android App Components
PDF
[Android] Multiple Background Threads
PPTX
Android Training (AdapterView & Adapter)
PPT
Hello Android
layout and UI.pptx
Android App Development - 11 Lists, grids, adapters, dialogs and toasts
Tech talk
Don't Make Android Bad... Again
Adapter and adapter views that are used in android
Android Chapter 4 part2 Types of View and View group
Android best practices
Android classes in mumbai
Android Best Practices
Grid View- GridView is a ViewGroup that displays items in a two d.pdf
Android Training Session 1
Android TV: Building apps with Google’s Leanback Library
Binding data with the AdapterView class.pptx
05 content providers - Android
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
[Android] Multiple Background Threads
Android Training (AdapterView & Adapter)
Hello Android

Recently uploaded (20)

PPTX
history of c programming in notes for students .pptx
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
ai tools demonstartion for schools and inter college
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Nekopoi APK 2025 free lastest update
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Digital Strategies for Manufacturing Companies
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
System and Network Administraation Chapter 3
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
history of c programming in notes for students .pptx
Which alternative to Crystal Reports is best for small or large businesses.pdf
Understanding Forklifts - TECH EHS Solution
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 41
ai tools demonstartion for schools and inter college
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Softaken Excel to vCard Converter Software.pdf
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Nekopoi APK 2025 free lastest update
Navsoft: AI-Powered Business Solutions & Custom Software Development
How to Migrate SBCGlobal Email to Yahoo Easily
Digital Strategies for Manufacturing Companies
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How to Choose the Right IT Partner for Your Business in Malaysia
System and Network Administraation Chapter 3
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025

Android AsyncTask Tutorial

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