TextView stops updating after a while using hourglass tick function - java

// 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);
}

Related

How to kill reverseTimer at this

Can you tell me how to kill this Timer, so after that i can create new timer again
public void reverseTimer(int seconds, final TextView tv)
{
new CountDownTimer(seconds * 1000 + 1000,1000)
{
public void onTick(long millisUntilFinished){
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
tv.setText(String.format("%02d",minutes)
+ ":" + String.format("%02d",seconds));
}
public void onFinish(){
tv.setText("Completed");
Intent myintent = new Intent(QuestionActivity.this,ResultActivity.class);
myintent.putExtra("total",String.valueOf(total));
myintent.putExtra("correct",String.valueOf(correct));
myintent.putExtra("incorrect",String.valueOf(wrong));
startActivity(myintent);
}
}.start();
how to create kill/cancel function at this
Welcome to SO community.
You can create a field for the CountDownTimer, and invoke .cancel() to get it over & renew it again by using your method reverseTimer().
and use a boolean to track whether the quiz question is ansewred by the user or not; When they answer it, then call restartTimer() to go to the next question
private CountDownTimer mTimer;
private boolean mIsAnswered = false;
public void reverseTimer(int seconds, final TextView tv)
{
if (mIsAnswered) {
mIsAnswered = false;
nextQuestion();
return;
}
mTimer = new CountDownTimer(seconds * 1000 + 1000,1000)
{
public void onTick(long millisUntilFinished){
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
tv.setText(String.format("%02d",minutes)
+ ":" + String.format("%02d",seconds));
}
public void onFinish(){
nextQuestion();
}
}.start();
}
public void restartTimer() {
if (mTimer != null)
mTimer.cancel();
mIsAnswered = true;
restartTimer(...);
}
public void nextQuestion() {
tv.setText("Completed");
Intent myintent = new Intent(QuestionActivity.this,ResultActivity.class);
myintent.putExtra("total",String.valueOf(total));
myintent.putExtra("correct",String.valueOf(correct));
myintent.putExtra("incorrect",String.valueOf(wrong));
startActivity(myintent);
}
private CountDownTimer timer;
timer = new CountDownTimer(seconds * 1000 + 1000,1000){
public void onTick(long millisUntilFinished){
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
tv.setText(String.format("%02d",minutes)
+ ":" + String.format("%02d",seconds));
}
public void onFinish(){
tv.setText("Completed");
Intent myintent = new Intent(QuestionActivity.this,ResultActivity.class);
myintent.putExtra("total",String.valueOf(total));
myintent.putExtra("correct",String.valueOf(correct));
myintent.putExtra("incorrect",String.valueOf(wrong));
startActivity(myintent);
}
};
timer.start();
private void cancelTimer(){
if(timer !=null){
timer.cancel();
}
}

Stopwatch repeating time one after another with pause between

this is my first time writing here. I am learning Android development and trying to make a stopwatch (countdown timer) app, which has 12 rounds and pause - example 10 sec between them. I wrote a code which works fine but I want to write it more "readable and nicely" so I would like to ask you for your help. As you can see, I don't want to write every time under public void run() in if-else if statement new roundtime number and setting text because it would take too much space. That is why I wrote it just for example(not 12 times) so you can see what I mean. Do you have any suggestions how to write it better for 12 rounds? Can I use a loop? If u have easier way for countdown round after round I would appreciate it. I am sorry for my english. Any comments are welcome. Enjoy coding.
This is my code:
public class Main3Activity extends AppCompatActivity {
Handler handler;
TextView textView;
ImageView imageView2;
ImageView imageView3;
Boolean checker=false;
long secondtime=1000;
long roundtime1= 10000;
long roundtime2=10000;
long pause= 31000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView=(TextView)findViewById(R.id.textView3);
imageView2=(ImageView)findViewById(R.id.imageView2);
imageView3=(ImageView)findViewById(R.id.imageView3);
imageView2.setOnClickListener(
new ImageView.OnClickListener(){
#Override
public void onClick(View v) {
handler = new Handler();
if (checker == false) {
handler.post(r);
checker = true;
}
imageView3.setOnClickListener(
new ImageView.OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(r);
}
}
);
}
final Runnable r= new Runnable() {
#Override
public void run() {
roundtime = roundtime - secondtime;
int seconds = (int) (roundtime / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (roundtime >= 0) {
textView.setText(String.format("%d:%02d", minutes, seconds));
handler.postDelayed(r, 1000);
} else if (pause > 0) {
pause = pause - secondtime;
int secondss = (int) (pause / 1000);
int minutess = secondss / 60;
secondss = secondss % 60;
textView.setText(String.format("%d:%02d", minutess, secondss));
handler.postDelayed(r, 1000);
} else if (roundtime2 > 0) {
roundtime2 = roundtime2 - secondtime;
int secondsss = (int) (roundtime2 / 1000);
int minutesss = secondsss / 60;
secondsss = secondsss % 60;
textView.setText(String.format("%d:%02d", minutesss, secondsss));
handler.postDelayed(r, 1000);
}else{
textView.setText("Over");
}
}
};
}
);
}
}

(Android)How to show time on my music player

