0

I want to run the getVehicles() method every 10 seconds, I have the following code:

Handler vehiclehandler = new Handler();
    final Runnable vehiclerunnable = new Runnable() {   
        public void run() {
            getVehicles(null);
            vehiclehandler.postDelayed(this, 10000);
        } 
    };

Yet at the moment it does nothing, I've searched around and can't figure it out.

I'm new to android and have never used a handler before, only a runnable to tell something to 'runOnUiThread'.

Seb
  • 410
  • 1
  • 6
  • 20

3 Answers3

1

did you run

vehiclehandler.post(vehiclerunnable)

at least once?

I mean outside the Runnable

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • It will not let me run this and I don't know why. I tried to run vehiclehandler.post(vehiclerunnable, 1000); and it would not allow it. – Seb Nov 28 '12 at 13:57
  • What does "not allow" means? does it give you a Compile time error? where did you put the post(Runnable) call? – Blackbelt Nov 28 '12 at 13:58
  • Forgive me, it seems it has allowed it now, it was inside the onCreate method of the activity and I think it was purely Eclipse that wasn't behaving correctly, it is now working! Thanks! – Seb Nov 28 '12 at 13:59
  • If it does work for you, set the answer as accept in order to help other people recognize a fix to similar issue. You are welcome – Blackbelt Nov 28 '12 at 14:00
  • Yep, I have done, it wouldn't let me before as you'd answered me too fast!! – Seb Nov 28 '12 at 14:07
0
final Handler lHandler = new Handler();
Runnable lRunnable = new Runnable() {

    @Override
    public void run() {
        // do stuff
        lHandler.postDelayed(this, 10000);
    }
};
lHandler.post(lRunnable);
DroidBender
  • 7,762
  • 4
  • 28
  • 37
0

Here is an adjustment to your code that will make it run properly

Handler vehiclehandler = new Handler();
    vehiclehandler.postDelayed(new Runnable(){
            public void run(){
                    getVehicles(null);
            }
        },10000);

But this will just delay your code before get executed. If you want to repeat the process over and over again you have to use Timer, something like:

private static Timer timer = new Timer();  
timer.scheduleAtFixedRate(new mainTask(), 0, 10000);
private class mainTask extends TimerTask
    { 
        public void run() 
        {
            getVehicles(null);
        }
    }    
Husam A. Al-ahmadi
  • 2,056
  • 2
  • 20
  • 27