Tuesday, April 9, 2013

Countup demo in Android | Custom timer example in Android | Start, Pause, Stop digital watch code in Android | Java example for Watch

Hello Friends,

Today I am going to share very Important code for countdown watch in Android. For this I am using Handler Thread. Hope it will help you guys. Just copy paste below code and enjoy.

1)TimerDemo.java
package com.example.timerdemoandroid;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class TimerDemo extends Activity {
/** Called when the activity is first created. */
private TextView textTimer;
private Button startButton;
private Button pauseButton;
private long startTime = 0L;
private Handler myHandler = new Handler();
long timeInMillies = 0L;
long timeSwap = 0L;
long finalTime = 0L;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_demo);

textTimer = (TextView) findViewById(R.id.textTimer);

startButton = (Button) findViewById(R.id.btnStart);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
myHandler.postDelayed(updateTimerMethod, 0);

}
});

pauseButton = (Button) findViewById(R.id.btnPause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwap += timeInMillies;
myHandler.removeCallbacks(updateTimerMethod);

}
});

}

private Runnable updateTimerMethod = new Runnable() {

public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;

int seconds = (int) (finalTime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
textTimer.setText("" + minutes + ":"
+ String.format("%02d", seconds) + ":"
+ String.format("%03d", milliseconds));
myHandler.postDelayed(this, 0);
}

};

}

2)activity_timer_demo.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="#000000"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textTimer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btnPause"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="37dp"
        android:textSize="40sp"
        android:textColor="#ffffff"
        android:text="00:00:00" />

    <Button
        android:id="@+id/btnPause"
        android:layout_width="90dp"
        android:layout_height="45dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/btnStart"
        android:text="Pause" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="90dp"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="48dp"
        android:text="Start" />

</RelativeLayout>



Please put your comment..
Thanks,

34 comments :

  1. nice tutorial.very helpful.

    ReplyDelete
    Replies
    1. Thanks ak for your valuable comment..

      Delete
    2. can u explane pushnotification in setting

      Delete
    3. @venkateswara what you mean by-"pushnotification in setting" . please see below url for push notification demo.
      http://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html

      Delete
  2. And what about if you want to stop the countdown when it reaches an specified time? how do you do it?

    ReplyDelete
    Replies
    1. Add one more Button for stop watch and
      Use this line of code-
      if (v == imageStop) {
      Toast.makeText(DashboardMoveTrack.this, "Stop", Toast.LENGTH_SHORT).show();
      mTime += millis;
      mHandler.removeCallbacks(mUpdateTimeTask);
      }

      Delete
    2. I don't want to stop it with a button, I want it to stop when it reaches 01:00:00 (one minute) for example. Your countdown (it is not countdown, it increases the time) pauses only if you click the pause button, if not, it continues counting indefily...

      Delete
    3. I think you are looking for just opposite code. Do googling please well it should be something like that-
      @Override
      public void onClick(View v) {
      if (!timerHasStarted) {
      countDownTimer.start();
      timerHasStarted = true;
      startB.setText("STOP");
      } else {
      countDownTimer.cancel();
      timerHasStarted = false;
      startB.setText("RESTART");
      }
      }


      public class MyCountDownTimer extends CountDownTimer {
      public MyCountDownTimer(long startTime, long interval) {
      super(startTime, interval);
      }

      @Override
      public void onFinish() {
      text.setText("Time's up!");
      }

      @Override
      public void onTick(long millisUntilFinished) {
      text.setText("" + millisUntilFinished/1000);
      }
      }

      Delete
  3. Hi..Nice tutorial...
    But I would like to know if there is anyway to pause a progressBar when pause button is clicked and resume it again after play is clicked. Please help if you have any idea.

    ReplyDelete
    Replies
    1. Please check my blog for custom progress bar..

      Delete
    2. Please check my blog for custom progress bar..

      Delete
  4. how to open url in android web browser send coad me

    ReplyDelete
  5. how to open url in android web browser send coad me

    ReplyDelete
    Replies
    1. Hi Please try this post-
      http://www.androidhub4you.com/2012/10/web-view-in-android.html

      Delete
  6. hi I just tried your code and it is great but I think it is not right that it says countdown watch but it counts upwards haha can you tell me how can I make it something like starts from 3:00 and countdown to 0:00 Thanks

    ReplyDelete
    Replies
    1. hmmmm you are right its title should be count-up :)
      any way just do some effort it is doable. Idea is that-
      1)take a initial value like 3 min.
      2)run my code but don't display count-up just calculate 3 minute. and then stop that timer.
      3)for display UI distribute your 3 min in second and millisecond and inside loop time=-1;

      Hope you understand what i am trying to say.
      Thanks!

      Delete
  7. Replies
    1. just stop the thread. and get final value.

      Delete
  8. I wanted to pause my timer on start of dialog box and start once again on cancel on dialog box (no button).here is [My code](http://stackoverflow.com/questions/19224184/how-to-implement-pause-and-resume-countdowntimer)

    ReplyDelete
    Replies
    1. Okay I will response on your question.

      Delete
    2. Check your stack-overflow question.

      Delete
    3. how to take the incoming notification time and store it in some activity .?

      Delete
    4. @Siva Ram- when you get notification form GCM server or local android just get current time of your device like-
      see my this post-
      http://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html
      here 2)GCMIntentService.java
      @Override
      protected void onMessage(Context context, Intent intent) {
      Log.i(TAG, "new message= ");
      Date date=new Date();
      String message = intent.getExtras().getString("message");
      generateNotification(context, message);
      }

      Delete
  9. Great tutorial. It works all fine.To your example I added one more EditText. But when I click on the edittext, the timer is not getting updated in the textview also if I type something in the edittext, its not getting updated.Seems like the UI is halt.Please help me.

    ReplyDelete
    Replies
    1. you want timer value in textview? it is already in a textview. and at the time of typeing in edit-text why it got halt..
      Do one check please before start timer try to type and let me know its halt or not? if no that mean it is thread issue.

      Delete
  10. I want to restart the timer by clicking the next point on image...and i want to store the counter time..

    ReplyDelete
    Replies
    1. use this line of code for restart timer-

      if (v == imageRestart) {
      mTime = 0;
      millis = 0;
      mStartTime = SystemClock.uptimeMillis();

      }

      and for save the counter time just get the value of that textview like=
      String value=textview1.getText.toString();

      Delete
  11. When i copied your code and run it here on my laptop, it says "force close". why is it? Can you help me with this? hoping for your fast reply.

    ReplyDelete
  12. This is a great tutorial but i was wondering how do you take away the milliseconds

    ReplyDelete
  13. hi..when a user presses a button an alert dialog appears and the app should close in some 10 seconds and i need show the remaining time in the alertdialog something like " App will be closed in 10..9..8.....0 seconds" how can i show remaining time in the alert dialog..any help will be helpfull..

    ReplyDelete
  14. I want to save time to shared preferences and load it when app started again.,please help! ?

    ReplyDelete
  15. It is stopped when i close activity so how can i run always in background until timer finish.

    ReplyDelete

Note: Only a member of this blog may post a comment.