android: do some code on media player special time - android

I'm newbie in android programming..
I have a media player in my activity to play a sound.
I want to do some code on a special time that the media player is playing. I mean I want to do code1 during media player is in 0 to 5sec, and do code2 during 5 to 14 and do code3 during 14 to 18sec.
here's my timer code and I don't know how to run my codes on special times..
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button1);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button1);
b.setText("start");
}
}

This isn't the most elegant solution, especially if all your time blocks will be exactly 5 seconds apart but if you set initalTime when the media player starts, it should work. Further documentation for uptimeMillis() and other Android timer methods are linked here
int initialTime= SystemTimer.uptimeMillis();
while (mediaIsRunning){
int currentTime=SystemTimer.uptimeMillis();
int elapsed=currentTime-initialTime;
if (elapsed<=5000){ // 5 seconds
//your code 1
}
else if (elapsed<=10000){ //10 seconds
//code 2
}
//etc ...
}

Related

How I can make chess-timer clock in android

I am a beginner in android, and I want to make a simple chess-timer clock. Here, I have taken two buttons. If I click on the first one the second button should start a countdown or vice-versa. But pause button is not working properly it pauses only one time second time it will not pause. Here I attached my code.
package com.example.jaydeep.practicework.chessClock;
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.TextView;
import com.example.jaydeep.practicework.R;
public class Main8Activity extends AppCompatActivity {
Button button11,button22;
CountDownTimer count,count1;
int s1=60,s2=60;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main8);
button11 = (Button) findViewById(R.id.Button11);
button22 = (Button) findViewById(R.id.Button22);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button11.setEnabled(false);
reverseTimer1(s2, button22);
}
});
button22.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button22.setEnabled(false);
reverseTimer(s1, button11);
}
});
}
public void reverseTimer(int Seconds,final Button button){
button11.setEnabled(true);
count= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s1=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count.start();
}
public void reverseTimer1(int Seconds,final Button button){
button22.setEnabled(true);
count1= new CountDownTimer(Seconds* 1000+1000, 1000) {
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
s2=seconds;
int minutes = seconds / 60;
seconds = seconds % 60;
button.setText( String.format("%02d", minutes)
+ ":" + String.format("%02d", seconds));
}
public void onFinish() {
button.setText("Time Up!!!");
}
};
count1.start();
}
}
cancel();
You need this code
if(isPaused || isCanceled)
{
//If the user request to cancel or paused the
//CountDownTimer we will cancel the current instance
cancel();
}
This link should help you understand:
https://android--examples.blogspot.com.au/2015/04/android-countdowntimer-start-pause.html

I am not able to stop the Android Timer

I am using following code to run a timer in my Android App.
I want to stop the Timer exactly when the time reaches to
1 Minute
2 Minute
3 Minute
and so on.
But I am not able to understand how to do it.
Any Help Will be appreciated.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView timerTextView;
long startTime = 0;
//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timerTextView.setText(String.format("%d:%02d", minutes, seconds));
timerHandler.postDelayed(this, 500);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTextView = (TextView) findViewById(R.id.text);
Button b = (Button) findViewById(R.id.button);
b.setText("start");
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button b = (Button) v;
if (b.getText().equals("stop")) {
timerHandler.removeCallbacks(timerRunnable);
b.setText("start");
} else {
startTime = System.currentTimeMillis();
timerHandler.postDelayed(timerRunnable, 0);
b.setText("stop");
}
}
});
}
#Override
public void onPause() {
super.onPause();
timerHandler.removeCallbacks(timerRunnable);
Button b = (Button)findViewById(R.id.button);
b.setText("start");
}
}
Why not use the CountDownTimer class?
You can simply instantiate it as:
int bigTime = 1000000000;
//1000 is ms after which the timer ticks (that is, the method gets called and so, you can update your view)
CountDownTimer countDownTimer = new CountDownTimer(bigTime, 1000) {
public void onTick(long millisUntilFinished) {
updateTime();
//you can write the code to update your view in this method
}
#Override
public void onFinish() {
Log.i("Get a life bro..."," 31 years have passed!");
}
};
Now, in your onCreate() method, according to the clicklisteners on your start/stop button, you can simply start or stop the timer:
countDownTimer.start();
if(seconds == 0 && minutes > 0) {
// get the values of seconds and minutes from the view.
countDownTimer.cancel();
}
Just in case you want to pause the timer and start from the paused time, you can store the value of the time in milliseconds, stop the timer and restart it after adding the value you stored.

How to display the timer in android

