Android Creating a variable that increments once per second - android

In Java for Android, I want to create a variable that increases by 1 every second, in other words, it counts, that way I can check to see if a function has been called in the past 3 seconds, and if not, I want it to do something different than if it had been.
Is there any built-in way to do this? I'm familiar with the Timer class, but it doesn't seem to work the way I would want it to.. is there anything else?
tl;dr: I want to create a variable that increases by 1 every second, so I can use it to treat a function differently based on how long it has been since its last call. Is there an easy way to do this? If not, what is the hard way to do this?

Why not store the last time the method was called instead, then check it against the current time?
private long timeLastCalled;
public void someMethod() {
timeLastCalled = SystemClock.elapsedRealTime();
}
public boolean someMethodCalledRecently() {
return (SystemClock.elapsedRealTime() - timeLastCalled) > 3000;
}

final int[] yourVariable = new int[1];
yourVariable[0] = 0;
updateVariableTimer = new CountDownTimer(howLongYouWantTimerToLast, 1000) {
#Override
public void onTick(long l) {
yourVariable[0] += 1;
}
}.start();
Or Alternatively to do it with a flag instead of keeping track of variable counting:
final boolean functionCalledRecently = false;
hasFunctionBeenCalledRecentlyTimer = new CountDownTimer(3000, 1000) {
#Override
public void onTick(long l) {
functionCalledRecently = true;
}
#Override
public void onFinish() {
functionCalledRecently = false;
}
}.start();

If you just need to see if the method has been called within the last 3 seconds you can use a Handler and a Boolean flag to acomplish this.
private Handler mHandler = new Handler();
private boolean wasRun = false;
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if(wasRun){
//whatever you want to do if run
}
mHandler.postDelayed(this, 3000);
}
},3000); //3 sec
In this example the Handler will run on a 3 second delay. Each time it runs it will check to see if the other method was perviously called by evaluating if(wasRun). This way you can change what happens if the method was/was not called. The handler will then start iself again on another 3 second delay. All you have to do then is update the wasRun flag to be true if your method was called, or false if it was not. .

Related

How to obtain the expected order of actions in my game loop?

I don't fully understand what is going on behind the scene, and therefore, what I can do to correctly code this issue. I'm looking for an explanation that will lead me to figure it out myself. This is just a fun home based project(I'm not a student), where I'm coding a turn based app. However, the battle scenes are randomly calculated durations, rather than turn based, so my desire is as follows:
Present initial battle count on screen for 2 seconds
Calculate first skirmish
Present updated battle count on screen for 2 seconds
Calculate 2nd skirmish
...
...
Present Victory or Defeat on screen
The problem I'm having is that the app is performing as follows currently:
Present initial battle count on screen
Calculate all skirmishes
Page displays null for the number, since it's apparently already returned?
Code looks like this:
void fightBattle(){
setContentView(R.layout.brigands);
boolean winnerDetermined = false;
while(!winnerDetermined) {
boolean brigandsWon = brigandsWon(player, brigandCount);
if(brigandsWon) {
player.removeWarriors(2);
}
displayWarriors(player);
if(brigandsWon){
if(player.getWarriors() < 2){
winnerDetermined = true;
}
}
if(!brigandsWon) {
brigandCount = brigandCount / 2;
}
displayBrigands();
if(brigandCount == 0){
winnerDetermined = true;
}
}
}
private void displayWarriors(Player player){
final Player currentPlayer = player;
new CountDownTimer(2000, 2000) {
public void onTick(long millisUntilFinished) { }
public void onFinish() {
setContentView(R.layout.warriors);
TextView warrior_count_tv = findViewById(R.id.warrior_count_tv);
warrior_count_tv.setText(currentPlayer.getWarriors());
}
}.start();
}
private void displayBrigands(Player player){
new CountDownTimer(2000, 2000) {
public void onTick(long millisUntilFinished) { }
public void onFinish() {
setContentView(R.layout.brigands);
TextView brigand_count_tv = findViewById(R.id.brigand_count_tv);
brigand_count_tv.setText(Integer.toString(brigandCount));
}
}.start();
}
Ultimately, what I want to see is something like the below sudo-code:
displayPage1For2Seconds;
while(somethingIsTrue){
calculateNumber;
displayPage2For2Seconds;
displayPage3for2Seconds;
}
displayPage4For2Seconds;
Calculate all skirmishes
Your current code does this because the while loop doesn't actually stops to wait. The flow will be like this:
enter while loop -> call displayWarriors() -> create CountDownTimer() to do something after 2 seconds -> return to while loop -> call displayBrigands() -> create CountDownTimer() to do something after 2 seconds -> return to while loop -> do the same until you exit while
With this code you'll end up with a bunch of CountDownTimers that are created and executed at the same(almost) time so after two seconds they all try to set a view to some value(with an indefinite behavior like you mention it happens).
There are several ways to do what you want. You could use a Thread for example:
void fightBattle(){
setContentView(R.layout.brigands);
new Thread(new Runnable() {
public void run() {
// I assume R.layout.brigands is the initial screen that you want to show for 2 seconds?!? In this case wait 2 seconds
TimeUnit.Seconds.sleep(2);
boolean winnerDetermined = false;
while(!winnerDetermined) {
// ...
// from your code it seems you want to show this for 2 seconds?
displayWarriors(player);
TimeUnit.Seconds.sleep(2);
//...
displayBrigands();
// also show this for 2 seconds
TimeUnit.Seconds.sleep(2);
// ...
}
}
}).start();
}
Then your display methods will be something like this:
private void displayWarriors(Player player){
// you need to wrap this code in a runOnUiThread() method(from the activity)
// because we are on a background thread and we are changing views!
final Player currentPlayer = player;
setContentView(R.layout.warriors);
TextView warrior_count_tv = findViewById(R.id.warrior_count_tv);
warrior_count_tv.setText(currentPlayer.getWarriors());
}
Another approach would be to use a Handler and break your code in Runnables that you then schedule at appropriate times.

Android Handler/Timer Request

So I have a question, and if it's a stupid one I do apologize up front, I have tried to search for it but not sure what to search for exactly. I am trying to run a delayed task, but only if my int = 0, would this work correctly like I am wanting it to?
public static void runTask(String p)
{
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
pendingRequest = pendingRequest - 1;
if (pendingRequest == 0)
{
context.startActivity(p);
}
}
}, 4000);
}
}
What I want it to do is only run if pendingRequest is 0, but I have other activities that add to pending request after the runTask() is called. If this doesn't make any sense please let me know and I will try to reword it.
This is a bit of an obscure way to do things so seeing just this snippet I cant tell exactly what the desired behavior is, however, it should work if you make the parameter "p" final. Im also not familiar with a startActivity method that takes a string instead of an intent, but I cant tell if "context" is actually an Android Context object, but I'm assuming it is.
What I'm not sure about is why you would wait 4 seconds BEFORE decrementing pendingRequest. I would think you want to decrement, allow 4 seconds for someone else to add a pending request, and if it's still 0 after the wait start the Activity... but, again, I cant tell from the snippet.
Try this:
private static Object requestLock = new Object();
public static void runTask(final String p)
{
synchronized(requestLock)
{
if (--pendingRequest > 0) // Decrement first
{
// There are more requests
return;
}
}
// Wait 4 sec and if there are still no requests start the activity.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run()
{
synchronized(requestLock)
{
if (pendingRequest == 0)
{
context.startActivity(p);
}
}
}
}, 4000);
}
}
Note: You will also need to add a synchronized block where you increment the pendingRequests.

