Continuous countup timer for Android Game [duplicate] - java

This question already has an answer here:
Timer in Eclipse for Android Game
(1 answer)
Closed 9 years ago.
I have a 3-level math game. Our professor wants me to put a timer that starts at first level and stops only if the user already finished the 3rd level. I have this 3 activity class since I have 3 levels. I made it like this so that I will not be confused.
My problem is how can I make a timer continuously within each activity? I tried the examples found on the internet but I can able to run it on the first level.
Please help , because I don't have any idea how can I make this possible.
Thankyou :)

You could store the time when the game starts and then just calculate the current gameplay time according to that.
First you need to create the static variable to store the time in, we need it to be static, so it can be shared between classes easily.
public static long time_start = System.currentTimeMillis();
Then if you want to get the current passed time since the game started, you would do the following.
double time = (System.currentTimeMillis() - time_start) / 1000d;
The time variable is the passed time since the game started, and it is in seconds.
Then if you further want to reset the gameplay time at any point you would just call.
time_start = System.currentTimeMillis();

When opening a new Activity, use intent.putExtra(currentTime) so that the next Activity knows where to continue the timer from.

Related

How to change variable every x second without stopping the program in Java?

Iam new here, like week ago I started learning to program and Iam working on my text based strategic game in which I would like to make resources gather every x seconds passively.
basicaly my game is based on while (true) loop in which are switch cases and the game keeps waiting for keys to press to gather resources.
I would like the game to gather resources passively every x seconds.
example : every 10 seconds you will receive +1 wood.
I will welcome in help :)
Iam programming in java using NetBeansIDE
Just get the current time in every loop run with this
and check whether the 10 seconds passed since last time you gave +1 wood.
Note the time unit.
I am not sure how you are storing gathered resources, but if you could call a method to look it up based on when the game began. You could store the following variable as part of your game class:
private long startTime = System.currentTimeMillis();
And then get current resources by using the following method:
public int getWood() {
long diffMilliseconds = System.currentTimeMillis() - startTime;
int numSeconds = (int)diffMilliseconds / 1000;
int amtWood = numSeconds/10;
return amtWood + <any other wood gathering/calculating parameters>;
}
This does not account for using your wood. If you want a variable to update every ten seconds, you could use something like the solution here: Print "hello world" every X seconds. This solution uses the TimeTask class. Rather than printing, you could update a amtWood variable.
If there are no restrictions on what classes you can use, try Timer class available as part of Java Swing. You can also look at java.util.Timer class for scheduling your updates.

Run a clock or timer even when app closes - Android

Ever played Candy Crush? Know how you run out of lives and have to wait 30 minutes to regenerate a new life and up to a maximum of 5? That is idea I am trying to implement in my app but I am uncertain on how to have code running even when the user closes app and/or phone.
My question is how to have a timer constantly running in the background of phone until the timer hits X minutes. Would I use the Timer class for this? Because I am familiar with that class and already have a form of it implemented in my app.
There are two pieces to your question:
To actually have a timer running so that you have an action taken after a certain period of time, use the AlarmManager. This should only be used if you are going to proactively interrupt or notify the user.
Your scenario doesn't actually need a timer, and it's more efficient not to use one unnecessarily. Instead, store a timestamp. When your app is opened again, compare the current time to the timestamp and calculate the effect. In the regenerating-lives example, you'd compare timestamps, see that 100 minutes have passed, divide by 30 minutes, and add 3 lives (maybe keeping the extra 10 minute remainder).
If you want timer to run in background you may use AlarmManager. You can set Alarm at specified intervals or you can set it in service if you want single shot alarms. Also while using AlarmManager beware that if your phone goes down then all alarms you've set will be vanished. So take care that you are saving alarm times before phone goes off. Take a look at:
http://developer.android.com/reference/android/app/AlarmManager.html
While using AlarmManager, use correct PendingIntent flags or you could lose previous alarms. If you still want more information you can raise here or have a google.
I don't think you can keep a timer running for you application even when the application is closed. Here is an idea i think about:
You need to start a timer when the life is gone and your application is running.
On your application close event, save that timer value in a persistent storage such as file
On appliction start, read the timer value from the persistent storage, and restart the timer for the remaining time
Once timer expires, generate a new life.
Hope it helps!
I found this answer that might be of great help. Hope it helps others.
There are several different approaches.
You can make use of the System's AlarmManager.
You can make your own Service.
You can make your TimerObject persist.
Check the link for the complete answer and links.

