How to set the value of TextView in application? - android

Hi i want make a timer counter and i want the timer still counting and pause or stop when i click a button but now i can run the timer in app but i cannot set textView on fragment with the value of the timer
How can i set the text in text view ? so it will become a timer ?
here my code :
public class TimerFragment extends BaseFragment {
private ImageView btnPause, btnStop, iconCreditInfo, iconStockOpname, iconOrder, iconReturn;
private TextView timerValue, txtCreditInfo, txtStockOpname, txtOrder, txtReturn, namaClient, keterangan, dateValue;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private float textSizeBig, imgSizeBig, textSizeSmall, imgSizeSmall;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_timer, container, false);
initialize();
//start-time
/*
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);*/
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// App.appInstance.startTimer();
/*App app = ((App) getActivity().getApplicationContext());
app.afficher();
timerValue.setText(app.getTimer().toString());*/
}
});
//make default icon and text size
creditInfoDefault();
orderDefault();
stockOpnameDefault();
returnDefault();
//set today date
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
dateValue.setText(dateFormat.format(date).toString());
return rootView;
}
#Override
public void onPause() {
super.onPause();
// cancel();
}
#Override
public void onResume() {
super.onResume();
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
timerValue.setText("" + mins + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
}
Here the app code :
public class App extends Application {
public static App appInstance;
private SimpleDateFormat dateFormat;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private StringBuilder timer;
public StringBuilder getTimer() {
return timer;
}
public void setTimer(StringBuilder timer) {
this.timer = timer;
}
#Override
public void onCreate() {
super.onCreate();
appInstance = this;
dateFormat = new SimpleDateFormat("mm:ss");
}
public void afficher() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
timer.append("");
timer.append(mins);
timer.append(":");
timer.append(String.format("%02d", secs));
// Toast.makeText(getBaseContext(),mins).show();
/* timerValue.setText("" + mins + ":"
+ String.format("%02d", secs));*/
customHandler.postDelayed((Runnable) this, 0);
/*
handler.postDelayed(runnable,1000);*/
}
public void startTimer() {
runnable.run();
}
public void stopTimer() {
handler.removeCallbacks(runnable);
}
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
}
};
}

You could use runOnUiThread.
I am assuming timerValue is your textView.
Inside your Thread :
your_activity.runOnUiThread(new Runnable() {
public void run() {
timerValue.setText("" + mins + ":"+String.format("%02d",secs));
}
});
Or you could use Chronometer widget. Check out this tutorial.

Related

How to start new thread for chronometer in fragment

I'm making a chronometer app. And its obviously lagging on my older device but not so much on newer. So after research, I understood that I have to make a new thread and update UI thread from it. But no matter what I cant get rid of that lag.
Here is the chronometer fragment stripped down to important components. Any help would be appreciated. Thanks
public class ChronometerFragment extends Fragment {
private static final String TAG = "ChronometerFragment";
private Button btnRestart,btnStartStop;
private TextView time;
private int currentTime;
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private int running = 0;
private TimeConverter timeConverter;
CycleDataListener callback;
DecimalFormat df = new DecimalFormat("#.#####");
public ChronometerFragment(){}
public interface CycleDataListener{
void fragmentDataUpdate(Bundle bundle);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
callback = (CycleDataListener)getActivity();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_chronometer,container,false);
initWidgets(view);
view.setKeepScreenOn(true);
df.setRoundingMode(RoundingMode.CEILING);
timeConverter = new TimeConverter();
btnRestart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: button restart" );
resetTime();
}
});
btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: button startStop");
btnStartStop.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if(running == 0){
running = 1;
btnStartStop.setText(R.string.stop);
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}else{
running = 0;
btnStartStop.setText(R.string.start);
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
}
});
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
private Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
timeConverter.setUpTime(updatedTime);
time.setText(timeConverter.getTimeStringFormat());
customHandler.postDelayed(this, 0);
}
};
/**
* *********************helper methods**********************
*/
private void resetTime(){
running = 0;
btnStartStop.setText(R.string.start);
timeSwapBuff += timeInMilliseconds;
startTime = 0L;
timeInMilliseconds = 0L;
timeSwapBuff = 0L;
updatedTime = 0L;
customHandler.removeCallbacks(updateTimerThread);
time.setText("00:00:00:000");
}
private void initWidgets(View v){
btnRestart = v.findViewById(R.id.restart_button);
btnStartStop = v.findViewById(R.id.start_stop_button);
time = v.findViewById(R.id.currentTime);
}
}
This line cause lagging. You posted the runnable almost immediately on the mainthread.
customHandler.postDelayed(this, 0);
Change to
customHandler.postDelayed(this, 10);
The best solution is to only use the main handler to update UI. Time calculation and conversion should be handled by a background handler associated with a HandlerThread to avoid UI blocking.
private Handler mainHandler = new Handler(Looper.getMainLooper());
private HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
private Handler backgroundHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
handlerThread.start();
backgroundHandler = new Handler(handlerThread.getLooper());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
btnStartStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: button startStop");
btnStartStop.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
if (running == 0){
running = 1;
btnStartStop.setText(R.string.stop);
startTime = SystemClock.uptimeMillis();
backgroundHandler.post(updateTimerThread);
} else {
running = 0;
btnStartStop.setText(R.string.start);
timeSwapBuff += timeInMilliseconds;
backgroundHandler.removeCallbacks(updateTimerThread);
}
}
});
}
private Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
timeConverter.setUpTime(updatedTime);
final String timeWithFormat = timeConverter.getTimeStringFormat();
mainHandler.post(() -> time.setText(timeWithFormat);)
backgroundHandler.postDelayed(this, 10);
}
};
#Override
public void onDestroy() {
handlerThread.quitSafely();
super.onDestroy()
}

