Course Content

If you are facing any issue in playing video please use Firefox browser.

Course Content

Description

Async task in Android with Example

Here in this video we will see Asynctask in Android with Example and its functionalities. 

Android Asynctask Example Stepwise :

Step-1 For that in a layout folder we have designed a 'main.xml' In which we have taken a linearlayout and a text view, in textview we will display a timer from 0 to 10 seconds.

Step-2 After that we have taken second linearlayout, in which we will put two buttons, 'start' and 'stop', by using them we can control timer.

Step-3 Now we have created AsyncTimer class, in which we have used Asynctask. Using thread and Asynctask we will sleep our thread for 1000 milliseconds in a loop for each and every time, till our timer don't work from 0-10 seconds.

Step-4 And in between we will use different methods to define thread functionality,

               public AsyncTimer(Context c) { context=c; }

public void setOnProgressUpdateListener(OnProgressUpdateListener l) {listener=l;}

@Override

protected Boolean doInBackground (Void... arg0)

{

stop=false;

isRunning=true;

seconds=0;

this.publishProgress(seconds);

while(seconds<10&&stop!=true)

{

try {

Thread.sleep(1000);

}

catch (InterruptionException e)

{

Log.e(""AsyncTutorial"", e.getMessage());

}

seconds++;

this.publishProgress(seconds);

}

 

if(stop==false)

return true;

else

return false;

}

Step-5 Here we have taken methods like 'onCancelled()' and 'onPostExecute'. In which we will use different toast notification like ""User stopped thread"" and ""Running of 10 second timer complete"".

Step-6 Now in our 'Main.java' file we have used a switch case, to provide the functionality of 'start' and 'stop' button,

switch(arg0.getId()}

{

case R.id.button1:

{

stopThread();

break;

}

case R.id.button2:

{

startThread();

break;

}

}

Step-7 For 'start' button, we have generated a toast notification saying ""Timer is already running"" and we have also displayed timer. While for 'stop' button, we have generated a toast notification saying ""Timer is not working"".

Step-8 Now we will execute the code. After executing the code it is successfully working and this is how we can use Async task.

FAQs

Recommended Courses

Share With Friend

Have a friend to whom you would want to share this course?

Download The Apps

Code Scan or Download the app
Google Play Store
297K+ Downloads
4.5 Rating
10K+ Reviews
  • Learn anywhere on the go
  • Get regular updates about your enrolled or new courses
  • Share content with your friends
  • Evaluate your progress through practice tests
  • No internet connection needed
  • Enroll for the webinar and join at the time of the webinar from anywhere