I want to display the timer in TextView in the format of like [ 19:59].so when i click the start button ,the timer will display like this for example,i want to set upto 20 mintues,it will display like [19:58][19:87].can anyone give some ideas or example code?
You can use the CountDownTimer.
http://developer.android.com/reference/android/os/CountDownTimer.html
TextView _tv = (TextView) findViewById( R.id.textView1 );
new CountDownTimer(20*60000, 1000) {
public void onTick(long millisUntilFinished) {
_tv.setText("seconds remaining: " +new SimpleDateFormat("mm:ss:SS").format(new Date( millisUntilFinished)));
}
public void onFinish() {
_tv.setText("done!");
}
}.start();
To cancel just call cancel on the timer.
public final void cancel()
Cancel the countdown.
package com.example.testproject;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
public int seconds = 60;
public int minutes = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.main_timer_text);
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds -= 1;
if(seconds == 0)
{
tv.setText(String.valueOf(minutes)+":"+String.valueOf(seconds));
seconds=60;
minutes=minutes-1;
}
}
});
}
}, 0, 1000);
}
}
//start button click
CountDown timer = new CountDown(180000, 1000);
timer.start();
//stop button click
timer.stop();
//countdown class
public class CountDown extends CountDownTimer {
public CountDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
long ms = millisUntilFinished;
String text = String.format("%02d\' %02d\"",
TimeUnit.MILLISECONDS.toMinutes(ms) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(ms)),
TimeUnit.MILLISECONDS.toSeconds(ms) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(ms)));
textViewTimer.setText(text);
}
#Override
public void onFinish() {
textViewTimer.setText("ffinish");
}
}
do it this way activity_timer.xml
<android.support.v7.widget.LinearLayoutCompat
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Chronometer
android:id="#+id/chronometer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.LinearLayoutCompat>
And in Activity
public class TimerActivity extends AppCompatActivity {
private Chronometer chronometer2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
chronometer2 = findViewById(R.id.chronometer2);
chronometer2.start();
}
}
You can also use stop
chronometer2.stop();
Re Start
chronometer2.setBase(SystemClock.elapsedRealtime());
chronometer2.start();
Here I have use Timer class to display timer
public class FourthActivity extends AppCompatActivity {
Button startButton, pauseButton;
TextView timerValue;
Timer timer;
int seconds = 0, minutes = 0, hour = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
bindView();
timer = new Timer();
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (seconds == 60) {
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
minutes = seconds / 60;
seconds = seconds % 60;
hour = minutes / 60;
}
seconds += 1;
timerValue.setText(String.format("%02d", hour) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds));
}
});
}
}, 0, 1000);
}
});
}
private void bindView() {
timerValue = (TextView) findViewById(R.id.timerValue);
startButton = (Button) findViewById(R.id.startButton);
}
}
In layout, there are one TextView and one Button to start timer. I have use Timer class method scheduleAtFixedRate. Time will be displayed in hh:mm:ss form.
This can be done using cronometer, the most main reason is supporting API 1+, which is quite impressive rather than TextClock, which supports API 17+.
You can do lots of other things with cronometer. for example you can set start time in it
chronometer.setBase(SystemClock.elapsedRealtime());
You can also learn about it more here.
I made code for timer display in textView.The formate is for e.g:- 02:59:00
You can follow this link to get the Step By Step Code.
https://stackoverflow.com/a/58316149/11613683

How to use Lap Button using timer program in android(lap button code for timmer application in android)

I have one button start and three editText. If I press the start button then timer starts and the button text changes to Lap and hour minutes and seconds are displayed in edittext1. If I press Lap button then editText1's values are stop. All three values of editText1 are displayed in editText2 at stop position of editText1.
Please help me for Lap button source code. I have the following code so far:
package com.example.timmerproject;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class LapActivity extends Activity
{
EditText ed1,ed2,ed3;
Button btntimer;
final Handler handler = new Handler();
long startTime=0;
Handler h2 = new Handler();
Runnable run = new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - startTime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
ed1.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
h2.postDelayed(this, 500);
}
};
class firstTask extends TimerTask
{
#Override
public void run()
{
handler.sendEmptyMessage(0);
}
};
class secondTask extends TimerTask
{
#Override
public void run()
{
// TODO Auto-generated method stub
LapActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - startTime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
ed2.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
class thirdTask extends TimerTask
{
#Override
public void run()
{
// TODO Auto-generated method stub
LapActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
long millis = System.currentTimeMillis() - startTime;
int seconds = (int)(millis/1000);
int hours =seconds/3600;
int minutes = (seconds % 3600)/60;
seconds = seconds % 60;
ed3.setText(String.format("%02d:%02d:%02d", hours,minutes,seconds));
}
});
}
}
Timer timer = new Timer();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.lap);
ed1 = (EditText)findViewById(R.id.ed11);
ed2 = (EditText)findViewById(R.id.ed12);
ed3 = (EditText)findViewById(R.id.ed13);
btntimer = (Button)findViewById(R.id.lapbutton);
btntimer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button btn = (Button)v;
if(btn.getText().equals("Stop"))
{
timer.cancel();
timer.purge();
h2.removeCallbacks(run);
btn.setText("Start");
}
else
{
startTime = System.currentTimeMillis();
timer = new Timer();
timer.schedule(new firstTask(), 0,500);
timer.schedule(new secondTask(), 0,500);
timer.schedule(new thirdTask(), 0,500);
h2.postDelayed(run, 0);
btn.setText("Stop");
}
}
});
}
}

android timer problem

I have question. is this code timer correct;]? or i can do it more easily
package timer2.android;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Timer2Activity extends Activity {
private TextView tv;
private Timer myTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.textView1);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
long mStartTime = System.currentTimeMillis();
private Runnable Timer_Tick = new Runnable() {
public void run() {
final long start = mStartTime;
long millis = System.currentTimeMillis() - start;
int seconds = (int) (millis / 1000);
int minutes = (int) (seconds / 60);
seconds = seconds % 60;
if (seconds < 10)
{
tv.setText("" + minutes + ":0" + seconds);
}
else
{
tv.setText("" + minutes + ":" + seconds);
}
//a++;
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
Can't see anything wrong here. But you should use Handler for timers as it does not create additional threads. See example here: Repeat a task with a time delay?

Categories

Resources