What is AsyncTask?
AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.
When to use AsyncTask?
Assume you have created a simple Android application which downloads Images file from Internet on launching the application.
How to implement AsyncTask in Android applications?
- Create a new class inside Activity class and subclass it by extending AsyncTask as shown below
1234567891011
private
classMy
Task
extends
AsyncTask<URL, Integer, Long> {
protected
Long doInBackground(URL... urls) {
//Yet to code
}
protected
void
onProgressUpdate(Integer... progress) {
//Yet to code
}
protected
void
onPostExecute(Long result) {
//Yet to code
}
}
- Execute the task simply by invoking execute method as shown below:
Create New Projects Name AsyncTaskAsyncTask\app\src\main\res\layout1.activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/download_img"
android:layout_gravity="center_vertical" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/download_next"
android:layout_gravity="right" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/download_nextimg"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/download_nexttimeimg"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Download"
android:id="@+id/button"
android:onClick="downloadImage" />
</LinearLayout>2.AsyncTask\app\src\main\java\com\problemhunt\tanuj\asynctask:MainActivity.javapackage com.problemhunt.tanuj.asynctask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView mDownloadImgV;
private ImageView mDownloadNext;
private ImageView mDownloadImgNext;
private ImageView mDownloadNextTimeImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDownloadImgV=(ImageView) findViewById(R.id.download_img);
mDownloadNext=(ImageView) findViewById(R.id.download_next);
mDownloadImgNext=(ImageView) findViewById(R.id.download_nextimg);
mDownloadNextTimeImg=(ImageView) findViewById(R.id.download_nexttimeimg);
}
public void downloadImage(View view) {
MyTask myTask=new MyTask(mDownloadImgV,mDownloadNext,mDownloadImgNext,mDownloadNextTimeImg,MainActivity.this);
myTask.execute("http://images.indianexpress.com/2015/07/kalam_pranab_759.jpg","http://images.indianexpress.com/2015/07/kalam_dd_759.jpg","http://cdn.narendramodi.in/cmsuploads/0.34592100-1450848819-indian-pm-narendra-modi-russia-remains-our-principal-partner.jpg","http://astrotarot.net/wp-content/uploads/2015/09/army.jpg");
}
}
Create Class MyTask.java
package com.smartpropertyhunt.tanuj.asynctask;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
/**
* Created by Tanuj on 06/09/2016.
*/
public class MyTask extends AsyncTask<String,String,ArrayList<Bitmap>> {
ImageView mImageView;
ImageView vImageView;
ImageView nImageView;
ImageView iImageView;
private Context mContext;
private ProgressDialog mprogressDialog;
ArrayList<Bitmap> marry= new ArrayList<Bitmap>();
public MyTask(ImageView mImageView,ImageView vImageView, ImageView nImageView,ImageView iImageView,Context mContext) {
this.mImageView = mImageView;
this.vImageView=vImageView;
this.nImageView=nImageView;
this.iImageView=iImageView;
this.mContext = mContext;
mprogressDialog = new ProgressDialog(mContext);
}
@Override
protected ArrayList<Bitmap> doInBackground(String... params) {
Bitmap bm = null;
for (int i=0;i<=3;i++)
{
try {
URL aURL = new URL(params[i]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
marry.add(bm);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub", "Error getting the image from server : " + e.getMessage().toString());
}
}
return marry;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mprogressDialog.setMessage("Loading Image...");
mprogressDialog.show();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(ArrayList<Bitmap> bitmaps){
super.onPostExecute(bitmaps);
mImageView.setImageBitmap(marry.get(0));
vImageView.setImageBitmap(marry.get(1));
nImageView.setImageBitmap(marry.get(2));
iImageView.setImageBitmap(marry.get(3));
mprogressDialog.dismiss();
}
}
No comments:
Post a Comment