If condition in repeated countdown - java

Hi I am making boxing countdowntimer. And I would like to set on text view "end" after all tasks. But I don't know how to do that. During the round I see that (pic1)
and during the break I see that (pic2)
And how make a condition to see "end" after all tasks because I am using handler function to repeat this for example 2 times and when I set condition " if (!tv1.getText().toString().equals("Przerwa"){ tv3.setText("end")
but "end" shows me every single break.
Btw. runda means rund and this is= tv1 1/2= tv2 2-3-2=tv3 00:03=tv4
tv means -textview
Przerwa means break
timerododliczania = new CountDownTimer(1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
btn1.setVisibility(View.INVISIBLE);
tv2.setText("" + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
MediaPlayer boksring=MediaPlayer.create(Main3Activity.this,R.raw.rin9 );
boksring.start();
int liczbarund = 1;
tv4.setText(ilośćrund);
try {
liczbarund = Integer.parseInt(tv4.getText().toString());
} catch (Exception ex) {
Toast.makeText(cntx, "Invalid Integer", Toast.LENGTH_LONG).show();
return;
}
if (liczbarund == 0) {
return;
}
final int[] round_count = {0};
final int finalNum_rounds = liczbarund;
final int[] round_count1 = {0};
final int finalNum_rounds1 = liczbarund;
final int[] round_count2 = {0};
final int finalNum_roundsp = liczbarund;
timerodrundy = new CountDownTimer(dłrundy, 1000) {
#Override
public void onTick(long millisUntilFinished) {
btn1.setVisibility(View.VISIBLE);
tv1.setText("Runda");
tv5.setText( (round_count1[0] + 1) + "/" + finalNum_rounds1);
mTimeLeftInMillis = millisUntilFinished;
updatetext();
}
#Override
public void onFinish() {
tv1.setText("Przerwa");
MediaPlayer r1=MediaPlayer.create(Main3Activity.this, R.raw.rinknkw);
r1.start();
if (licz > 1) {
round_count[0]++;
if (round_count[0] < finalNum_rounds) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
start();
}
}, dłprzerwy);
}
}
if (!tv2.getText().toString().equals("00:00")){
tv3.setText("Koniec");
}
}
}.
start();
timerodkombosa = new CountDownTimer(dłrundy, 5000) {
#Override
public void onTick(long millisUntilFinished) {
final Random rand = ThreadLocalRandom.current();
tv3.setText(kombosy[new Random().nextInt(kombosy.length)]);
int resourceID = R.raw.rin1;
switch (tv3.getText().toString()) {
case "1-2":
resourceID = R.raw.rin1;
break;
case "1-1-2":
resourceID = R.raw.rin2;
break;
case "1-2-3-2":
resourceID = R.raw.rin3;
break;
case "1-2-5-2":
resourceID = R.raw.rin4;
break;
case "1-6-3-2":
resourceID = R.raw.rin5;
break;
case "2-3-2":
resourceID = R.raw.rin6;
break;
}
player = MediaPlayer.create(Main3Activity.this, resourceID);
player.start();
}
#Override
public void onFinish() {
tv5.setText("");
tv3.setText("");
if (licz > 1) {
round_count1[0]++;
if (round_count1[0] < finalNum_rounds1) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
start();
}
}, dłprzerwy);
timerodprzerwy = new CountDownTimer(dłprzerwy, 1000) {
#Override
public void onTick(long millisUntilFinished) {
mTimeLeftInMillis = millisUntilFinished;
updatetext();
}
#Override
public void onFinish() {
MediaPlayer r2=MediaPlayer.create(Main3Activity.this, R.raw.rinnkr);
r2.start();
CountDownTimer countDownTimer= new CountDownTimer(1000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}.start();

Related

Music plays only one time from server in online music player

I designed an online music player which streams file from my server and shows them in a recyclerView. when I click on the specific song it plays automatically, but when I go back to my recyclerview and I choose it again it doesn't play anymore and even duration of song becomes an insane number. I even tried to handle my media player onBackPressed() method or in OnRestart() or onResume() method. I'm confused. Please let me know about any suggestion.
Here's my code for player:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener {
private CircularMusicProgressBar cover;
private ImageButton playPause, rewind, forward, repeat, fav, download;
private TextView title, term, spendingTime, totalTime, emptyRec;
private Context context;
public static MediaPlayer mediaPlayer;
int i;
private Timer timer;
private Bundle extra;
Uri uri;
RecyclerView recyclerView;
RequestQueue requestQueue;
SuggestionAdapter suggestionAdapter;
LinearLayoutManager layoutManager;
List<Listening> list = new ArrayList<>();
String url = "https://www.learnhere.ir/listening.php";
AccessDataOnServer suggestionData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initFields();
playOnStart();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
if (i == 1) {
i = 2;
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.pause();
} else {
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
int b = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(b);
mediaPlayer.start();
}
break;
case R.id.rewind:
Toast.makeText(context, "rewind", Toast.LENGTH_SHORT).show();
break;
case R.id.forward:
Toast.makeText(context, "forward", Toast.LENGTH_SHORT).show();
break;
case R.id.repeat:
Toast.makeText(context, "repeat", Toast.LENGTH_SHORT).show();
break;
case R.id.fav:
Toast.makeText(context, "fav", Toast.LENGTH_SHORT).show();
break;
case R.id.download:
Toast.makeText(context, "download", Toast.LENGTH_SHORT).show();
break;
}
}
public void initFields() {
i = 0;
context = this;
cover = findViewById(R.id.cover_progress);
playPause = findViewById(R.id.play_pause);
rewind = findViewById(R.id.rewind);
forward = findViewById(R.id.forward);
repeat = findViewById(R.id.repeat);
fav = findViewById(R.id.fav);
download = findViewById(R.id.download);
title = findViewById(R.id.title_tv);
term = findViewById(R.id.term_tv);
emptyRec = findViewById(R.id.empty_rec);
spendingTime = findViewById(R.id.spending_time);
totalTime = findViewById(R.id.total_time);
playPause.setOnClickListener(this);
rewind.setOnClickListener(this);
forward.setOnClickListener(this);
repeat.setOnClickListener(this);
fav.setOnClickListener(this);
download.setOnClickListener(this);
extra = getIntent().getExtras();
Picasso.get().load(extra.getString("cover")).into(cover);
title.setText(extra.getString("title"));
term.setText(extra.getString("term"));
timer = new Timer();
uri = Uri.parse(extra.getString("link"));
recyclerView = findViewById(R.id.suggestion_recycler);
requestQueue = Volley.newRequestQueue(context);
layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
suggestionAdapter = new SuggestionAdapter(list, context);
suggestionData = new AccessDataOnServer();
recyclerView.setAdapter(suggestionAdapter);
recyclerView.setLayoutManager(layoutManager);
suggestionData.getSuggestion(context, list, recyclerView, url, requestQueue);
if (list.size() <= 1) {
emptyRec.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
emptyRec.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void play() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes
.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getTime();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
thread.start();
}
public void playOnStart() {
Toast.makeText(context, "Please wait until the audio plays...", Toast.LENGTH_SHORT).show();
play();
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
}
public String millisecondToSecond(long millisecond) {
String finalTimerString = "";
String secondString = "";
String minuteString = "";
//convert total duration into time
int hour = (int) (millisecond / (1000 * 60 * 60));
int minute = (int) (millisecond % (1000 * 60 * 60) / (1000 * 60));
int second = (int) (millisecond % (1000 * 60 * 60) % (1000 * 60) / 1000);
//Add hours if there
if (hour > 0) {
finalTimerString = hour + ":";
}
//Prepending 0 to second if it's one digit
if (second < 10) {
secondString = "0" + second;
} else {
secondString = "" + second;
}
//Prepending 0 to minute if it's one digit
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = "" + minute;
}
finalTimerString = finalTimerString + minuteString + ":" + secondString;
//Return timer string
return finalTimerString;
}
public void getTime() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Without runOnUiThread we don't have access to modifiers like text view
runOnUiThread(new Runnable() {
#Override
public void run() {
long current = mediaPlayer.getCurrentPosition();
int i = (mediaPlayer.getCurrentPosition() * 100) / mediaPlayer.getDuration();
spendingTime.setText("" + millisecondToSecond(current));
cover.setValue(i);
int duration = mediaPlayer.getDuration();
String time = String.format(Locale.US, "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
totalTime.setText(time);
}
});
}
}, 0, 1000);
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
#Override
protected void onRestart() {
super.onRestart();
playOnStart();
}
Well I reviewed your codes and it seems you aren't using Media player class properly.
I made a few changes to each block of your codes. I hope it solves your problem.
First of all change the following scope:
public static MediaPlayer mediaPlayer;
To
MediaPlayer mediaPlayer = new MediaPlayer();
I made a method for your mediaPlayer and you should use it in your onCreate() :
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
updateSeekBarTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
A method to update your seekbar :
private void updateSeekBarTimer() {
try {
if (mediaPlayer.isPlaying()) {
total_time = mediaPlayer.getDuration();
current_time = mediaPlayer.getCurrentPosition();
totalTime.setText("" + utils.milliSecondsToTimer(total_time));
spendingTime.setText("" + utils.milliSecondsToTimer(current_time));
int progress = (int) (utils.getProgressPercentage(current_time, total_time));
seekBar.setProgress(progress);
Runnable runnable = new Runnable() {
#Override
public void run() {
updateSeekBarTimer();
}
};
handler.postDelayed(runnable, 1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
And finally you need an Interface to decide what happens when your track ends:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener
#Override
public void onCompletion(MediaPlayer mp) {
handler.removeCallbacks(null);
playPause.setImageResource(R.drawable.ic_baseline_play);
if (rep) {
mediaPlayer.start();
playPause.setImageResource(R.drawable.ic_baseline_pause);
updateSeekBarTimer();
} else {
seekBar.setProgress(0);
totalTime.setText(R.string.zero_time);
spendingTime.setText(R.string.zero_time);
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.reset();
prepareMediaPlayer();
}
}

CountDownTimer adds time with each loop

I'm working on a fragment that includes two timers that take user input. Timer B is linked to timer A such that when timer A is started, so is timer B. The purpose of timer A is to count down once. The purpose of timer B is to count down, beep once at 0, reset to the original value, and repeat. The problem I'm having is that when timer B reaches 0, it doesn't reset and start counting down right away. The timer seems to be delayed further by calling ToneGenerator. This results in the two timers becoming more and more out of sync each time timer B resets.
For example, say timer A is set to 10 seconds and timer B is set to 2 seconds.
-The timers are started-
timer A:10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
timer B: 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1
The timer only beeps 3 times (when timer B is at 0,) when it should beep 5 times (5 sets of 2 second intervals = 10 seconds: the value of timer A.) In other words, I'd like timer B to beep when timer A is at 8, 6, 4, 2, and 0.
How might I accomplish this?
I've consulted the forums, YT, and have tried playing around with the value for millisInFuture.
Fragment
public class fragmentdro extends Fragment {
private EditText session_edit_text;
private EditText dro_edit_text;
private TextView session_text_view;
private TextView dro_text_view;
private Button session_start_button;
private Button dro_start_button;
private Button session_reset_button;
private Button dro_reset_button;
private Button session_set_button;
private Button dro_set_button;
private CountDownTimer sessionTimer;
private CountDownTimer droTimer;
private boolean SessionTimerRunning;
private boolean DROTimerRunning;
private long SessionStartTimeInMillis;
private long DROStartTimeInMillis;
private long SessionTimeLeftInMillis = SessionStartTimeInMillis;
private long DROTimeLeftInMillis = DROStartTimeInMillis;
private long SessionEndTime;
private long DROEndTime;
View View;
public View onCreateView(#NonNull LayoutInflater inflater, #NonNull ViewGroup container, #NonNull Bundle savedInstanceState) {
View = inflater.inflate(R.layout.dro_fragment, container, false);
session_edit_text = View.findViewById(R.id.session_edit_text);
dro_edit_text = View.findViewById(R.id.dro_edit_text);
session_text_view = View.findViewById(R.id.session_text_view);
dro_text_view = View.findViewById(R.id.dro_text_view);
session_start_button = View.findViewById(R.id.session_start_button);
dro_start_button = View.findViewById(R.id.dro_start_button);
session_reset_button = View.findViewById(R.id.session_reset_button);
dro_reset_button = View.findViewById(R.id.dro_reset_button);
session_set_button = View.findViewById(R.id.session_set_button);
dro_set_button = View.findViewById(R.id.dro_set_button);
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
Timer A
session_set_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
String Sessioninput = session_edit_text.getText().toString();
if (Sessioninput.length() == 0) {
Toast.makeText(getActivity(), "Fill it in", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(Sessioninput) * 1000;
if (millisInput == 0) {
Toast.makeText(getActivity(), "Please enter a positive number", Toast.LENGTH_SHORT).show();
return;
}
setSessionTime(millisInput);
session_edit_text.setText("");
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
});
session_start_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (SessionTimerRunning) {
pauseSessionTimer();
resetDROTimer();
} else {
startSessionTimer();
startDROTimer();
}
}
});
session_reset_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (SessionTimerRunning) {
resetSessionTimer();
} else {
resetSessionTimer();
}
}
});
public void setSessionTime(long milliseconds) {
SessionStartTimeInMillis = milliseconds;
resetSessionTimer();
}
public void startSessionTimer() {
SessionEndTime = System.currentTimeMillis() + SessionTimeLeftInMillis;
sessionTimer = new CountDownTimer(SessionTimeLeftInMillis, 100) {
#Override
public void onTick(long millisUntilFinished) {
SessionTimeLeftInMillis = millisUntilFinished;
updateSessionText();
}
#Override
public void onFinish() {
SessionTimerRunning = false;
session_start_button.setText("Start");
session_start_button.setVisibility(android.view.View.INVISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
}
}.start();
SessionTimerRunning = true;
session_start_button.setText("Pause");
}
public void pauseSessionTimer() {
sessionTimer.cancel();
droTimer.cancel();
SessionTimerRunning = false;
DROTimerRunning = false;
session_start_button.setText("Start");
updateSessionText();
}
public void resetSessionTimer() {
if (SessionTimerRunning) {
sessionTimer.cancel();
SessionTimeLeftInMillis = (SessionStartTimeInMillis);
updateSessionInterface();
startSessionTimer();
} else {
SessionTimeLeftInMillis = (SessionStartTimeInMillis);
updateSessionText();
updateSessionInterface();
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setVisibility(android.view.View.VISIBLE);
}
}
public void updateSessionText() {
int minutes = (int) (SessionTimeLeftInMillis/1000/60);
int seconds = (int) (SessionTimeLeftInMillis/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),
timeLeftFormatted = String.format(Locale.getDefault(), "%2d:%02d", minutes, seconds));
session_text_view.setText(timeLeftFormatted);
}
public void updateSessionInterface() {
if (SessionTimerRunning) {
session_edit_text.setVisibility(android.view.View.INVISIBLE);
session_set_button.setVisibility(android.view.View.INVISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setText("Pause");
} else {
session_edit_text.setVisibility(android.view.View.VISIBLE);
session_set_button.setVisibility(android.view.View.VISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setText("Start");
}
}
Timer B
dro_set_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
String DROinput = dro_edit_text.getText().toString();
if (DROinput.length() == 0) {
Toast.makeText(getActivity(), "Fill it in", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(DROinput) * 1000;
if (millisInput == 0) {
Toast.makeText(getActivity(), "Please enter a positive number", Toast.LENGTH_SHORT).show();
return;
}
setDROTime(millisInput);
dro_edit_text.setText("");
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
});
dro_start_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (DROTimerRunning) {
pauseDROTimer();
} else {
startDROTimer();
}
}
});
dro_reset_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (DROTimerRunning) {
resetDROTimer();
} else {
resetDROTimer();
}
}
});
return View;
}
public void setDROTime(long milliseconds) {
DROStartTimeInMillis = milliseconds;
resetDROTimer();
}
public void startDROTimer() {
DROEndTime = System.currentTimeMillis() + DROTimeLeftInMillis;
droTimer = new CountDownTimer(DROTimeLeftInMillis, 100) {
#Override
public void onTick(long millisUntilFinished) {
DROTimeLeftInMillis = millisUntilFinished;
updateDROText();
}
#Override
public void onFinish() {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_ALARM, 400);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
DROTimerRunning = false;
DROTimeLeftInMillis = DROStartTimeInMillis;
updateDROText();
updateDROInterface();
startDROTimer();
}
}.start();
DROTimerRunning = true;
dro_start_button.setText("Pause");
}
public void pauseDROTimer() {
droTimer.cancel();
DROTimerRunning = false;
dro_start_button.setText("Start");
updateDROText();
}
public void resetDROTimer() {
if (DROTimerRunning) {
droTimer.cancel();
DROTimeLeftInMillis = (DROStartTimeInMillis);
updateDROInterface();
startDROTimer();
} else {
DROTimeLeftInMillis = (DROStartTimeInMillis);
updateDROText();
updateDROInterface();
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setVisibility(android.view.View.VISIBLE);
}
}
public void updateDROText() {
int seconds = (int) (DROTimeLeftInMillis/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),
timeLeftFormatted = String.format(Locale.getDefault(), ":%02d", seconds));
dro_text_view.setText(timeLeftFormatted);
}
public void updateDROInterface() {
if (DROTimerRunning) {
dro_edit_text.setVisibility(android.view.View.INVISIBLE);
dro_set_button.setVisibility(android.view.View.INVISIBLE);
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setText("Pause");
} else {
dro_edit_text.setVisibility(android.view.View.VISIBLE);
dro_set_button.setVisibility(android.view.View.VISIBLE);
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setText("Start");
}
}
#Override
public void onStop() {
super.onStop();
SharedPreferences preferences = this.getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("SessionStartTimeInMillis", SessionStartTimeInMillis);
editor.putLong("DROStartTimeInMillis", DROStartTimeInMillis);
editor.putLong("MillisLeft", SessionTimeLeftInMillis);
editor.putLong("DROMillisLeft", DROTimeLeftInMillis);
editor.putBoolean("TimerRunning", SessionTimerRunning);
editor.putBoolean("DROTimerRunning", DROTimerRunning);
editor.putLong("EndTime", SessionEndTime);
editor.putLong("DROEndTime", DROEndTime);
if (sessionTimer !=null); {
sessionTimer.cancel();
}
}
#Override
public void onStart() {
super.onStart();
SharedPreferences preferences = this.getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE);
SessionStartTimeInMillis = preferences.getLong("SessionStartTimeInMillis", 0);
SessionTimeLeftInMillis = preferences.getLong("MillisLeft", SessionTimeLeftInMillis);
SessionTimerRunning = preferences.getBoolean("TimerRunning", false);
DROStartTimeInMillis = preferences.getLong("DROStartTimeInMillis", 0);
DROTimeLeftInMillis = preferences.getLong("DROMillisLeft", DROTimeLeftInMillis);
DROTimerRunning = preferences.getBoolean("DROTimerRunning", false);
updateSessionText();
updateSessionInterface();
updateDROText();
updateDROInterface();
if (SessionTimerRunning) {
SessionEndTime = preferences.getLong("EndTime", 0);
SessionTimeLeftInMillis = SessionEndTime - System.currentTimeMillis();
if (SessionTimeLeftInMillis <0) {
SessionTimeLeftInMillis = 0;
SessionTimerRunning = false;
} else {
startSessionTimer();
}
}
if (DROTimerRunning) {
DROEndTime = preferences.getLong("EndTime", 0);
DROTimeLeftInMillis = DROEndTime - System.currentTimeMillis();
if (DROTimeLeftInMillis <0) {
DROTimeLeftInMillis = 0;
DROTimerRunning = false;
} else {
startDROTimer();
}
}
}
}

