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();
}
}
Related
// 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);
}
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");
}
}
};
}
);
}
}
In android studio in the MainActivity in the onCreate i did:
timerValueRecord = (TextView) findViewById(R.id.timerValueRecord);
In strings.xml i added:
<string name="timerValRecord">Recording Time: 00:00:00</string>
In activity_main.xml i added:
<TextView
android:id="#+id/timerValueRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20sp"
android:textColor="#000000"
android:layout_marginTop="315dp"
android:text="#string/timerValRecord" />
In the activity_main designer it looks like:
In the MainActivity i have a touch event:
#Override
public boolean onTouchEvent(MotionEvent event)
{
float eventX = event.getX();
float eventY = event.getY();
float lastdownx = 0;
float lastdowny = 0;
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
lastdownx = eventX;
lastdowny = eventY;
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
byte[] response = null;
if (connectedtoipsuccess == true)
{
if (is_start == true)
{
response = Get(iptouse + "start");
is_start = false;
} else
{
textforthespeacch = "Recording stopped and preparing the file to be shared on youtube";
MainActivity.this.initTTS();
response = Get(iptouse + "stop");
is_start = true;
startuploadstatusthread = true;
servercheckCounter = 0;
}
if (response != null)
{
try
{
a = new String(response, "UTF-8");
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (a.equals("Recording started"))
{
status1.setText("Recording");
}
if (a.equals("Recording stopped and preparing the file to be shared on youtube"))
{
status1.setText("Recording Stopped");
}
}
});
textforthespeacch = a;
MainActivity.this.initTTS();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
Logger.getLogger("MainActivity(inside thread)").info(a);
}
}
}
});
t.start();
return true;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
return true;
}
What i want to do is when in the touch event it's true after this line:
if (is_start == true)
Start the timer and display on the timerValueRecord the time running including milliseconds seconds and minutes until the user touch again and then it's getting to the stop part and then to stop the timer.
The problem is how to build the timer at all and how to stop and start it.
You can try this below Code:
public class ShowTimer {
private long startTime = 0L;
private Handler customHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
public void StartTimer() {
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
}
public void StopTimer() {
timeSwapBuff += timeInMilliseconds;
customHandler.removeCallbacks(updateTimerThread);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeSwapBuff + timeInMilliseconds;
int secs = (int) (timeInMilliseconds / 1000);
int mins = secs / 60;
secs = secs % 60;
int hours = mins / 60;
mins = mins % 60;
//int milliseconds = (int) (updatedTime % 1000);
//+ ":" + String.format("%03d", milliseconds)
String timer = "" + String.format("%02d", hours) + ":" + String.format("%02d", mins) + ":" + String.format("%02d", secs);
//set yout textview to the String timer here
customHandler.postDelayed(this, 1000);
}
};
You can use StartTimer() and StopTimer() function where you want to start or stop the timer:
try this way
public class AndroidTimerTaskExample extends Activity {
Timer timer;
TimerTask timerTask;
//we are going to use a handler to be able to run in our TimerTask
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
//onResume we start our timer so it can start when the app comes from the background
startTimer();
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 5000, 10000); //
}
public void stoptimertask(View v) {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
//show the toast
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
}
}
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;
}
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..