Saturday, July 28, 2012

Android TimerTask

Android TimerTask Example
TimerTask Represents the task will run specified time and it will run only once or Repeat.
Create new Class new TimerTask.
TimerTask Having two methods.

-->
1 .scheduledExecutionTime() // Repeat Task
2 .schedule() //Only once
Timer singleTask = new Timer();
Timer repeatTask = new Timer();

int singleTaskInterval = 3000; // 3 sec
int repeatInterval = 10000; // 10 sec

 // this task for specified time only once it will run
singleTask.schedule(new TimerTask() {
@Override
public void run() {
// Here do something
// This task will run 3 sec only once.
}
}, 1000);

  // this task for specified time it will run Repeat
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Here do something
// This task will run every 10 sec repeat
}
}, 0, repeatInterval);

When your activity went to destroy or stop . you should cancel this task
--> -->
@Override
protected void onDestroy(){
super.onDestroy();
if(singleTask != null){
singleTask.cancel();
}
if(repeatTask != null){
repeatTask.cancel();
}
}
Activity Code
/**
*
* @author vijayakumar
*
*/
public class AndroidMADQAActivity extends Activity {
/** Called when the activity is first created. */
Timer singleTask = new Timer();
Timer repeatTask = new Timer();
int singleTaskInterval = 3000; // 3 sec
int repeatInterval = 10000; // 10 sec
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
singleTask.schedule(new TimerTask() {
@Override
public void run() {
// Here do something
// This task will run 3 sec only once.
}
}, 1000);
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Here do something
// This task will run every 10 sec repeat
}
}, 0, repeatInterval);
}
@Override
protected void onDestroy(){
super.onDestroy();
if(singleTask != null){
singleTask.cancel();
}
if(repeatTask != null){
repeatTask.cancel();
}
}
}



5 comments:

  1. Excellent beat ! I wish to apprentice whilst you amend
    your website, how can i subscribe for a blog web site?
    The account aided me a applicable deal. I had been a little bit acquainted
    of this your broadcast provided vivid transparent concept
    Feel free to visit my weblog Ball Honeys

    ReplyDelete
  2. Excellent beat ! I wish to apprentice whilst you amend
    your website, how can i subscribe for a blog web site

    ReplyDelete
  3. A well informative blog which speaks about Mobile applications hands-on experience like these helps us to become an Android application developer.

    ReplyDelete

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...