The music can play normally but I can't show time of music on my music Player.How can I do?
In main class
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
}
}
private void UpdateseekChange(View v){
if(mMedia.isPlaying()){
SeekBar sb = (SeekBar)v;
mMedia.seekTo(sb.getProgress());
}
This one should work:
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
txtView.post(mUpdateTime);
}
}
private Runnable mUpdateTime = new Runnable() {
public void run() {
int currentDuration;
if (mMedia.isPlaying()) {
currentDuration = mp.getCurrentPosition();
updatePlayer(currentDuration);
txtView.postDelayed(this, 1000);
}else {
txtView.removeCallbacks(this);
}
}
};
private void updatePlayer(int currentDuration){
txtView.setText("" + milliSecondsToTimer((long) currentDuration));
}
/**
* Function to convert milliseconds time to Timer Format
* Hours:Minutes:Seconds
* */
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
You need of course to remove runnable when the track is finished.
Try this code coders :)
//Get duration
long totalDuration = mediaPlayerOBJ.getDuration();
//Get current time
long currentDuration = mediaPlayerOBJ.getCurrentPosition();
textViewCurrentTime.setText(milliSecondsToTimer(currentDuration));
textViewDuration.setText(milliSecondsToTimer(totalDuration));
//Here is function to convert milliseconds to timer
public String milliSecondsToTimer(long milliseconds) {
String finalTimerString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours > 0) {
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
It's the all code page of the application media player.How can I do?
In main class
private MediaPlayer mMedia;
private Handler handler = new Handler();
private SeekBar seekBar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mMedia != null){
mMedia.release();
}
final TextView txtView = (TextView)findViewById(R.id.textView1);
txtView.setText("Source : music.mp3");
/* Resource in R.
* mMedia = MediaPlayer.create(this, R.raw.music);
* mMedia.start();
*/
/*
* from DataSource
* mMedia = new MediaPlayer();
* mMedia.setDataSource("http://www.thaicreate.com/music/mymusic.mp3");
* mMedia.start();
*
*/
mMedia = MediaPlayer.create(this, R.raw.music);
seekBar = (SeekBar)findViewById(R.id.seekBar1);
seekBar.setMax(mMedia.getDuration());
seekBar.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
UpdateseekChange(v);
return false;
}
});
final Button btn1 = (Button) findViewById(R.id.button1); // Start
// Start
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mMedia.isPlaying()) {
txtView.setText("Playing : music.mp3....");
mMedia.pause();
} else {
txtView.setText("pause : music.mp3....");
mMedia.start();
}
}
});
}
private void UpdateseekChange(View v){
if(mMedia.isPlaying()){
SeekBar sb = (SeekBar)v;
mMedia.seekTo(sb.getProgress());
}
}
public void startPlayProgressUpdater() {
seekBar.setProgress(mMedia.getCurrentPosition());
if (mMedia.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mMedia != null && fromUser){
mMedia.seekTo(progress * 1000);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(mMedia != null){
mMedia.release();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Ok, if you want to show it with String, use this method.
It gets remaining length(duration) and return the String:
public String convertTime(long value) {
String audioTime;
int dur = (int) value;
int hrs = (dur / 3600000);
int mns = (dur / 60000) % 60000;
int scs = dur % 60000 / 1000;
if (hrs > 0) {
audioTime = String.format("%02d:%02d:%02d", hrs, mns, scs);
} else {
audioTime = String.format("%02d:%02d", mns, scs);
}
return audioTime;
}

What method do i call to start the countdown timer "AccurateCountDownTimer"

as seen in Sam's post on
here, I am unsure what method to use to start the countdown timer "AccurateCountDownTimer".
It will be called from a button (onClick) which is easily set up later.
And the Time remaining will be displayed on a text view.
Here is my code:
public abstract class AccurateCountDownTimer {
public AccurateCountDownTimer(long millisInFuture, long countDownInterval) {
long seconds = (millisInFuture / 1000);
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
// ************AccurateCountdownTimer***************
mTickCounter = 0;
// ************AccurateCountdownTimer***************
testTimer.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
/**
* Cancel the countdown.
*/
public final void cancel() {
mHandler.removeMessages(MSG);
}
/**
* Start the countdown.
*/
public synchronized final AccurateCountDownTimer start() {
if (mMillisInFuture <= 0) {
onFinish();
return this;
}
mNextTime = SystemClock.uptimeMillis();
mStopTimeInFuture = mNextTime + mMillisInFuture;
mNextTime += mCountdownInterval;
mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG), mNextTime);
return this;
}
/**
* Callback fired on regular interval.
*
* #param millisUntilFinished
* The amount of time until finished.
*/
public abstract void onTick(long millisUntilFinished);{
}
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
synchronized (AccurateCountDownTimer.this) {
final long millisLeft = mStopTimeInFuture - SystemClock.uptimeMillis();
if (millisLeft <= 0) {
onFinish();
} else {
onTick(millisLeft);
// Calculate next tick by adding the countdown interval from the original start time
// If user's onTick() took too long, skip the intervals that were already missed
long currentTime = SystemClock.uptimeMillis();
do {
mNextTime += mCountdownInterval;
} while (currentTime > mNextTime);
// Make sure this interval doesn't exceed the stop time
if(mNextTime < mStopTimeInFuture)
sendMessageAtTime(obtainMessage(MSG), mNextTime);
else
sendMessageAtTime(obtainMessage(MSG), mStopTimeInFuture);
}
}
}
};
}
I am not sure if i understand your question... Do you ask how to use this class? I think it will be enough to start timer like this:
new AccurateCountDownTimer(millisInFuture, countDownInterval).start();
Edit: And also you can have callbacks like explained in source code:
new AccurateCountDownTimer(millisInFuture, countDownInterval) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Android: Count Down Timer e.g. 10:00 to 00:00? using OnclickListener to TextView?

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..

Categories

Resources