How to add timer to app - android

I am a new android developer. Recently, launched a word puzzle app - Wozzle
I want to add timer to the game so that a player gets a limited time to make a move. How to do that ? Also, the timer should be displayed to the player.

Try this,
public class CountDownTest extends Activity {
TextView tv; // textview to display the countdown
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
this.setContentView(tv);
// 5000 is the starting number (in milliseconds)
// 1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(5000, 1000);
counter.start();
}
//countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
tv.setText("done!");
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText("Left: " + millisUntilFinished/1000);
}
}
}
Have a look at these links
A Stitch in Time
On screen timer in Android application?
stop watch logic
Android Game Programming: The Game Loop

Related

Multiple CountDown Timer running one after another

this is my first question here.
I need to implement in my app six countdown timers running one after another. When first finishes, next one starts and so on. Init time of every single run depends on user input. The problem is that I need to put different code in onTick() and onFinish() methods for every single countdown timer running and, well, I'm not sure how to start a next counter after one is finished. I was thinking about calling next counter in onFinish() method of current one but I can't figure out how to do this with 6 counters.
This is my Countdown timer class:
public class Counter extends CountDownTimer
{
public Counter(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick(long millisUntilFinished)
{
//this code is the same for every counter
timer_view.setText(formatTime(millisUntilFinished));
//this code depends on specific counter running
output_view1.setText("My output here");
output_view2.setText("My output here");
output_view3.setText("My output here");
}
public void onFinish()
{
playSound(sound_id_1);
runMyMethod(user_input_1);
timerHasStarted = false;
}
}
I'm starting my counter in the same activity:
if(!timerHasStarted)
{
counter = new Counter(user_input1, 1000);
counter.start();
}
You probably need to break out the start timer functionallity and call it in onFinish().
public void startTimer(int counterId){
Counter counter = null;
switch(counterId){
case 0:
counter = new CounterOne(counterId,user_input1,1000);
break;
/* Counter 1-5 goes here*/
default:
break;
}
if(counter !=null ){
counter.start();
}
}
then start your next timer in onFinsh()
public abstract class Counter extends CountDownTimer
{
private int counterId;
public Counter(int counterId /*counter id start with 0*/,long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
this.counterId = counterId;
}
public abstract void onTick(long millisUntilFinished);
public void onFinish()
{
playSound(sound_id_1);
runMyMethod(user_input_1);
startTimer(this.counterId++);
}
}
public class CounterOne extends Counter{
public void onTick(long millisUntilFinished)
{
//counter 1 logic
}
}
/* Subclass others. eg. CounterTwo etc. */
You never set
timerHasStarted
to true. It's always false, so...yeah, one timer after another. Set it to true before calling counter.start() and it should work.

forever running thread + updating UI in android

Let's say I have a TextView and I want to update it's text with random numbers continuously, from the start of the application until it terminates.
What's the way to perform such a task? Does it have to be timed? (ie update it once in a second etc.) A statement with while(true) can't be used because there's only one UI thread in android and such a statement blocks it forever.
EDIT: Thanks for the quick and accurate answers. After seeing the answers and and thinking a little bit, I've come up with a tricky way to achieve this. Is there any downside of such a technique?
TextView tv;
Handler myHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView1);
myHandler=new Handler();
myHandler.post(new Nani());
}
private class Nani implements Runnable{
int i=0;
#Override
public void run() {
tv.setText(Integer.toString(i));
myHandler.post(this);
i++;
}
}
Simply, Runnable queues itself..
Without knowing more about what exactly you are doing such as when or why, you will want to use a Handler with postAtTime(). This part of the Docs talks more about how to handle these things depending on what you need
This can be achieved by using the Looper class: http://developer.android.com/reference/android/os/Looper.html
A good tutorial for using this, can be found here: http://pierrchen.blogspot.dk/2011/10/thread-looper-and-handler.html
This example approach with self-restarting CountDownTimer would do. Though this might be not the best approach, it will work
public class CountDown extends Activity {
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
this.setContentView(tv);
//5000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(5000,1000);
counter.start();
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
this.start();
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText("your values here");
}
}
}
I think the best way is to use a Handler with timer. But make sure that you must not kill or terminate the runner when living one or other activities
e.g.:
private void timer() {
mRunnable = new HandlerManger();
mHandler = new Handler();
mHandler.postDelayed(mRunnable, 1000*10);
}
The runnable
private class HandlerManger implements Runnable {
#Override
public void run() {
// your business logic method here;
}
}
Activity
private Handler mHandler;
private Runnable mRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act...);
timer();
}

