I'm having an issue where my code won't display the onTick method, and each time the counter is run, it simply displays the text "Done", as it should when it's finished. It seems that the endTime variable isn't being passed to the timer class? Any help with what I'm missing would be appreciated.
public class MainActivity extends AppCompatActivity {
private long endTime;
private MyTimer mainTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set up the two number pickers
NumberPicker minutes = (NumberPicker) findViewById(R.id.minutes);
pickerSetup(minutes);
NumberPicker seconds = (NumberPicker) findViewById(R.id.seconds);
pickerSetup(seconds);
mainTimer = new MyTimer(this, endTime, 1000);
}
public void pickerSetup(NumberPicker pickerId){
pickerId.setMaxValue(60);
pickerId.setMinValue(0);
pickerId.setWrapSelectorWheel(true);
}
public void calcTime(View view){
//Get value of Number pickers and convert to milliseconds from minutes and seconds.
NumberPicker minutes = (NumberPicker) findViewById(R.id.minutes);
int selectedMinutes = minutes.getValue() * 60000;
NumberPicker seconds = (NumberPicker) findViewById(R.id.seconds);
int selectedSeconds = seconds.getValue() * 1000;
//Add selected Minutes and seconds together
endTime = selectedMinutes + selectedSeconds;
Log.v("End time = ", String.valueOf(endTime));
mainTimer.start();
}
}
timer class:
class MyTimer extends CountDownTimer {
private Context mContext;
private TextView mToUpdate;
public MyTimer(Context context, long startTime, long interval) {
super(startTime, interval);
mContext = context;
TextView toUpdate = (TextView) ((Activity)mContext).findViewById(R.id.intervalTimer);
mToUpdate = toUpdate;
}
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
mToUpdate.setText(String.valueOf(minutes) + ":" + String.valueOf(seconds));
}
#Override
public void onFinish() {
mToUpdate.setText("Done");
}
}
It happens because you are not initialized endTime when the time of calling mainTimer = new MyTimer(this, endTime, 1000); . It is set to 0 and that is why it stops as starts. You can change the two methods into something like this.
public long calcTime(View view){
//Get value of Number pickers and convert to milliseconds from minutes and seconds.
NumberPicker minutes = (NumberPicker) findViewById(R.id.minutes);
int selectedMinutes = minutes.getValue() * 60000;
NumberPicker seconds = (NumberPicker) findViewById(R.id.seconds);
int selectedSeconds = seconds.getValue() * 1000;
//Add selected Minutes and seconds together
endTime = selectedMinutes + selectedSeconds;
Log.v("End time = ", String.valueOf(endTime));
return mainTimer.start();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set up the two number pickers
NumberPicker minutes = (NumberPicker) findViewById(R.id.minutes);
pickerSetup(minutes);
NumberPicker seconds = (NumberPicker) findViewById(R.id.seconds);
pickerSetup(seconds);
endTime=calcTime();
mainTimer = new MyTimer(this, endTime, 1000);
mainTimer.start();
}
Related
I am an absolute beginner and was trying to code a Count-up-timer app that will run in the background, in other words when the app is closed from overview or when the back button is pressed, the timer will still appear to continue on the corrected time the next time the app is opened. I tried to do this by using SharedPreferences.
An error that I run into is that when I launch the emulator, the timer does not start at 00:00:00 as it should, however, it starts at random times. Here is a screenshot
public class MainActivity extends AppCompatActivity {
TextView timerText;
TextView dayText;
Button startStopButton;
Timer timer;
TimerTask timertask;
Double time = 0.0;
Double mEndTime = 0.0;
Double startingSysTime = 0.0;
Double timeGap = 0.0;
public static final String SHARED_PREFS ="sharedPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerText = (TextView) findViewById(R.id.timerText);
startStopButton = (Button) findViewById(R.id.startStopButton);
dayText = (TextView) findViewById(R.id.dayText);
timer = new Timer();
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
time = Double.longBitsToDouble(prefs.getLong("mTimeValue", Double.doubleToLongBits(0.0)));
mEndTime = Double.longBitsToDouble(prefs.getLong("onDestr_SysTime", Double.doubleToLongBits(0.0)));
if(mEndTime==0.0){
startingSysTime = 0.0;
}else{
startingSysTime = (double) (System.currentTimeMillis());
}
timeGap = startingSysTime - mEndTime;
time += timeGap;
startTimer();
}
#Override
protected void onStop() {
super.onStop();
Log.i("TIMEGAP", "onStop called");
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("mTimeValue", Double.doubleToRawLongBits(time)); //saves the time value
editor.putLong("onDestr_SysTime", Double.doubleToRawLongBits(System.currentTimeMillis())); //saves the CurrentSystemTime when onStop is invoked
editor.apply();
}
private void startTimer() {
timertask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
time++;
timerText.setText(getTimerText());
dayText.setText(getDayText());
}
});
}
};
timer.scheduleAtFixedRate(timertask, 0, 1000);
}
private String getDayText() {
int rounded = (int) Math.round(time);
int days = (rounded / 86400);
return formatDay(days);
}
private String formatDay(int days) {
String pluralDays;
if (days == 1) {
pluralDays = " Day";
} else {
pluralDays = " Days";
}
return days + pluralDays;
}
private String getTimerText() {
int rounded = (int) Math.round(time);
int seconds = ((rounded % 86400) % 3600) % 60;
int minutes = ((rounded % 86400) % 3600) / 60;
int hours = ((rounded % 86400) / 3600);
return formatTime(seconds, minutes, hours);
}
private String formatTime(int seconds, int minutes, int hours) {
return String.format("%02d", hours) + " : " + String.format("%02d", minutes) + " : " + String.format("%02d", seconds);
}
EDIT: Problem fixed, I simply had to convert timeGap to seconds by dividing it by 1000
timeGap = (startingSysTime - mEndTime)/1000;
Try this way
Handler.postDelayed(new Runnable{
//Todo write your code here
handler.postdelayed(this,1000);
},1000);
Start where you need
long starttime;
start time = System.currentTimeMilisecond();
End where you need
long currtime = System.currentTimeMilisecond() - startime;
}
According to your question try to convert this millisecond in your format which you need. Store long value in shared preference if you want to manage this on app close also
I have implemented timer like this (Mentioned in code). I changed its string format so that it takes hours:minutes:seconds and for me, to use a switch, I have to add an if(){} conditional statement.
So I did and I had to declare the string inside the if(){} cause i couldnt do it outside if(){}. But now I want to use that string information for an intent to open a new activity and assign the string value to a TextView.
The problem is I can't use the string outside of the if(){} and at first I used the hms string with a TextView called myText.
The thing is that the myText TextView worked perfectly on the first activity but when sending the information using Inetnt to another Textview in the other activity it showed no change on the TextView.
Heres is the code:
if (mySwitch.isChecked()) {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//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)));
myText.setText(hms);
}
public void onFinish() {
myText.setText("TIME'S UP!!"); //On finish change timer text
}
}.start();
and heres how i used the Intent Activity1:
Intent toST = new Intent(MainActivity.this, ShowTime.class);
String textMessage = myText.getText().toString() ;
toST.putExtra("wargra", textMessage);
startActivity(toST);
and heres how I received it in activity2:
Bundle receiver = getIntent().getExtras();
if(receiver == null){
return;
}
String textMessage = reciver.getString("wargra");
myText2.setText(textMessage);
How can I send hms value to myText2?
Here is the complete activity1 code:
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Switch;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
Button silentButton;
AudioManager myAudioManager;
NumberPicker numPickerHour;
NumberPicker numPickerMin;
Switch mySwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Text,Audio,Button,Time
myAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
silentButton = (Button) findViewById(R.id.Start);
//Number Picker
numPickerHour = (NumberPicker) findViewById(R.id.numberPickerHour);
numPickerMin = (NumberPicker) findViewById(R.id.numberPickerMinute);
mySwitch = (Switch) findViewById(R.id.Toggle);
//Hour
numPickerHour.setMaxValue(24);
numPickerHour.setMinValue(0);
numPickerHour.setWrapSelectorWheel(true);
//Min
numPickerMin.setMaxValue(60);
numPickerMin.setMinValue(0);
numPickerMin.setWrapSelectorWheel(true);
silentButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final TextView myText;
myText = (TextView)findViewById(R.id.timeText);
if (mySwitch.isChecked()) {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("Viberation end in: " + "%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)));
myText.setText(hms);
//set text
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
public void onFinish() {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
myText.setText("TIME'S UP!!"); //On finish change timer text
}
}.start();
} else {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//Convert milliseconds into hour,minute and seconds
String hms = String.format("Silent ends in (" + "%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)));
myText.setText(hms);//set text
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
public void onFinish() {
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
myText.setText("TIME'S UP!!"); //On finish change timer text
}
}.start();
}
Intent toST = new Intent(MainActivity.this, ShowTime.class);
String textMessage = myText.getText().toString() ;
toST.putExtra("wargra", textMessage);
startActivity(toST);
}
}
);
}
}
final TextView myText;
myText = (TextView)findViewById(R.id.timeText);
Change these two lines. Declare myText globally (as you have already done with silentButton, myAudioManager, numPickerHour, numPickerMin, mySwitch).
public class MainActivity extends AppCompatActivity {
//Following your other code
....
TextView myText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Following your other code
....
myText = (TextView)findViewById(R.id.timeText);
//Rest of your code
....
}
}
Hope your problem will be gone.
There could be two reasons and solutions:
case 1: If you are using your if inside a Thread then you should update the TextView on UIThread i.e MainThread.
Like this:
if (mySwitch.isChecked()) {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//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)));
MainActivity.this.runOnUIThread(new Runnable()
{
#Override
public void run()
{
myText.setText(hms);
}
}).start();
}
public void onFinish() {
MainActivity.this.runOnUIThread(new Runnable()
{
#Override
public void run()
{
myText.setText("TIME'S UP!!"); //On finish change timer text
}
}).start();
}
}.start();
You should always update any UI element on MainThread only by using the runOnUIThread() method. May be this was the cause of your problem.
case 2: Solution given by Sudip Podder.
case 3 : Answer to your query :
In java you can not just use a variable outside of its scope. All you can do the thing is to put the value to class variable like this :
Just declare a class variable and put value in it and then use the class variable for the values.
public class MainActivity extends AppCompatActivity {
....
....
String time;
....
....
}
....
....
....
if (mySwitch.isChecked()) {
int getvaluehour = numPickerHour.getValue();
int getvalueminute = numPickerMin.getValue();
getvaluehour = getvaluehour * 3600000;
getvalueminute = getvalueminute * 60000;
long hoursandMinstomils = getvalueminute + getvaluehour;
new CountDownTimer(hoursandMinstomils, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to edittext
long millis = millisUntilFinished;
//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)));
MainActivity.this.time=hms;
MainActivity.this.runOnUIThread(new Runnable()
{
#Override
public void run()
{
myText.setText(MainActivity.this.time);
}
}).start();
}
public void onFinish() {
MainActivity.this.runOnUIThread(new Runnable()
{
#Override
public void run()
{
myText.setText("TIME'S UP!!"); //On finish change timer text
}
}).start();
Now you can use the value of hms variable by the class variable time. And yes don't forget to declare myText as class variable.
I'm making a simple app where I start a countdown timer e.g. 25 to 0 and when the timer expires it shows a template.But when my mobile is locked timer will be paused and when i unlocked it will resume .what can i do for continues timer ??
public class MyActivity extends Activity {
TextView tvCountDown;
MyCount counter;
long countDownInterval = 1000;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auth);
tvCountDown = (TextView) findViewById(R.id.tvCountDown);
counter = new MyCount(6000, countDownInterval);
counter.start();
}
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick (long millisUntilFinished)
{
Log.v("test","onTick Seconds: "+millisUntilFinished+" : "+(millisUntilFinished / 1000));
tvCountDown.setText ( formatTime(millisUntilFinished));
System.out.print("");
}
public void onFinish() {
tvCountDown.setText("done!");
}
public String formatTime(long millis)
{
String output = "00:00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD + " : " + minutesD + " : " + secondsD;
return output;
}
}
Just call .cancel() method when your activity/fragment going to destroy.
If you want to pause/resume yout timer go for this answer;
My app checks if there is a file with a date.
If there is a date, it calculates the difference between today and that (future) date and initializes a timer counting down the seconds until that date in the way X days Y hours Z minutes S seconds.
If there is no file, then the user can select a date with a button. The program will store the date in the file and set the countdown.
There is a Delete Button to delete the date and choose another. This delete button should cancel the timer so it stops counting.
The timer does not stop when I cancel it. My timer is ticking but the difference is 2 seconds instead of one. It shows 40 38 36... instead of 40 39 38...
And lastly, it's storing the picked date twice instead of once.
The DatePicker code is from here.
public class NextVisit extends Activity implements DatePickerFragment.TheListener{
protected Vibrator vibrate;
protected int SECONDS_IN_A_DAY = 24 * 60 * 60;
protected String filePath = "";
protected SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
final long[] pattern = {0, 1000, 500, 1000, 500, 1000, 500, 1000 };
CountDownTimer timer = null;
String dateString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next_visit);
final TextView label = (TextView) findViewById(R.id.label);
final TextView countdown = (TextView) findViewById(R.id.time_visit);
final Button bDate = (Button) findViewById(R.id.date_button);
final Button bDelete = (Button) findViewById(R.id.delete_button);
File dir = new File(getFilesDir(), "loveApp");
if(!dir.exists())
dir.mkdirs();
final File f = new File(getFilesDir()+"/loveApp"+"/love_date.txt");
filePath = f.getAbsolutePath();
vibrate = (Vibrator) getSystemService(VIBRATOR_SERVICE);
bDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(f.exists()){
f.delete();
System.out.println("File deleted successfully");
bDate.setVisibility(View.VISIBLE);
label.setText(R.string.next_visit1);
timer.cancel();
countdown.setText("");
System.out.println("I cancelled the timer");
bDelete.setVisibility(View.INVISIBLE);
bDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
bDelete.setVisibility(View.VISIBLE);
bDate.setVisibility(View.INVISIBLE);
picker.show(getFragmentManager(), "datePicker");
}
});
}
}
});
if(f.exists()){
System.out.println("File exists");
bDate.setVisibility(View.INVISIBLE);
label.setText(getString(R.string.label));
try{
BufferedReader br = new BufferedReader(new FileReader(f));
dateString = br.readLine();
br.close();
System.out.println("Date: "+dateString);
Date finalDate = formatter.parse(dateString);
setCountdown(finalDate);
}catch(Exception e){
e.printStackTrace();
label.setText("ERROR");
}
}else{
System.out.println("File DOES NOT EXIST");
bDelete.setVisibility(View.INVISIBLE); //Removing the delete date button
bDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
bDelete.setVisibility(View.VISIBLE);
bDate.setVisibility(View.INVISIBLE);
picker.show(getFragmentManager(), "datePicker");
}
});
}
}
public void setCountdown(Date finishDate){
long end = finishDate.getTime();
final TextView countdown = (TextView) findViewById(R.id.time_visit);
timer = new CountDownTimer(end, 1000){
#Override
public void onTick(long millisUntilFinished) {
long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000;
long diff = millisUntilFinished - now;
long diffSec = diff / 1000;
long days = diffSec / SECONDS_IN_A_DAY;
long secondsDay = diffSec % SECONDS_IN_A_DAY;
long seconds = secondsDay % 60;
long minutes = (secondsDay / 60) % 60;
long hours = (secondsDay / 3600);
countdown.setText(days+ " days, "+ hours + "hours, "+minutes + "m, "+seconds + "s remaining!");
}
#Override
public void onFinish() {
countdown.setText("done!");
vibrate.vibrate(pattern,-1);
}
}.start();
}
#Override
public void returnDate(String date) {
dateString = date;
TextView label = (TextView) findViewById(R.id.label);
label.setText(R.string.label);
BufferedWriter bw;
try {
bw = new BufferedWriter(new FileWriter(new File(filePath)));
bw.write(dateString);
bw.close();
System.out.println("Saved the file, date is: "+ dateString);
Date finishDate = formatter.parse(date);
setCountdown(finishDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I think problem in this string long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000; you need put it outside of countdowntimer code.
final long now = Calendar.getInstance(Locale.GERMANY).getTimeInMillis()+1000;
timer = new CountDownTimer(end, 1000){
#Override
public void onTick(long millisUntilFinished) {
long diff = millisUntilFinished - now;
long diffSec = diff / 1000;
...
};
I added to MainActvitiy.java
private Button startButton;
private Button pauseButton;
private TextView timerValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
Then in the onCreate i added:
And did that the timer will start automatic when i run the program without the need to click the start button i want the timer to start right when i run my program.
customHandler.postDelayed(updateTimerThread,0);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
Then the method updateTimerThread:
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = 0L;//SystemClock.uptimeMillis() - startTime;
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
In this method i did:
timeInMilliseconds = 0L;
But it didn't change much.
what i want to do is each time i run my program from the beginning the timer will start from 00:00:00
EDIT
In the on activity i did now this:
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread,0);
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
});
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
});
In the upadteTimerThread i didn't change:
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = System.currentTimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs) + ":"
+ String.format("%03d", milliseconds));
customHandler.postDelayed(this, 0);
}
};
Still when running the program the timer is not starting from 00:00:00 but i see on the minutes a long number also in second like it's continuing not starting over like reseted.
In the startButton onClick method, you have:
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
But at the top, you only have:
customHandler.postDelayed(updateTimerThread,0);
Since updateTimerThread uses the startTime value, you'd very likely want to initialize it the same way at the top.
The key to resetting the timer back to zero is in the updatedTime variable. This is what determines where the timer starts when you press the Start button.
There's no need to reinitialize the startTime variable since startTime = SystemClock.uptimeMillis(); already properly sets the startTime back to 0. Remember that startTime is relative to what's currently showing on the timer. That's why the timer starts off where you paused it and doesn't skip the seconds for when the timer was paused.
Set the timeSwapBuff back to 0L in the onClick event for the Start Button. This resets the time buffer to 0. That then gets added back to the startTime (also 0) and forces the timer to start over completely.
Try:
public void onClick(View view) {
timeSwapBuff = 0L;
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}