15 AsyncTask

public abstract class AsyncTask 


extends Object 

AsyncTask enables proper and easy use of the UI thread. 
This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. 
An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 
4 steps, called onPreExecutedoInBackground,onProgressUpdate and onPostExecute.
USAGE:

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

AsyncTask's generic types

The three types used by an asynchronous task are the following:
  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:
 private class MyTask extends AsyncTask<Void, Void, Void> { ... }

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:
  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...)to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.



Algorithm:

Step 1) Create a new Android Studio Project named as AsyncTask.
Step 2)Go to project open activity_main.xml file and change Constraint Layout to Relative Layout add Text View, Edit Text and Button .
Step3)Create an Inner class  named as  AsyncTaskRunner  which extends AsyncTask and implement the following methods.



private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    private String resp;
    ProgressDialog progressDialog;

    @Override    protected String doInBackground(String... params) {
        publishProgress("Sleeping...");// Calls onProgressUpdate()       try{
       }
      catch(...){
       }
     return resp;
    }


    @Override    protected void onPostExecute(String result) {
    }
 
    @Override    protected void onPreExecute() {
    }

    @Override    protected void onProgressUpdate(String... text) {
    }
}


Program:

 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 xmlns:app="http://schemas.android.com/apk/res-auto" 
 xmlns:tools="http://schemas.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 tools:context=".MainActivity">

    <TextView         
        android:id="@+id/tv_time"         
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="20sp" 
        android:textColor="#444444" 
        android:layout_alignParentLeft="true" 
        android:layout_marginRight="9dip" 
        android:layout_marginTop="20dip" 
        android:layout_marginLeft="10dip" 
        android:text="Sleep time in Seconds:"/>
    <EditText         
        android:id="@+id/in_time" 
        android:layout_width="150dip" 
        android:layout_height="wrap_content" 
        android:background="@android:drawable/editbox_background"        android:layout_toRightOf="@id/tv_time"        android:layout_alignTop="@id/tv_time"        android:inputType="number"        />
    <Button         
       android:id="@+id/btn_run" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Run Async task" 
       android:layout_below="@+id/in_time" 
       android:layout_centerHorizontal="true" 
       android:layout_marginTop="64dp" />
    <TextView 
       android:id="@+id/tv_result" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:textSize="20sp" 
       android:layout_below="@+id/btn_run" 
       android:layout_centerHorizontal="true" />
</RelativeLayout>


MainActivity.java

package com.example.asynctask;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText time;
    private TextView finalResult;

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        time = (EditText) findViewById(R.id.in_time);
        button = (Button) findViewById(R.id.btn_run);
        finalResult = (TextView) findViewById(R.id.tv_result);
        button.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = time.getText().toString();
                runner.execute(sleepTime);
            }
        });
    }

    private class AsyncTaskRunner extends AsyncTask<String, String, String> {

        private String resp;
        ProgressDialog progressDialog;

        @Override 
        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // Calls onProgressUpdate() 
     try {
                int time = Integer.parseInt(params[0])*1000;

                Thread.sleep(time);
                resp = "Slept for " + params[0] + " seconds";
            } catch (InterruptedException e) {
                e.printStackTrace();
                resp = e.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                resp = e.getMessage();
            }
            return resp;
        }


        @Override         
        protected void onPostExecute(String result) {
            // execution of result of Long time consuming operation            progressDialog.dismiss();
            finalResult.setText(result);
        }


        @Override 
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(MainActivity.this,
                    "ProgressDialog",
                    "Wait for "+time.getText().toString()+ " seconds");
        }
        @Override         
        protected void onProgressUpdate(String... text) {
            finalResult.setText(text[0]);

        }
    }
}























Comments

  1. Pragmatic Play Slots - iTanium Arts
    Pragmatic Play is titanium tube a camillus titanium leading content provider to the gaming industry, ford focus titanium hatchback offering innovative, regulated and mobile-focused gaming products.‎Table Games · titanium armor ‎Mobile titanium damascus · ‎Gaming

    ReplyDelete

Post a Comment

Popular posts from this blog

20 Simple Content Provider Example

14 Popup Menu

17 Simple Notification Program