Android issue - Using handler while taking picture

I am trying to show the total image taking time(timer) to the user in my android application.
What I did:
I am starting the Handler when the fragment starts. (i.e) I have started the handler in my "onCreateView" method as like below.
MainFragment:
private long startTime = 0L;
private long timeInMillies = 0L;
private long timeSwap = 0L;
private long finalTime = 0L;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.capture,
container, false);
TextView textview = (TextView)rootView.findViewById(R.id.timer);
startTime = SystemClock.uptimeMillis();
Handler myHandler = new Handler();
Runnable updateTimer = new Runnable() {
public void run() {
timeInMillies = SystemClock.uptimeMillis() - startTime;
finalTime = timeSwap + timeInMillies;
int seconds = (int) (finalTime / 1000);
seconds = seconds % 60;
int milliseconds = (int) (finalTime % 1000);
milliseconds = milliseconds % 60 ;
textview.setText(String.format("%02d", seconds) + ":" + String.format("%02d", milliseconds) + "s");
myHandler.postDelayed(this, 0);
}
};
myHandler.postDelayed(updateTimer, 0);
.
.
.
return rootView;
}
What I want:
The handler is running well and timer runs without delaying like(00.00, 00.01, 00.02, 00.03, 00.04, ......, 10.32) until I start to call the "camera.takePicture(null, null, pictureCallback);". Once I call the "camera.takePicture" the timer shows the time with some sec delay(00.00, 00.01, 00.02, 00.03, delay, 02.30, 02.31, 02.32, delay, 04.03, 04.04, ......)
#Override
public void onResume() {
super.onResume();
.
.
.
camera.takePicture(null, null, pictureCallback);
}
What would be the problem? Did anyone face this issue? How do I fix this issue?

how to get value from countdowntimer and display into toast

i have countdown timer from 1 to 9999 if i click start button the count will start, but if click stop button i need to get current value from countdown and display that value in toast but the countdown could not stop if i click stop button please help me
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView ;
private final long startTime = 9999 * 1;
private final long interval = 1 *1 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1));
}
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!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
}
}
thank you
Here is my countdown timer:
QuestionCountdownTimer
public class QuestionCountdownTimer extends CountDownTimer {
private TextView remainingTimeDisplay;
private Context context;
public QuestionCountdownTimer(Context context,long millisInFuture, long countDownInterval,TextView remainingTimeDisplay) {
super(millisInFuture, countDownInterval);
this.context = context;
this.remainingTimeDisplay = remainingTimeDisplay;
}
#Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
String hms = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
remainingTimeDisplay.setText(hms);
}
#Override
public void onFinish() {
Toast.makeText(context,"COUNTDOWN FINISH :)",Toast.LENGTH_SHORT).show();
}
}
Note:
TextView remainingTimeDisplay
remainingTimeDisplay.setText(hms);
I use it to display the remaining time using a TextView
Here I call the timer:
//Start Quiz timer
QuestionCountdownTimer timer = new QuestionCountdownTimer(this,10000, 1000, remainingTimeDisplay);
timer.start();
-first parameter: this - I use it for context to show Toast message
-second parameter: 10000 - total time (10 sec)
-third parameter: 1000 - countdown interval (1 sec)
-last parameter: dispaly remaining time in real time
Tested and working
Create your CountDownTimer like this:
public class MyCountDownTimer extends CountDownTimer
{
private long timePassed = 0;
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
//text.setText("Time's up!");
countDownTimer.start();
}
#Override
public void onTick(long millisUntilFinished)
{
timePassed++;
text.setText("" + millisUntilFinished / 1);
}
public long getTimePassed()
{
return timePassed;
}
}
And on your onClick just do:
((MyCoundDownTimer) countDownTimer).getTimePassed();
to retrieve the time and set your textview text to it.
You should use handler
private Handler tickResponseHandler = new Handler() {
public void handleMessage(Message msg) {
int time = msg.what;
//make toast or do what you want
}
}
and pass it to MyCountDownTimer constructor
private Handler handler;
public MyCountDownTimer(long startTime, long interval, Handler handler) {
super(startTime, interval);
this.handler = handler;
}
And send message
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1);
Message msg = new Message();
msg.what = millisUntilFinished/1;
handler.sendMessage(msg);
}
That's all you need to do :)

CountDownTimer showing in 00:00:00 format

I have a count down timer that is meant to reading a time and stop at a particular time.
show use time and remaining time. I have codded a sample in my activity. But the function that is suppose to help me display in 00:00:00 format does not work well. It only displays it in that format when the timer as stoped.
public class PracticeQuestionActivity extends SherlockActivity implements OnClickListener {
private long timeElapsed;
private boolean timerHasStarted = false;
private final long startTime = 50000;
private final long interval = 1000;
MyCountDownTimer countdown = null;
TextView timerText = null, ElaspedTime = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.practicequestion);
context = PracticeQuestionActivity.this;
initializeComponents(context);
countdown = new MyCountDownTimer(startTime,interval);
this.controlTimer(); //This is going to start the timer
}
private void controlTimer(){
if (!timerHasStarted)
{
countdown.start();
timerHasStarted = true;
}
else
{
countdown.cancel();
timerHasStarted = false;
}
}
//This is going to format the time value from duration in second
private String setTimeFormatFromSeconds(long durationSeconds){
return String.format("%02d:%02d:%02d", durationSeconds / 3600, (durationSeconds % 3600) / 60, (durationSeconds % 60));
}
//This method is going to be used to initialize the components of the view
private void initializeComponents(Context context){
timerText = (TextView)findViewById(R.id.timer);
ElaspedTime = (TextView)findViewById(R.id.timeElapsed);
}
// CountDownTimer class
public class MyCountDownTimer extends CountDownTimer
{
public MyCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
timerText.setText("Time's up!");
ElaspedTime.setText("Time Elapsed: " + setTimeFormatFromSeconds(startTime));
}
#Override
public void onTick(long millisUntilFinished)
{
timerText.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
ElaspedTime.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
}
SimpleDateFormat is your friend:
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
#Override
public void onFinish() {
timerText.setText("Time's up!");
ElaspedTime.setText("Time Elapsed: " + timeFormat.format(startTime);
}
#Override
public void onTick(long millisUntilFinished) {
timerText.setText("Time remain:" + timeFormat.format(millisUntilFinished));
timeElapsed = startTime - millisUntilFinished;
ElaspedTime.setText("Time Elapsed: " + timeFormat.format(timeElapsed));
}

Countdown timer with pause and resume

I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)
{
public void onTick(long millisUntilFinished)
{
System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
}
public void onFinish()
{
System.out.println("Finished!");
}
}
in onTick method..save the milliseconds left
long s1=millisUntilFinished;
when you want to pause the timer use..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
timervalue=s1
counter= new Counter1();
counter.start();
See this link
I would add something to the onTick handler to save the progress of the timer in your class (number of milliseconds left).
In the onPause() method for the activity call cancel() on the timer.
In the onResume() method for the activity create a new timer with the saved number of milliseconds left.
Refer the below links
LINK
LINK
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean variable to control.
declare in your Activity:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
#Override
public void run() {
if (shouldTimerRun) //if false, it runs but skips counting
{
counterTv.setText(simplifyTimeInMillis(runningTime));
if (runningTime==0) {
deployToast("Task Completed"); //show toast on task completion
}
runningTime -= 1000;
presetTime = runningTime; //to resume the timer from last position
}
mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
}
};
mHandler.post(countDownRunnable); // Start our CountdownTimer
Now, whenever you want to pause the timer change the value of shouldTimerRun false and to resume make it true.
#Override
public void onResume() {
super.onResume();
shouldTimerRun=true;
}
#Override
public void onPause() {
super.onPause();
shouldTimerRun=false;
deployToast("Timer is paused !!");
}
Helping methods: (can be skipped)
public static String simplifyTimeInMillis(long time) {
String result="";
long difference = time;
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
if (difference<1000){
return "0";
}
if (difference>=3600000) {
result = result + String.valueOf(difference / hoursInMilli) + "hr ";
difference = difference % hoursInMilli;
}
if (difference>=60000) {
result = result + String.valueOf(difference / minutesInMilli) + "m ";
difference = difference % minutesInMilli;
}
if (difference>=1000){
result = result + String.valueOf(difference / secondsInMilli) + "s";
}
return result;
}
public void deployToast(String msg){
if (toastObj!=null)
toastObj.cancel();
toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
toastObj.show();
}
I'm using two private vars in this case:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
I am afraid that it is not possible to pause or stop CountDownTimer and pausing or stopping in onTick has no effect whatsoever user TimerTask instead.
Set up the TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}
You can add event listener's like this..
private Handler mHandler = new Handler();
...
OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
};
OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
};
For more refer to Android Documentation.
//This timer will show min:sec format and can be paused and resumed
public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.YourXmlLayout);
timer = (TextView)findViewById(R.id.Yourtimer)
startTimer(); // it will start the timer
}
public void startTimer(){
ct = new CountDownTimer(c,1000) {
#Override
public void onTick(long millisUntilFinished) {
// Code to show the timer in min:sec form
// Here timer is a TextView so
timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
c = millisUntilFinished; // it will store millisLeft
}
#Override
public void onFinish() {
//your code here
}
};
ct.start();
}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view);
textView.setText("Click to start");
textView.setOnClickListener(this::clickStartAndPauseAndResume);
leftTime = MILL_IN_FUTURE;
}
public void clickStartAndPauseAndResume(View view) {
if (!runCountDown) {
long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
ctimer = new CountDownTimer(time, 1) {
#Override
public void onTick(long l) {
leftTime = l;
textView.setText(l + "ms");
}
#Override
public void onFinish() {
textView.setText("Done");
leftTime = 0;
runCountDown = false;
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("Click to start");
}
}, 1000);
}
}.start();
runCountDown = true;
} else {
ctimer.cancel();
textView.setText(textView.getText() + "\n Click to resume");
runCountDown = false;
}
}
}
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
public void timerStart(long timeLengthMilli) {
timer = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft=milliTillFinish;
min = (milliTillFinish/(1000*60));
sec = ((milliTillFinish/1000)-min*60);
clock.setText(Long.toString(min)+":"+Long.toString(sec));
Log.i("Tick", "Tock");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
startPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(startPause.getText().equals("Start")){
Log.i("Started", startPause.getText().toString());
startPause.setText("Pause");
timerStart(15*1000);
} else if (startPause.getText().equals("Pause")){
Log.i("Paused", startPause.getText().toString());
startPause.setText("Resume");
timerPause();
} else if (startPause.getText().equals("Resume")){
startPause.setText("Pause");
timerResume();
}

Categories

Resources