简体   繁体   中英

Re executing a code after a certain period of time in android

I am in a google map project and here is my code in oncreate:

mapView = (MapView)findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(false);
        mapView.setStreetView(true);
        mapController = mapView.getController();
        mapController.setZoom(19);
        getLastLocation();
        drawCurrPositionOverlay();
        drawMalls();
        animateToCurrentLocation();

but now i want to call this DrawMalls(); method after some seconds and unless the user closes this application this method will be being called after that time? Is there any way to do this?

You can use Handler and Runnable combination to execute statements after a period of time.

You can delay a Runnable using postDelayed() method of Handler.

Runnable mRunnable;
Handler mHandler=new Handler();

mRunnable=new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                 drawMalls();
                 //If you want to re call this method at a gap of x seconds then you can schedule  handler again
                  mHandler.postDelayed(mRunnable,2*1000);       
                }
            };
mHandler.postDelayed(mRunnable,10*1000);//Execute after 10 Seconds

If you want to cancel this then you have to use removeCallback() method of Handler like mHandler.removeCallbacks(mRunnable);

Or You can use Timer. You can refer an example here http://thedevelopersinfo.wordpress.com/2009/10/18/scheduling-a-timer-task-to-run-repeatedly/

You could use a java.util.Timer 's schedule() method to arrange future execution of drawMalls() :

Timer t = new Timer();

t.schedule(
    new TimerTask()
    {
        public void run()
        {
            System.out.println("hello\n");
        }
    },
    2000); // Milliseconds: 2 * 1000

I am unsure if drawMalls() is a static or non-static method. If it is static then it is straightforward to call in the TimerTask.run() method. Otherwise, you will need to arrange for the class instance to which drawMalls() belongs is available to the run() method of TimerTask :

class DrawMallsTask extends TimerTask
{
    public DrawMallsTask(YourClass a_build) { _instance = a_instance; }

    public void run() { _instance.DrawMalls(); }

    private YourClass _instance;
};

Timer t = new Timer();

t.schedule(new DrawMallsTask(this), 2000);

EDIT:

To repeatedly run the task after every two seconds you can use:

t.scheduleAtFixedRate(new DrawMallsTask(this), 2000, 2000);

您可以按照此处使用ScheduledExecutorService的说明进行操作, 遇到无法停止并在2.1上正确启动计时器的问题之前,我已经遇到了一些错误,不过所描述的调度方案对我来说非常理想。

There are two ways

1) using Handler 2)Using Timer

      //using Timer//
    public void OnCreate(Bundle SaveInstanceState())
    {
      ------------
      -----------------
      PreferedTime  pTime=new preferedTime();

      Timer t=new Timer(false);
      t.Schedule(pTime,2000);
   }


   class PreferedTime extends TimerTask
   {
      public void run()
      {
         drawMalls();
       }
   }




     //method 2//
     public void OnCreate(Bundle SaveInstanceState())
    {
      -----------------
      -----------------
     Handler handler=new handler(new Runnable()
     {
        public void run()
        {
            drawMalls();
         }
      },2000);
MyCount counter;
@Override 
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 counter= new MyCount(60000,1000);
counter.start();
}    


public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
 counter= new MyCount(60000,1000);
}
@Override
public void onTick(long millisUntilFinished) {
    s1=millisUntilFinished/1000;
 if(s1%2==0)
{
drawMalls();

}


}
}

this one calls drawMalls() for every 2 seconds..u can change it as required..

If re-executing code is not bound to state of application, but only to time period, look at Timer class

http://developer.android.com/reference/java/util/Timer.html

Timer timer;

function myCallerFunction(){
    timer = new Timer();
    timer.schedule(seconds * 1000); //must be in milliseconds
}

private class MyTask extends TimerTask {
    public void run() {
      drawMalls();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM