i want to make counter time in Android - java

I create a Android app and I want to make time counter. there are two long variables that it storage long data.
When running second finished, walking second must started and after this process go on four times that must finished.
public void Counter(long runsecond, final long walksecond) {
new CountDownTimer(runsecond, 1000) {
public void onTick(long millisUntilFinished) {
showtext.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
showtext.setText("done!");
new CountDownTimer(walksecond, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
showtext.setText("done!");
}
}.start();
}
}.start();
}
i take in for. only it count once. how can i correct this problem?

I think something like that might satisfy your needs. Number of seconds for both, run and walk counters, is configurable. Repeat rate specifies, how many times should both counters run.
public enum CounterType {
RUN_COUNTER,
WALK_COUNTER
}
private void start() {
int runSeconds = 5;
int walkSeconds = 5;
int repeatRate = 4; // 2 - run, 2 walk
startCount(runSeconds, walkSeconds, repeatRate, RUN_COUNTER);
}
private void startCount(final int runSeconds, final int walkSeconds, final int repeatRate, final CounterType actualCounter) {
if (repeatRate == 0) {
return;
}
int actualSeconds = 0;
if (actualCounter == RUN_COUNTER) {
actualSeconds = runSeconds;
} else if (actualCounter == WALK_COUNTER) {
actualSeconds = walkSeconds;
}
new CountDownTimer(actualSeconds * 1000, 1000) {
#Override public void onTick(long millisUntilFinished) {
Log.d("Counter - onTick", actualCounter.toString() + ": millis remaining: " + millisUntilFinished);
}
#Override public void onFinish() {
Log.d("Counter - onFinish", actualCounter.toString());
CounterType nextCounter = actualCounter == RUN_COUNTER ? WALK_COUNTER : RUN_COUNTER;
startCount(runSeconds, walkSeconds, repeatRate - 1, nextCounter);
}
}.start();
}

Related

How to implement decreasing counter in textView.setText using for loop?

I'm trying to implement a decreasing counter using for loop in android java. I have used handler & runnable to delay for loop iteration and I want the counter to start from 80 and end on 0, but in output, I'm getting counter from 0 to 80. In short, the reverse is required.
This is my code,
TextView totalpoints = (TextView) findViewById(R.id.txttotalpoints);
Handler handler1 = new Handler();
for (int count = 80;count>=0; count--){
int finalCount = count;
handler1.postDelayed(new Runnable() {
#Override
public void run() {
totalpoints.setText("Total Points : "+ finalCount);
System.out.println("This is in newpointsCounter" + finalCount);
}
}, 1000 * count);
}
Current output => Start from 0 & end on 80
Required output => Start from 80 & end on 0
You can user CountDownTimer as:
CountDownTimer countDownTimer = new CountDownTimer(80000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//TODO on each interval, print your count
}
#Override
public void onFinish() {
//TODO on finish of timer, you will get notified
}
};
countDownTimer.start();
Try this :
final Handler handler = new Handler();
int count = 80;
final Runnable runnable = new Runnable() {
public void run() {
totalpoints.setText("Total Points : " + count);
Log.d(TAG, "count: " + count);
if (count-- > 80) {
handler.postDelayed(this, 5000);
}
}
};
handler.post(runnable);
Also I would recommend using log tags rather than system.println for android
No need to use handler, Android provides CountDownTimer itself just use it.
// For Java
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
System.out.println( millisUntilFinished / 1000)
}
public void onFinish() {
//work done
}
}.start();
// For kotlin
object : CountDownTimer(30000, 1000) {
override fun onTick(millisUntilFinished: Long) {
System.out.println( millisUntilFinished / 1000)
}
override fun onFinish() {
}
}.start()

Counting up 0 to 100

CountDown 0 to 100 Android
I'm only beginner with android can you help me guys with this.
The Result must be the end of the countdown.
for example, the result value is 75 the countdown will start to 0 ends to 75
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
new CountDownTimer(30000, 100){
public void onTick(long millisUntilFinished){
waveLoadingView.setProgressValue(counter);
waveLoadingView.setCenterTitle(String.format("%d%%",result)); //result is the value from randomize 60 to 80 .
result++;
}
public void onFinish(){
}
}.start();
}
});
// result varible define as a public
long result = 80;
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new CountDownTimer(result * 1000, 100) {
public void onTick(long millisUntilFinished) {
// its start with 1 if you want start with 0 then replace with below code
//int sec = (int) (result - (millisUntilFinished / 1000)-1);
int sec = (int) (result - (millisUntilFinished / 1000));
waveLoadingView.setProgressValue(sec);
waveLoadingView.setCenterTitle(String.valueOf(result)); //result is the value from randomize 60 to 80 .
}
public void onFinish() {
}
}.start();
}
});
Try below code
mCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showResult();
new CountDownTimer(result*1000, 1000){
public void onTick(long millisUntilFinished){
waveLoadingView.setProgressValue(counter);
waveLoadingView.setCenterTitle(String.format("%d%%",newResult)); //newResult is temp value initialize with 0
newResult++;
}
public void onFinish(){
}
}.start();
}
});
You simply need to use the matching parameters when instantiating the CountDownTimer for your use case, take a look for CountDownTimer constructor method CountDownTimer(long millisInFuture, long countDownInterval). When you want to create a count down from 0 to 100 with 1 second step, you can construct your code like this:
final long ONE_SECOND = 1000;
final long ONE_HUNDRED_SECOND = 100 * ONE_SECOND;
new CountDownTimer(ONE_HUNDRED_SECOND, ONE_SECOND){
public void onTick(long millisUntilFinished) {
int second = millisUntilFinished / ONE_SECOND;
int counter = second - 1;
// do something with the counter value
}
public void onFinish() {
// do something when we finished the count down.
}
}.start();

