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.
Please put your comment..
Thanks,
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,
nice tutorial.very helpful.
ReplyDeleteThanks ak for your valuable comment..
Deletecan u explane pushnotification in setting
Delete@venkateswara what you mean by-"pushnotification in setting" . please see below url for push notification demo.
Deletehttp://www.androidhub4you.com/2013/04/google-cloud-messaging-example-in.html
And what about if you want to stop the countdown when it reaches an specified time? how do you do it?
ReplyDeleteAdd one more Button for stop watch and
DeleteUse this line of code-
if (v == imageStop) {
Toast.makeText(DashboardMoveTrack.this, "Stop", Toast.LENGTH_SHORT).show();
mTime += millis;
mHandler.removeCallbacks(mUpdateTimeTask);
}
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...
DeleteI think you are looking for just opposite code. Do googling please well it should be something like that-
Delete@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);
}
}
Nice Demo...
ReplyDeleteThanx....
Thanks umesh!
DeleteHi..Nice tutorial...
ReplyDeleteBut 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.
Please check my blog for custom progress bar..
DeletePlease check my blog for custom progress bar..
Deletehow to open url in android web browser send coad me
ReplyDeletehow to open url in android web browser send coad me
ReplyDeleteHi Please try this post-
Deletehttp://www.androidhub4you.com/2012/10/web-view-in-android.html
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
ReplyDeletehmmmm you are right its title should be count-up :)
Deleteany 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!
How to stop timer ?
ReplyDeletejust stop the thread. and get final value.
DeleteI 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)
ReplyDeleteOkay I will response on your question.
DeleteCheck your stack-overflow question.
Deletehow to take the incoming notification time and store it in some activity .?
Delete@Siva Ram- when you get notification form GCM server or local android just get current time of your device like-
Deletesee 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);
}
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.
ReplyDeleteyou want timer value in textview? it is already in a textview. and at the time of typeing in edit-text why it got halt..
DeleteDo 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.
I want to restart the timer by clicking the next point on image...and i want to store the counter time..
ReplyDeleteuse this line of code for restart timer-
Deleteif (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();
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.
ReplyDeleteThis is a great tutorial but i was wondering how do you take away the milliseconds
ReplyDeletehi..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..
ReplyDeleteI want to save time to shared preferences and load it when app started again.,please help! ?
ReplyDeleteIt is stopped when i close activity so how can i run always in background until timer finish.
ReplyDelete