How can I control a timer in android?

I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.

Why is my CountDownTimer counting faster than given parameters?

I'm having an issue with my CountDownTimer. Here's the situation:
Working on a game and I am not using a framework (who needs one, right? coughs) and I have a CountDownTimer running. This CountDownTimer is used to calculate how long a player has to complete a level, and also update the screen per 100ms tick.
In the first level this works fine, but in the second level it ticks per 50ms, and in the third per 60/90/50ms ticks (yes, in that order repeatedly) making the game behave odly and messing up collision.
I have no idea what's going on here.
I've ruled out if it's dependant on the level by loading later levels first, and upon solving those the problem arrises all the same.
I have, however, pinpointed where it's going wrong: During the loading for a new level, and only then; even reloading a current level doesn't bring this bug up.
I have a suspicion that somehwere in this code, something's not going as it should be:
public void prepareNewLevel(){
RelativeLayout rl = (RelativeLayout)findViewById(R.id.game);
level.clear();
movables.clear();
img_move.clear();
img_noMove.clear();
timerCount.cancel();
totalSolved = 0;
solvable = 0;
levelWidth = 0;
levelHeight = 0;
allCollided = false;
firstDraw = true;
rl.removeAllViewsInLayout();
}
level, movables, img_move and img_noMove are List items.
This my timer:
MyCount update = new MyCount(15*1000, 100);
This is MyCount:
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
remaining_time = millisUntilFinished;
if(!loadingNewLevel)
MoveObjects();
}
#Override
public void onFinish() {
resetLevel = true;
upMotion = false;
downMotion = false;
leftMotion = false;
rightMotion = false;
update.start();
}
}
And then I also call update.start() at the end of my loadLevel() function. I first thought I had two timers running at once, but writing to the LogCat showed me that was false, concidering I got a neat 'reset' message every 15 seconds, instead of at multiple moments smaller than 15s.
And that's basically the issue here. Now that I know where it's being caused and what the issue is, how do I solve it?
-Zubaja
Try use Timer instead CountDownTimer:
// start timer inside your method
if( timer != null) timer.cancel();
timer = new Timer();
timer.scheduleAtFixedRate( new TimerTask()
{
#Override
public void run()
{
handler.obtainMessage( yourInegerMessage).sendToTarget();
}
}, 100, 15000);
// and define you handler
public Handler handler = new Handler( new Handler.Callback()
{
#Override
public boolean handleMessage( Message message)
{
// use 'message.what' as yourInegerMessage
// ...
return true;
}
});
// and stop your timer after first time
May be this help you.
May be you start more one CountDownTimer? Try stop existing CountDownTimer before start new CountDownTimer.

Small android animation delay issue

I just want to call a function after every 3secs on click of a button
What is going wrong here-
galleryBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Handler handler = new Handler();
for(int i = 0;i<3;i++){
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
viewAnimator.showNext();
}
}, 3000);
}
}
});
You don't actually say what goes wrong but I'll take a wild guess that nothing happens (i.e. no animations) and the reason for that is probably that your Handler is being GC'd long before it gets to handle anything. Try keeping moving 'handlers' scope from local variable to class member.
(Also note that, even when it works, all 3 of your functions will run at more or less the same time. If you want them to run 3 seconds apart you should change the '3000' to 'i*3000'.)

Categories

Resources