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;
}
Related
Hi I am new in android studio and i made a chronometer with a couple of other functions in my app but i have a problem when I change the fragment or screen rotates everything is good except my chronometer is set back to 00:00:00. Can someone help me please and show me how can I keep my chronometer running when those changes are made or even let it run when app is closed...
here is my code:
public class HomeFragment extends Fragment {
private Chronometer chronometer;
private Button buttonStart, buttonMinus;
private TextView mTVCount, gTVCount, lTVCount;
private int mCount;
private Double gCount=0.00, lCount=0.00;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
chronometer = v.findViewById(R.id.simpleChronometer);
gTVCount = v.findViewById(R.id.textView67);
mTVCount = v.findViewById(R.id.textView62);
lTVCount = v.findViewById(R.id.textView69);
buttonStart = (Button) v.findViewById(R.id.button);
buttonMinus = (Button) v.findViewById(R.id.button2);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
if (mCount > 20) {
Toast.makeText(buttonStart.getContext(), "Du wirst zu einem Schornstein!",
Toast.LENGTH_SHORT).show();
} else if (mCount >= 15) {
Toast.makeText(buttonStart.getContext(), "Du willst doch aufhören...oder?",
Toast.LENGTH_SHORT).show();
} else if (mCount >= 10) {
Toast.makeText(buttonStart.getContext(), "Ok Großer, mach eine Pause!",
Toast.LENGTH_SHORT).show();
} else if (mCount >= 5) {
Toast.makeText(buttonStart.getContext(), "Ganz Langsam!",
Toast.LENGTH_SHORT).show();
} else if (mCount > 0) {
Toast.makeText(buttonStart.getContext(), "Nicht so schlimm...",
Toast.LENGTH_SHORT).show();
}
}
private void increment() {
mCount++;
mTVCount.setText(String.valueOf(mCount));
lCount += 5;
lTVCount.setText(String.valueOf(String.format("%.0f", lCount) + " min"));
if (lCount >= 60) {
lTVCount.setText(String.valueOf(String.format("%.2f", lCount / 60)) + " h");
}
gCount += 0.36;
gTVCount.setText(String.valueOf(String.format("%.2f", gCount) + "€"));
}
});
Chronometer timeElapsed = (Chronometer) v.findViewById(R.id.simpleChronometer);
timeElapsed.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer cArg) {
long time = SystemClock.elapsedRealtime() - cArg.getBase();
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
cArg.setText(hh + ":" + mm + ":" + ss);
}
});
buttonMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrement();
}
private void decrement() {
mCount--;
mTVCount.setText(String.valueOf(mCount));
lCount -= 5;
lTVCount.setText(String.valueOf(String.format("%.0f", lCount) + " min"));
if (lCount >= 60) {
lTVCount.setText(String.valueOf(String.format("%.2f", lCount / 60)) + " h");
}
gCount -= 0.36;
gTVCount.setText(String.valueOf(String.format("%.2f", gCount) + "€"));
}
});
if (savedInstanceState != null){
mCount = savedInstanceState.getInt("count");
mTVCount.setText(String.valueOf(mCount));
gCount = savedInstanceState.getDouble("geld");
gTVCount.setText(String.valueOf( gCount) + "€");
lCount = savedInstanceState.getDouble("leben");
lTVCount.setText(String.valueOf(String.format("%.0f", lCount) + " min"));
if (lCount >= 60) {
lTVCount.setText(String.valueOf(String.format("%.2f", lCount / 60)) + " h");
}
}
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", mCount);
outState.putDouble("geld", gCount);
outState.putDouble("leben", lCount);
super.onSaveInstanceState(outState);
}
}
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();
}
}
// 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);
}
I making a timer in my android app. I have a scenario where I dont need to stop the timer even if the app is closed. If the timer is running and user closes the app and reopen it after sometime. He should see the latest time on the timer. But currently I am not able to show the latest time. I am only able to show the time when the user killed the app. I am storing the time of the timer and when the user open the app I am putting the stored time back to the timer. But I want to show the latest time. Here what I have done till now. I am using chronometer widget.
MainActivity.class:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
Chronometer tvTextView;
Button btnStart, btnStop;
private int state = 0; //0 means stop state,1 means play, 2 means pause
SharedPreferences sharedPreferences;
private boolean running = false;
private long pauseOffSet = -1;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.textview);
progressBar = findViewById(R.id.puzzleProgressBar);
btnStart = findViewById(R.id.button1);
btnStop = findViewById(R.id.button2);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
state = sharedPreferences.getInt("state", 0);
tvTextView.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
#Override
public void onChronometerTick(Chronometer chronometer) {
long time = SystemClock.elapsedRealtime() - chronometer.getBase();
pauseOffSet=time;
Log.e(TAG,"pauseOffSet "+pauseOffSet);
if (time >= 79200000) {
tvTextView.setBase(SystemClock.elapsedRealtime());
tvTextView.stop();
running = false;
progressBar.setProgress(0);
} else {
chronometer.setText(setFormat(time));
int convertTime = (int) time;
progressBar.setProgress(convertTime);
}
}
});
if (state == 1) { // its in play mode
running = true;
tvTextView.setBase(SystemClock.elapsedRealtime() - sharedPreferences.getLong("milli", 0));
tvTextView.start();
} else if (state == 2) { //its in pause mode
running = false;
pauseOffSet = sharedPreferences.getLong("milli", -1);
long time = SystemClock.elapsedRealtime() - pauseOffSet;
tvTextView.setBase(time);
int convertTime = (int) pauseOffSet;
progressBar.setProgress(convertTime);
} else {
running = false;
tvTextView.setBase(SystemClock.elapsedRealtime());
}
}
public void onClick(View v) {
if (btnStart == v) {
if (!running) {
if (pauseOffSet != -1) {
pauseOffSet = sharedPreferences.getLong("milli", -1);
}
tvTextView.setBase(SystemClock.elapsedRealtime() - pauseOffSet);
tvTextView.start();
state = 1;
pauseOffSet = 0;
running = true;
}
} else if (btnStop == v) {
if (running) {
tvTextView.stop();
pauseOffSet = SystemClock.elapsedRealtime() - tvTextView.getBase();
state = 2;
running = false;
}
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putLong("milli", pauseOffSet).commit();
sharedPreferences.edit().putInt("state", state).commit();
}
#Override
protected void onDestroy() {
Log.e(TAG, "onDestroy called, state: " + state);
super.onDestroy();
}
String setFormat(long time) {
int h = (int) (time / 3600000);
int m = (int) (time - h * 3600000) / 60000;
int s = (int) (time - h * 3600000 - m * 60000) / 1000;
String hh = h < 10 ? "0" + h : h + "";
String mm = m < 10 ? "0" + m : m + "";
String ss = s < 10 ? "0" + s : s + "";
return hh + ":" + mm + ":" + ss;
}
}
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");
}
}
};
}
);
}
}