Count down timer how to implement onfinish method

I have a countdown timer that i want to implement on finish method or some kind of code so that when the timer stops, the text views change to Time's up and another method is initiated (in the activity).
To clarify, the timer is given a starting number that counts down from, to zero in format of xx:xx.
The class of the timer :
public class countdown_timer {
private long pls;
private long millisInFuture;
private long countDownInterval;
private boolean status;
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
this.millisInFuture = pMillisInFuture;
this.countDownInterval = pCountDownInterval;
this.pls = pMillisInFuture;
status = false;
Initialize();
}
public void Stop() {
status = false;
}
public void Reset() {
millisInFuture = pls;
}
public long getCurrentTime() {
return millisInFuture;
}
public void Start() {
status = true;
}
public void Initialize()
{
final Handler handler = new Handler();
Log.v("status", "starting");
final Runnable counter = new Runnable(){
public void run(){
long sec = millisInFuture/1000;
if(status) {
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain");
millisInFuture -= countDownInterval;
handler.postDelayed(this, countDownInterval);
}
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
handler.postDelayed(this, countDownInterval);
}
}
};
handler.postDelayed(counter, countDownInterval);
}
The activty that the timer is used:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_game_2);
//...find views
mycounterup = new countdown_timer(startcard, 1000);
mycounterdown = new countdown_timer(startcard, 1000);
RefreshTimer();
mycounterdown.Start();
public void RefreshTimer()
{
final Handler handler = new Handler();
final Runnable counter = new Runnable(){
public void run(){
int minutes_up_start = (int) (mycounterup.getCurrentTime() / 1000) / 60;
int seconds_up_start = (int) (mycounterup.getCurrentTime() / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
card_2_up.setText(time_2_up_start_formatted);
int minutes_down_start = (int) (mycounterdown.getCurrentTime() / 1000) / 60;
int seconds_down_start = (int) (mycounterdown.getCurrentTime() / 1000) % 60;
String card_2_down_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_down_start, seconds_down_start);
card_2_down.setText(card_2_down_start_formatted);
handler.postDelayed(this, 100);
}
};
handler.postDelayed(counter, 100);
}
You can use CountDownTimer:
new CountDownTimer(endsIn * 1000, 1000) {
public void onTick(long millisUntilFinished) {
timerTextView.setText(String.valueOf(millisUntilFinished/1000);
}
public void onFinish() {
}
}.start();
OR:
extend CountDownTimer class:
public class countdown_timer extends CountDownTimer {
TextView textView;
#Override
public void onTick(long millisInFuture) {
long sec = millisInFuture/1000;
if(millisInFuture <= 0) {
Log.v("status", "done");
} else {
Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
}
}
#Override
public void onFinish() {
if(textView != null){
// change text in your textview
}
}
public countdown_timer(long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
}
public countdown_timer(TextView textView, long pMillisInFuture, long pCountDownInterval) {
super(pMillisInFuture, pCountDownInterval);
this.textView = textView;
}
}
here is a two constructors, one of them is the same as is in your example and in second one you can pass also TextView object and use it in onFinish() method.
UPDATE 2:
Here is CountDownTimer in the Activity:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 1000) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
UPDATE 3: if last tick is one, not zero change count down interval to 500 instead of 1000:
public class MainActivity extends AppCompatActivity {
TextView textView;
CountDownTimer mycounterdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startcard = 10000;
textView = (TextView) findViewById(R.id.test);
mycounterdown = new CountDownTimer(startcard, 500) {
#Override
public void onTick(long mycounterup) {
int minutes_up_start = (int) (mycounterup / 1000) / 60;
int seconds_up_start = (int) (mycounterup / 1000) % 60;
String time_2_up_start_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up_start, seconds_up_start);
textView.setText(time_2_up_start_formatted);
}
#Override
public void onFinish() {
// call here other methods from activity
testMethod();
}
};
mycounterdown.start();
}
public void testMethod(){
Toast.makeText(MainActivity.this, "Test Method called", Toast.LENGTH_SHORT).show();
}
}
NOTE: take a look at this answer
First, extend CountDownTimer in your timer class.
public class countdown_timer extends CountDownTimer {
}
This allows you to implement some methods.
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
}
Also you must implement constructor that matches super class. You can also add some additional parameters. For example TextView
TextView textView;
public countdown_timer(long millisInFuture, long countDownInterval, TextView txt) {
super(millisInFuture, countDownInterval);
textView = txt;
}
The onFinish() is what you want. Also make sure you are using this class as a CountDownTimer. Then you will be able to start your timer.
Hope it helps.

