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

What's hot (20)

PDF
Java.NET: Integration of Java and .NET
Dr Sukhpal Singh Gill
 
PPTX
React hooks
Sadhna Rana
 
PPTX
IT talk: Как я перестал бояться и полюбил TestNG
DataArt
 
PDF
Identifing Listeners and Filters
People Strategists
 
PPTX
Servlets - filter, listeners, wrapper, internationalization
susant sahu
 
PDF
Lab 5-Android
Lilia Sfaxi
 
DOC
New Microsoft Word Document.doc
butest
 
PPTX
Types of MessageRouting in Mule
VenkataNaveen Kumar
 
PDF
Java servlet technology
Minal Maniar
 
PPTX
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
DroidConTLV
 
PPTX
Exceptions
myrajendra
 
PDF
Concurrency and parallel in .net
Mohammad Hossein Karami
 
PPT
Programming Server side with Sevlet
backdoor
 
PDF
Servlet Filter
AshishSingh Bhatia
 
PDF
Usage Note of Microsoft Dependency Walker
William Lee
 
PDF
Java 8 new features
Tân Nguyễn Văn
 
PPTX
yii1
Rajat Gupta
 
PPTX
Servlet session 9
Anuj Singh Rajput
 
PPTX
Databases in Android Application
Mark Lester Navarro
 
PPTX
Struts
Rajkumar Singh
 
Java.NET: Integration of Java and .NET
Dr Sukhpal Singh Gill
 
React hooks
Sadhna Rana
 
IT talk: Как я перестал бояться и полюбил TestNG
DataArt
 
Identifing Listeners and Filters
People Strategists
 
Servlets - filter, listeners, wrapper, internationalization
susant sahu
 
Lab 5-Android
Lilia Sfaxi
 
New Microsoft Word Document.doc
butest
 
Types of MessageRouting in Mule
VenkataNaveen Kumar
 
Java servlet technology
Minal Maniar
 
Will it run or will it not run? Background processes in Android 6 - Anna Lifs...
DroidConTLV
 
Exceptions
myrajendra
 
Concurrency and parallel in .net
Mohammad Hossein Karami
 
Programming Server side with Sevlet
backdoor
 
Servlet Filter
AshishSingh Bhatia
 
Usage Note of Microsoft Dependency Walker
William Lee
 
Java 8 new features
Tân Nguyễn Văn
 
Servlet session 9
Anuj Singh Rajput
 
Databases in Android Application
Mark Lester Navarro
 

Viewers also liked (20)

PPT
Sandbox Introduction
msimkin
 
PPTX
Security threats in Android OS + App Permissions
Hariharan Ganesan
 
ODP
Android training day 4
Vivek Bhusal
 
PPTX
Tips dan Third Party Library untuk Android - Part 1
Ibnu Sina Wardy
 
PDF
Web Services and Android - OSSPAC 2009
sullis
 
PDF
Anatomizing online payment systems: hack to shop
Abhinav Mishra
 
ODP
Android permission system
Shivang Goel
 
ODP
Android permission system
Shivang Goel
 
ODP
Android(1)
Nikola Milosevic
 
PPTX
Android secuirty permission - upload
Bin Yang
 
ODP
Json Tutorial
Napendra Singh
 
PDF
Android 6.0 permission change
彥彬 洪
 
PDF
Basic Android Push Notification
Chaiyasit Tayabovorn
 
PDF
Android new permission model
Takuji Nishibayashi
 
PPTX
JSON overview and demo
Flatiron School
 
PDF
Simple JSON parser
Dongjun Lee
 
PDF
App Permissions
Shinobu Okano
 
PDF
Android webservices
Krazy Koder
 
ODP
Android porting for dummies @droidconin 2011
pundiramit
 
PPTX
Android json parser tutorial – example
Rajat Ghai
 
Sandbox Introduction
msimkin
 
Security threats in Android OS + App Permissions
Hariharan Ganesan
 
Android training day 4
Vivek Bhusal
 
Tips dan Third Party Library untuk Android - Part 1
Ibnu Sina Wardy
 
Web Services and Android - OSSPAC 2009
sullis
 
Anatomizing online payment systems: hack to shop
Abhinav Mishra
 
Android permission system
Shivang Goel
 
Android permission system
Shivang Goel
 
Android(1)
Nikola Milosevic
 
Android secuirty permission - upload
Bin Yang
 
Json Tutorial
Napendra Singh
 
Android 6.0 permission change
彥彬 洪
 
Basic Android Push Notification
Chaiyasit Tayabovorn
 
Android new permission model
Takuji Nishibayashi
 
JSON overview and demo
Flatiron School
 
Simple JSON parser
Dongjun Lee
 
App Permissions
Shinobu Okano
 
Android webservices
Krazy Koder
 
Android porting for dummies @droidconin 2011
pundiramit
 
Android json parser tutorial – example
Rajat Ghai
 
Ad

Similar to Android AsyncTask Tutorial (20)

PDF
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
PDF
Angular performance slides
David Barreto
 
PPTX
Android session-5-sajib
Hussain Behestee
 
PPTX
Angularjs2 presentation
dharisk
 
PPTX
Android async task
Madhu Venkat
 
PPTX
Threads handlers and async task, widgets - day8
Utkarsh Mankad
 
PDF
Android tutorial
master760
 
PDF
Answer1)Responsive design is the idea where all the developed pag.pdf
ankitcomputer11
 
DOCX
Android Studio (Java)Modify the Networking app (code given below.docx
amrit47
 
DOCX
Android Studio (Java)Modify the Networking app (code given bel.docx
amrit47
 
PPTX
Android Tutorials - Powering with Selection Widget
Prajyot Mainkar
 
PPT
Android lifecycle
Kumar
 
PDF
Android tutorial
Vaiga Nandhakumar
 
PDF
Android tutorial ppt
Rehna Renu
 
PDF
Android tutorial
Jagannath Das
 
PDF
Android tutorial
Danish_k
 
PDF
Android programming -_pushing_the_limits
Droidcon Berlin
 
PDF
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
PPT
Android classes in mumbai
Vibrant Technologies & Computers
 
PPTX
Angularj2.0
Mallikarjuna G D
 
Session 9 Android Web Services - Part 2.pdf
EngmohammedAlzared
 
Angular performance slides
David Barreto
 
Android session-5-sajib
Hussain Behestee
 
Angularjs2 presentation
dharisk
 
Android async task
Madhu Venkat
 
Threads handlers and async task, widgets - day8
Utkarsh Mankad
 
Android tutorial
master760
 
Answer1)Responsive design is the idea where all the developed pag.pdf
ankitcomputer11
 
Android Studio (Java)Modify the Networking app (code given below.docx
amrit47
 
Android Studio (Java)Modify the Networking app (code given bel.docx
amrit47
 
Android Tutorials - Powering with Selection Widget
Prajyot Mainkar
 
Android lifecycle
Kumar
 
Android tutorial
Vaiga Nandhakumar
 
Android tutorial ppt
Rehna Renu
 
Android tutorial
Jagannath Das
 
Android tutorial
Danish_k
 
Android programming -_pushing_the_limits
Droidcon Berlin
 
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Android classes in mumbai
Vibrant Technologies & Computers
 
Angularj2.0
Mallikarjuna G D
 
Ad

Recently uploaded (20)

PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
PDF
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
IObit Driver Booster Pro 12.4.0.585 Crack Free Download
henryc1122g
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Add Background Images to Charts in IBM SPSS Statistics Version 31.pdf
Version 1 Analytics
 
NEW-Viral>Wondershare Filmora 14.5.18.12900 Crack Free
sherryg1122g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 

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