views:

257

answers:

3

hi all, this is my first post..

so I'm learning Android & Java (coming from Actionscript), and I'm working on a project where :

I'm trying to click an ImageView, have that ImageView swap images for a second, then return to the original image. ( this is for a tapping game )

sounds easy enough, right? I've spent the whole day trying to get a standard Java Timer / TimerTask to work.. no luck..

is there a better way? I mean, is there an Android specific way to do something like this? If not, then what is the ideal way?

thanks for all your help in advance guys! -g

A: 

One way could be creating a Pipeline thread(a normal thread with Looper.prepare()). Post delayed messages to its message loop. In the Message Handler, swap the images. See the following list of tutorials to understand the entities involved:
Handler Tutorial
Handler: documentation
Android guts into Loopers(Pipeline threads) and Handlers

Hope that helps.

Samuh
+1  A: 

Here is my Android timer class which should work fine. It sends a signal every second. Change schedule() call is you want a different scheme.

Note that you cannot change Android gui stuff in the timer thread, this is only allowed in the main thread. This is why you have to use a Handler to give the control back to the main thread.

import java.util.ArrayList;

import java.util.List; import java.util.Timer; import java.util.TimerTask;

import android.os.Handler; import android.os.Message;

public class SystemTimerAndroid { private final Timer clockTimer;

private class Task extends TimerTask {
    public void run() {
        timerHandler.sendEmptyMessage(0);
    }
}

private final Handler timerHandler = new Handler() {
    public void handleMessage (Message  msg) {
        // runs in context of the main thread
        timerSignal();
    }
};

private List<SystemTimerListener> clockListener = new ArrayList<SystemTimerListener>();

public SystemTimerAndroid() {
    clockTimer = new Timer();
    clockTimer.schedule(new Task(), 1000, 1000);
}

private void timerSignal() {
    for(SystemTimerListener listener : clockListener)
        listener.onSystemTimeSignal();      
}

public void killTimer() {
    clockTimer.cancel();
}

@Override
public void addListener(SystemTimerListener listener) {
    clockListener.add(listener);        
}

}

StefanMK
A: 

you might find this article helpful Timed UI updates

schwiz
thanks for all your help guys! I"m looking into it all now..
Yorgo12345