Countdown Timer not counting correctly

When I pause the timer and then start it again it seems like the timer counts the current second again. For example it is 00:10, after half a second I stop the timer and when I start it again instead of going from 00:10 to 00:09 in half a second it counts a full second. I can't find what is wrong. Thanks for any help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer_2);
//...
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
if (timer_2_up_running) {
pausetimer_2_up();
starttimer_2_down();
} else {
starttimer_2_up();
if (timer_2_down_running) {
pausetimer_2_down();
private void starttimer_2_up() {
timer_2_up_countdowntimer = new CountDownTimer(starttimeup, 1000) {
#Override
public void onTick(long millisUntilFinished) {
starttimeup = millisUntilFinished;
update_up_text();
#Override
public void onFinish() {
timer_2_up_running = false;
}
}.start();
timer_2_up_running = true;
}
private void starttimer_2_down() {
timer_2_down_countdowntimer = new CountDownTimer(starttimedown, 1000) {
#Override
public void onTick(long millisUntilFinished) {
starttimedown = millisUntilFinished;
update_down_text();
}
#Override
public void onFinish() {
timer_2_down_running = false;
}
}.start();
timer_2_down_running = true;
}
private void pausetimer_2_up() {
timer_2_up_countdowntimer.cancel();
timer_2_up_running = false;
}
private void pausetimer_2_down() {
timer_2_down_countdowntimer.cancel();
timer_2_down_running = false;
}
private void update_up_text() {
int minutes_up = (int) (starttimeup / 1000) / 60;
int seconds_up = (int) (starttimeup / 1000) % 60;
String time_2_up_left_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_up, seconds_up);
timer_2_up.setText(time_2_up_left_formatted);
}
private void update_down_text() {
int minutes_down = (int) (starttimedown / 1000) / 60;
int seconds_down = (int) (starttimedown / 1000) % 60;
String time_2_down_left_formatted = String.format(Locale.getDefault(), "%02d:%02d", minutes_down, seconds_down);
timer_2_down.setText(time_2_down_left_formatted);
}
You can use Chronometer to display recording time. start the
Chronometer when recording start and stop it when recording stop
<Chronometer
android:id="#+id/chronometerRecordTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/relativeLayout_bottom_video_controls"
android:layout_centerInParent="true"
android:layout_marginBottom="20dp"
android:visibility="invisible"/>
private Chronometer chronometerRecordTime;
chronometerRecordTime = findViewById(R.id.chronometerRecordTime);
chronometerRecordTime.setBase(SystemClock.elapsedRealtime()); // Reset
chronometerRecordTime.start(); // start
chronometerRecordTime.stop(); // stop
I have also crate timer to stop recording after one min. you can
modify it according to your requirement.
int myTimeCounter;
Timer myRecordingTimer;
private boolean myTimerHasStarted = false;
private String TAG = "Log";
private void startTimerTask() {
myTimeCounter = 1;
myRecordingTimer = new Timer();
myRecordingTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
myTimerHasStarted = true;
if (myTimeCounter == 60) {
myRecordingTimer.cancel();
myTimerHasStarted = false;
return;
}
Log.d(TAG, "timer=" + String.valueOf(myTimeCounter));
myTimeCounter++;
}
});
}
}, 0, 1000);
}