Detect screen press at certain times

So, I am fairly new to java and android programming and I am having an issue coming up with the code for a project I am working on. Basically, there is a list of times, which I assume need to be stored as an array. Once the game has started, it needs to do one of two things:
If the user presses the screen within a few milliseconds of a time in the array, it will register as a hit and increase count.
If the user presses the screen outside of the "hit" time, it will register as a miss and reset count to 0.
Now, I have all the elements in place to make everything work (increasing count on screen press, etc). My issue is with the code to detect if the user pressed the screen on time or not. I have tried doing some searches, but I can't figure it out. Here is a small list of the times that are "good" hits:
0.25
0.84
1.03
1.60
2.3
2.6
2.9
These times can change a little and some can be removed if its not working correctly. The biggest issue I can think of is making sure that it starts the timer when the game starts so the times match up. The current timer starts at 100 and counts down 1 second at a time and when it reaches zero it takes the user to the game over screen. This of course can change if there is a better way to do it or a different way that it has to happen to make the screen press detection code work.
Any idea how to make this work?
Really, all you need to do is log the current system time at the time the game starts. Then, it's just:
long startTime = System.currentTimeMillis();
//...
System.currentTimeMillis() - startTime;
Then, to check if you're within the bounds set at any point in the array (which I will assume is an array of doubles):
public final static int THRESHOLD_MSEC = 100;
public boolean isHit(double time) {
int time = System.currentTimeMillis - startTime;
for(double d : array)
if(Math.abs(d-time) < THRESHOLD_MSEC) return true;
return false;
}
Then, elsewhere in your application, you can handle what happens when isHit returns either true or false. I'm not going to write that part for you. A point of note: a few milliseconds is nothing in comparison to human reflexes, and nobody will be able to make that time.

How to know when another app is begin launching? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android:how does application Protector app works?
How can i be notified when new app begin launching? clearly to say, i click on app icon , and app begin launching, i want to set my service to observer of that event (if there is any). Is there any event or some way to know that before app launched ?
If I were you, I would get the ActivityManager with a call to
getSystemService(Context.ACTIVITY_SERVICE)
and then setup my program with the following code:
private final static Handler updateHandler = new Handler();
private static long WAKEUP_INTERVAL = 10000; // 10secs?
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
checkRunningProcesses();
updateHandler.postDelayed(this, WAKEUP_INTERVAL);
}
};
to do periodical checks of the following two things:
check getRecentTasks() to find out what user has launched recently (requres GET_TASKS permission)
get from getRunningAppProcesses() and keep somewhere list of running processes just in case periodical check interval has been chosen too long and some processes were added/removed but did not show in getRecentTasks()
This way I could not get an instant notification about program launch, but could find about that soon enough (seconds later, maybe) to do something about it.
One more thing, it might be a wise idea to stop checks when screen goes dark, to save the battery.
android listen for app launch
You can't really do this with intents or anything like that. Check out this guy's brute hack. Not a great solution but the closest you'll get.

Getting the system start time in Java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
time since JVM started
Is there a way to get the system start time in Java?
I am trying to make some animations using the Alpha class. Alpha is a Java3D API function that models a time-dependent function into [0,1]. An Alpha instance needs to be told how many milliseconds from the system start to wait before it begins running. It calls this its triggerTime.
I want to be able to write a line of code that starts the Alpha immediately upon execution of the line. It follows that I need to know how much time has passed since the system started. In other words, I need to set alpha.triggerTime to System.currentTimeMillis() - startTime.
So how do I find this startTime? I know that I could call System.currentTimeMillis() as the first line of my code, but this animation is happening in a thread called by a different class than the one that starts the program, and I don't want to have to pass the startTime around to all of these objects. There has to be a cleaner solution.
Thanks,
Jeff
'myAlpha' will start immediately upon execution of following line assuming that 'triggerTime' is '0' (startTime + triggerTime >= currentTime) :
myAlpha.setStartTime(System.currentTimeMillis());
August, InteractiveMesh

Categories