synchronized countdown timer- android development

I have an app that has one countdown timer that should show up the same for every user when they open the app. In order to do this, I have based the time that the users' phones show on Epoch time. I do the following calculations to (what I thought would...) ensure that each phone shows the same time, and that the countdown clock is continuous and accurate. However, every time I open the app up, the clock is at a totally different time, when I think it should be continuously counting down and resetting. What's wrong? I have included my code below:
private static final int COUNTDOWN_DURATION = 30; //time in seconds
private static final long BASE_TIME = 1470729402L; //an arbitrary Epoch time that I have picked as a reference point
private TextView tvTimer;
private Long currentTimeMillis;
private int finalTime;
private boolean firstTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
//set up basics
...
//set up timer
tvTimer = (TextView) findViewById(R.id.tvTimer);
firstTime = true;
setCurrentTime();
}
private void setCurrentTime() {
currentTimeMillis = System.currentTimeMillis();
long currentTimeSecs = currentTimeMillis/1000;
long timeDiff = currentTimeSecs - BASE_TIME;
//determines what spot the countdown timer is at when the app is started
finalTime = (int) (timeDiff % COUNTDOWN_DURATION);
resetTimer();
}
public void resetTimer(){
if (firstTime) {
CountDownTimer countDownTimer = new CountDownTimer(finalTime * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
firstTime = false;
}
else {
CountDownTimer countDownTimer = new CountDownTimer(COUNTDOWN_DURATION * 1000, 1000) {
public void onTick(long millisUntilFinished) {
tvTimer.setText(" " + millisUntilFinished / 1000 + " ");
}
public void onFinish() {
resetTimer();
}
};
countDownTimer.start();
}
}

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();

Android: Pause/Resume Timer OR Thread

I have checked all SO answers about how to pause/resume timer, but can't find a solution.
I have created a Timer task which counts the effort time for an employee and puts it inside a TextView to show.
Code below:
Timer T = new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
String workingTime = "Your effort is "
+ format.format(Double.valueOf(hr)) + ":"
+ format.format(Double.valueOf(min)) + ":"
+ format.format(Double.valueOf(sec))
+ " till now for the day";
storeEffort.setText(workingTime);
sec++;
if (sec > 59) {
sec = 0;
min = min + 1;
}
if (min > 59) {
min = 0;
hr = hr + 1;
}
}
});
}
}, 1000, 1000);
where storeEffort is my TextView which shows the effort time which is stuck inside the running thread(main problem). I want to pause the effort timer with a button click and resume it when the same button clicked again.Is there any other way to do this kind of task?
You solution might have a slight problem - you are using timer to count time intervals whereas there is no need to. You could use i.e. StopWatch to count elapsed time. So instead of adding seconds in a timer job you could just get elapsed time from this timer. To pause the timer you could call stopWatch.stop() and to start it, you could call stopWatch.start().
It could look like this:
Stopwatch stopwatch = Stopwatch.createStarted();
void startThreadUpdateTimer(){}
Timer T = new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
String workingTime = "Your effort is " + sw.toString() +
" till now for the day";
}
});
}
}, 1000, 1000);
}
public void pause(){
if(stopwatch.isRunning()){
stopwatch.stop();
}
}
public void resume(){
if(!stopwatch.isRunning()){
stopwatch.start();
}
}
UPDATE Solution if the timer needs to start from beginning every second time:
public class YourOuterClass extends Activity {
private YourTimerTask mTimerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mTimerTask != null && mTimerTask.isTaskActive()) {
mTimerTask.deactivateTimer();
mTimerTask = null;
} else {
startTask();
}
}
});
...
}
private class YourTimerTask extends TimerTask {
private boolean mIsTimerActive;
public YourTimer() {
mIsTimerActive = true;
}
public void deactivateTimer() {
mIsTimerActive = false;
}
public boolean isTaskActive() {
return mIsTimerActive;
}
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
String workingTime = "Your effort is "
+ format.format(Double.valueOf(hr)) + ":"
+ format.format(Double.valueOf(min)) + ":"
+ format.format(Double.valueOf(sec))
+ " till now for the day";
if (!mIsTimerActive) {
cancel(); // will cancel this timer instance
}
sec++;
if (sec > 59) {
sec = 0;
min = min + 1;
}
if (min > 59) {
min = 0;
hr = hr + 1;
}
}
});
}
}
...
private void startTask() {
Timer T = new Timer();
mTimerTask = new YourTimertask();
T.scheduleAtFixedRate(mTimerTask, 1000, 1000);
}
}

Categories