disable a thread on click

I am working on app that calculate time when specific app run, to save ram, I want to stop some of the threads by using check box. i want a command when I press the check box the thread stops even "if condition" is right"
the if conditon of detecting app :
if (MainActivity.tgbutton.isChecked())
{
if (packageName.equals("com.facebook.katana"))
{
if (f==1)
{
}
else
{
// Toast.makeText(getApplicationContext(),"fb on", Toast.LENGTH_SHORT).show();
f=1;
facebook = true;
startTimef = SystemClock.uptimeMillis();
customHandlerf.postDelayed(updateTimerThreadfacebook, 0);
}
}
else
{
if(f==1)
{
//Toast.makeText(getApplicationContext(),"fb off", Toast.LENGTH_SHORT).show();
facebook = false;
timeSwapBufff += timeInMillisecondsf;
customHandlerf.removeCallbacks(updateTimerThreadfacebook);
f=2;
}
}
}
the check box :
blabla.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// what to write here to disable thread???
}
}
});
the thread itself :
private Runnable updateTimerThreadfacebook = new Runnable() {
public void run() {
if (facebook = true)
{
timeInMillisecondsf = SystemClock.uptimeMillis() - startTimef;
updatedTimef = timeSwapBufff + timeInMillisecondsf;
int secsf = (int) (updatedTimef / 1000);
int minsf = secsf / 60;
secsf = secsf % 60;
MainActivity.facebook.setText("" + minsf + ":" + String.format("%02d", secsf));
customHandlerf.postDelayed(this, 0);
}
}
};
you should use value on your run method
public class MyClass implements Runnable{
boolean signal=false;
public setisFinish(boolean sig)
{
signal = sig;
}
#Override
public void run()
{
if(!signal)
//Do SomeThing
}
public void foo()
{
System.out.println("foo");
}
}
and in your click listener
blabla.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
myThread.setisFinish(true);
}
}
});
this code resume your thread and you can start it whenever you whant and if you want interrupt your thread use this code
myThread.interrupt();
Overwrap your Runnable object with Thread class:
private Thread updateTimerThreadfacebook = new Thread(new Runnable() {
public void run() {
if (facebook = true) {
timeInMillisecondsf = SystemClock.uptimeMillis() - startTimef;
updatedTimef = timeSwapBufff + timeInMillisecondsf;
int secsf = (int) (updatedTimef / 1000);
int minsf = secsf / 60;
secsf = secsf % 60;
MainActivity.facebook.setText("" + minsf + ":" + String.format("%02d", secsf));
customHandlerf.postDelayed(this, 0);
}
}
});
when you want to stop it use interrupt method.
updateTimerThreadfacebook.interrupt();

Categories