Using a CountDownTimer to display a toast until button is pressed

I have an activity that starts after a certain time. Once this activity starts, the user is supposed to press a button that starts a new timer.
However, if the user does not press the button I want a toast to be displayed every 5 seconds until the button is pressed.
I'm trying to use a CountDownTimer. Here is the basics of the code I have so far:
I have no errors but no toasts are being displayed at the moment. Is it ok to have the MyCount class inside the BreakActivity class (if i put it outside I get an error).
Any help in getting this sorted will be greatly appreciated!
public class BreakActivity extends Activity {
Button startBreakButton; // button to start the break timer
Boolean clicked= false;
CountDownTimer counter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.breakscreen); // sets layout to breakscreen.xml
MyCount counter;
counter=new MyCount(5000,1000);
counter.start();
startBreakButton = (Button) findViewById(R.id.startBreakButton);
startBreakButton.setOnClickListener(mStartListener);
View.OnClickListener mStartListener = new OnClickListener() {
clicked=true;
//other listener code
};
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
if(clicked=false){
Toast.makeText(getApplicationContext(), "TAKE A BREAK", Toast.LENGTH_LONG).show();
counter= new MyCount(5000,1000);
counter.start();
}
}
#Override
public void onTick(long millisUntilFinished) {
long s1 = millisUntilFinished;
}
}
};
change :
if(clicked=false)
to
if(clicked==false)

Is there a Timer functionality in android? (Not the java.util.Timer)

Is there a timer functionality or timer that is a subclass of View in android that can be use to keep track the playing time of the user?
If I must build one, is it good to build a Thread or Runnable class that have a loop that put itself to sleep for 1000ms (Thread.sleep(1000)) then update itself. e.g.
public class TimerThread extends Runnable{
private int time;
boolean run = true;
public void run(){
while(run){
//update the View here
Thread.sleep(1000);
time++;
}
}
}
This might be helpful.
http://developer.android.com/reference/android/widget/Chronometer.html
I think you might need to Google for an example never really used it myself but I've heard of it.
Here is some code I use in one of my games. Hope it helps
MyCount counter = new MyCount(30000,10); //set to 30 seconds
counter.start();
public class MyCount extends CountDownTimer{
long time=0;
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
clock.setText("You lose!"); //clock is a textfield in the game
restart(); //call you own restart method
}
#Override
public void onTick(long millisUntilFinished) {
DecimalFormat df=new DecimalFormat("#.##"); //import java.text.DecimalFormat;
clock.setText("Left: "+ df.format(millisUntilFinished/1000.0));
time=millisUntilFinished;
}
public long getTime(){
return time;
}
}
Take look at.
http://developer.android.com/reference/android/os/CountDownTimer.html
Just to provide more options, here is another approach: Updating the UI from a Timer

Create a simple timer in a game

I would be very grateful if someone could explain how to create a simple timer in a game which starts off at 30 seconds and then goes back until 0. At 0 I would then stop the game and invoke a method which would allow the next player to take a turn.
Any advice would be appreciated. Thanks
Edit:
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCount extends CountDownTimer {
static TextView timeDisplay;
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
timeDisplay.setText("Done!");
}
public void onTick(long millisUntilFinished) {
timeDisplay.setText("Left: " + millisUntilFinished / 1000);
}
}
In a seperate class I have created a method:
public void setTimer() {
timeDisplay = new TextView(this);
this.setContentView(timeDisplay);
MyCount counter = new MyCount(30000, 1000);
counter.start();
}
Within an onClick method I have called the method above:
public void onClick(View v) {
setTimer();
}
I'd appreciate any advice on this.

Categories

Resources