the timer is set in a period of 800 milliseconds, so always RandomPositions() will execute the inner code every 800 milliseconds (the period). Now, what I want is to decrease this number by 50 every 20 seconds or 20,000 milliseconds until it gets the period to 200 milliseconds.
GOAL - IN THE GAME THIS MUST BE INCREASING THE SPEED GRADUALLY EVERY 20 SECONDS.
example: first execution - 800 milliseconds, second execution - 750 milliseconds, third execution - 700 milliseconds, and so on...
What I think is that I could insert a function of type Integer (instead of 800), that can make this job of decreasing from 800 to 200 miliseconds.
How can I make this function? or is there any other solution?
public void RandomPositions() {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run() {
getWindowManager().getDefaultDisplay().getMetrics(displaymatrics);
float dx = r.nextFloat() * displaymatrics.widthPixels/1.2f;
float dy = r.nextFloat() * displaymatrics.heightPixels/1.2f;
button.animate().x(dx).y(dy).setDuration(0);
}
}, 0, 800); // first value = Delay , Second value = Period(what I need to change)
I wouldn't use a Timer for that, as the interval changes all the time.
In vanilla Android I would probably use a Handler
Int interval = 800; // milliseconds
Handler handler = new Handler()
Runnable runnable = new Runnable() {
@Override void run() {
//
// do your logic here
//
// decrement interval by 20 milliseconds
// if interval - 20 is greater than 200
interval = interval - 20 > 200 ? interval - 20 : interval;
// Request an execution of this runnable with the new value of interval
handler.postDelayed(runnable, interval);
}
}
public void start() {
handler.postDelayed(runnable, interval);
}
public void stop() {
handler.removeCallbacks(runnable);
}
Make sure you call removeCallbacks
whenever you want to stop it, or whenever the user is leaving the activity/context where this is running.
Here's a solution that uses a timer. If you don't want to call the method in a loop then just subtract the delay parameter by 50 each time you call it.
public static void main(String[] args) {
Timer timer = new Timer();
for(int i = 800; i >= 200; i-=50)
{
runTimer(timer, i);
}
}
private static void runTimer(Timer timer, int delay) {
timer.schedule(new TimerTask()
{
public void run() {
}
}, 0, delay);
}
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.