Can anybody here help me with this code? It's working but when the countdown timer is finished it closes down my apps. I want it to display "finish" on text. But the coding for onFinish that I have used seems not workable.
public class SimpleCountdowTimer extends CountDownTimer {
public static int oneSecond = 1000;
TextView statusTextView;
ProgressBar mprogressBar, mprogressBar1;
Button startTimerButton;
Button stopTimerButton, pauseTimerButton, resumeTimerButton;
private long timeRemaining = 0;
public SimpleCountdowTimer(long millisInFuture, long countDownInterval,
TextView statusTextView, ProgressBar mprogressBar, ProgressBar mprogressBar1) {
super(millisInFuture, countDownInterval);
this.statusTextView = statusTextView;
this.mprogressBar1 = mprogressBar1;
this.mprogressBar = mprogressBar;
}
#Override
public void onTick(long millisInFuture) { //do something in every tick
//Put count down timer remaining time in a variable
statusTextView.setText(String.valueOf(millisInFuture/ oneSecond));
long millis = millisInFuture;
timeRemaining = millisInFuture;
long countDownInterval = 1000;
mprogressBar1.setProgress((int) (millisInFuture));
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
statusTextView.setText(hms);//set text
}
#Override
public void onFinish() {
statusTextView.setText("00:00:00");
mprogressBar.setVisibility(View.VISIBLE);
mprogressBar1.setVisibility(View.VISIBLE);
//Disable the pause, resume and cancel button
pauseTimerButton.setEnabled(false);
resumeTimerButton.setEnabled(false);
stopTimerButton.setEnabled(false);
//Enable the start button
startTimerButton.setEnabled(true);
}
}
Why don't you use this way :
CountDownTimer cdt = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
statusTextView.setText(String.valueOf(millisInFuture/ oneSecond));
long millis = millisInFuture;
timeRemaining = millisInFuture;
long countDownInterval = 1000;
mprogressBar1.setProgress((int) (millisInFuture));
//Convert milliseconds into hour,minute and seconds
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis), TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
statusTextView.setText(hms);//set text
}
#Override
public void onFinish() {
statusTextView.setText("00:00:00");
mprogressBar.setVisibility(View.VISIBLE);
mprogressBar1.setVisibility(View.VISIBLE);
//Disable the pause, resume and cancel button
pauseTimerButton.setEnabled(false);
resumeTimerButton.setEnabled(false);
stopTimerButton.setEnabled(false);
//Enable the start button
startTimerButton.setEnabled(true);
}
};
cdt.start();
Related
I was creating a timer app and I wanted to use CountdownTimer on Android Studio with a variable . It was showing no error , but on run-time it is (CountdownTimer) running only one time.
int set=1;
final long totalTime=(hour*60)+min;
if(set==1){
new CountDownTimer(totalTime , 1000){
#Override
public void onTick(long millisUntilFinished) {
long min=millisUntilFinished/1000;
Log.i("Remaining time", String.valueOf(min));
}
#Override
public void onFinish() {
}
}.start();
May be if you pass totalTime in ms like..
final long totalTime=(hour*60)+min; //In min convert to ms
long totalTimeInMs = ((hour*60)+min)*60*1000)
new CountDownTimer(totalTimeInMs , 1000){
#Override
public void onTick(long millisUntilFinished) {
long second = millisUntilFinished/1000;
long min = millisUntilFinished/60;
Log.i("Remaining time", String.valueOf(min));
}
#Override
public void onFinish() {
}
}.start();
CountDownTimer ctor expects two time intervals millisInFuture and countDownInterval, both in milliseconds. So:
final long totalTimeInMinutes=(hour*60)+min;
final long totalTime=totalTimeInMinutes * 60 * 1000;
I'm building a chat app which having voice message feature but while recording couldn't get any feeler or timer like "WhatsApp" so can anybody have this solution
I tried the code of developer Android but could find such a solution.
btn_voice.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN)
{
startRecording();
}
else if(event.getAction()==MotionEvent.ACTION_UP)
{
stopRecording();
}
return false;
}
});
Create a hanldler
private Handler customHandler = new Handler();
then in startRecording(){starttimer();}
Then
private void starttimer() {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
// customHandler.removeCallbacks(updateTimerThread);
}
private Runnable updateTimerThread = new Runnable() {
#SuppressLint({"SetTextI18n", "DefaultLocale"})
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
dialTimer.setText("" + mins + ":"+String.format("%02d", secs) + ":"+String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
And To stop the timer
customHandler.removeCallbacks(updateTimerThread);
You can also refer these ..
Linear Timer is a custom view for Android that enables circular progress animation
https://github.com/krtkush/LinearTimer
// After running for a few minutes the UI stop updating inside of the tick function.
//This is update function of my text view in given below
private void timerGreen(final long time, long interval) {
hourglassGreen = new Hourglass(time, interval) {
#Override
public void onTimerTick(long timeRemaining) {
updateUIGreen(timeRemaining);
if (soundrunning) {
soundTick = new SoundTick();
soundTick.playSound(MainActivity.this);
}
}
#Override
public void onTimerFinish() {
}
};
}
// here it is my textview call in my function
private void updateUIGreen(long timeRemain) {
greenTextView.setText(correctFormat(timeRemain));
}
//here my correctFormat method
public String correctFormat(long millisUntilFinished) {
int minutes = (int) (millisUntilFinished / 1000) / 60;
int secs = (int) (millisUntilFinished / 1000) % 60;
return String.format(Locale.getDefault(), "%02d:%02d", minutes, secs);
}
I want find the seconds between the current time and a date selected from a a calendar view. My current method goes as follows
mCalculateButton = (Button) findViewById(R.id.calcButton);
mDatePicker = (CalendarView) findViewById(R.id.calendarView);
mCalculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Grabbing the date selected from the CalendarView to send to intent
long age = mDatePicker.getDate();
startCalculation(age);
}
});
}
private void startCalculation(long age){
Intent intent = new Intent(this, CalcActivity.class);
intent.putExtra("key_age", age);
startActivity(intent);
}
and in the calculations activity
Intent intent = getIntent();
//Date selected in MSUE
mSelectedTime = intent.getLongExtra("key_age", 0);
//Current date in MSUE
mCurrTime = System.currentTimeMillis();
mSecondsInfo = (TextView) findViewById(R.id.secondsInfo);
mDaysInfo = (TextView) findViewById(R.id.daysInfo);
mMonthsInfo = (TextView) findViewById(R.id.monthsInfo);
mYearsInfo = (TextView) findViewById(R.id.yearsInfo);
//Replacing format specifiers with desired age information
mSecondsInfo.setText(mSecondsInfo.getText().toString().replace("%i%", Long.toString(ageInSeconds(mSelectedTime, mCurrTime))));
mDaysInfo.setText(mDaysInfo.getText().toString().replace("%i%", Long.toString(ageInDays(mSelectedTime, mCurrTime))));
mMonthsInfo.setText(mMonthsInfo.getText().toString().replace("%i%", Long.toString(ageInMonths(mSelectedTime, mCurrTime))));
mYearsInfo.setText(mYearsInfo.getText().toString().replace("%i%", Long.toString(ageInYears(mSelectedTime, mCurrTime))));
}
private long ageInSeconds(long mil, long currTime){
return (currTime - mil) / 1000;
}
private long ageInDays(long mil, long currTime){
return (currTime - mil)/ 1000 / 60 / 60 / 24;
}
private long ageInMonths(long mil, long currTime){
return (currTime - mil) / 1000 / 60 / 60 / 24/ 30;
}
private long ageInYears(long mil, long currTime){
return (currTime - mil) / 1000 / 60 / 60 / 24/ 30 / 12;
}
The issue is that the time returned by mDatePicker.getDate only increases by ~4000 milliseconds each day that it increments and I have no idea why. Any ideas as of to why this does not work?
CalendarView is not storing the selected date, but you can listen to the selection event and store it yourself.
mDatePicker .setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
storedDate = new GregorianCalendar(year,month,dayOfMonth);
}
});
mCalculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCalculation(storedDate.getTimeInMillis());
}
});
I'm trying to make a countdown timer starting at 10 minutes, similair to a basketball scoreboard: 10:00 to 00:00. How would I do that? This is my code:
private TextView Timer;
Handler handler = new Handler();
private int length = 120000;
private int decision = 0;
MyCount counter;
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
if (seconds < 10)
sec = "0" + seconds;
if (minutes < 10)
min= "0" + minutes;
output = min + " : " + sec;
return output;
}//formatTime
#Override
public void onCreate(Bundle cute) {
super.onCreate(cute);
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
}//end of cuteness
private Runnable updateTimeTask = new Runnable() {
public void run() {
updateTime();
handler.postDelayed(this, 1000);
}
};
private void updateTime() {
switch (decision) {
case 0:
startTime = 0L;
counter.start();
decision=1;
break;
case 1:
counter.onPause();
decision=0;
break;
}
}//updateTime
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}//MyCount
public void onPause() {
//do stuff later
onPause();
}//finish
public void onTick(long millisUntilFinished) {
Timer.setText("" + formatTime(millisUntilFinished));
}//on tick
#Override
public void onFinish() {
onStop();
}//finish
}//class MyCount
Any help would be appreciated. thanks!
This does not have to be too hard. You've already created your functionality for writing your time in letters, now you need to count down. Starting a timer is easy, just do this in your start button event handler (or whatever you choose to use) (modified example from the android developer reference:
// New timer for 10 minutes, starts after initialization
new MyCount(600000, 1000)
{
// Updates the text on your "scoreboard" every second
public void onTick(long millisUntilFinished)
{
Timer.setText("Time remaining: " + formatTime(millisUntilFinished));
}
public void onFinish()
{
mTextField.setText("done!");
}
}.start();
And that's all you need! You can skip your UpdateTime function and your updateTimeTask. Just replace all this on your onCreate method
counter = new MyCount(length, 1000);
updateTime();
handler.removeCallbacks(updateTimeTask);
handler.postDelayed(updateTimeTask, 1000);
With my code. Or modify it as you please!
why don't you just create 3 textviews so that it will be easier for you to code?
one for the minutes.
one for the colon.
one for the seconds.
then use the code he's using.
hope I helped.
The way i think of making a count down is just saving at the beginning the (current time + 10 minutes) aside and then just subtract it from current time every second in your handler and display the result in the desired format..