I wanted to use timer to decrease 15:00 (set in textview) by each second. i.e; 14:59, 14:58 and so on...
Tried working on it but facing issue with the code. Help me to solve this
Runnable updater;
void updateTime(final String timeString) {
mTimer = (TextViewMedium) findViewById(R.id.mTimer);
timerHandler = new Handler();
updater = new Runnable() {
#Override
public void run() {
mTimer.setText(timeString);
timerHandler.postDelayed(updater,1000);
Toast.makeText(JobRequestActivity.this, timeString, Toast.LENGTH_SHORT).show();
}
};
timerHandler.post(updater);
}
The logic behind your code is wrong. Use the code below:
int time;
int currentTime;
Handler timerHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message message) {
timerHandler.sendEmptyMessageDelayed(0,1000);
currentTime-=1;
int minutes = currentTime/60;
int seconds = currentTime%60;
String timeString = minutes+":"+seconds;
TextView mTimer = (TextViewMedium) findViewById(R.id.mTimer);
mTimer.setText(timeString);
Toast.makeText(JobRequestActivity.this, timeString, Toast.LENGTH_SHORT).show();
return false;
}
});
Then call the timeHandler anywhere in your code:
time = toSeconds(yourTimeString);
currentTime = time;
timerHandler.sendEmptyMessage(0);
Use this code to convert your time String to int:
private static int toSeconds(String s) {
String[] mTime = s.split(":");
int mins = Integer.parseInt(mTime[0]);
int seconds = Integer.parseInt(mTime[1]);
return mins*60 + seconds;
}
Related
So I found this background service code that keeps on popping up a toasts every 10 seconds. What I want to ask is translate this code on popping up in minutes interval instead of 10 seconds of interval and instead of a toast popping up I want to it to popup an activity when the interval finishes.
public class TimeService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// cancel if already existed
if(mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast
Toast.makeText(getApplicationContext(), getDateTime(),
Toast.LENGTH_SHORT).show();
}
});
}
private String getDateTime() {
// get date time in custom format
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
...
}
public static final long NOTIFY_INTERVAL = 10 * 1000 * 60;
10*1000 is 10 seconds.Time is always counted as milliseconds. so
change 10 * 1000 to 10 * 1000 * 60
public static final long NOTIFY_INTERVAL = 10 * 1000 * 60;
The timer works fine for starting then reseting and leaving the view, but if I start the time then leave the view and return and just hit Reset the app crashes. I know that most people would not hit reset when the timer is not started, but for idiot proofing I need a fix for this any suggestions?
public void startTimer(View view) {
final Handler handler = new Handler();
Timer ourtimer = new Timer();
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
int sec = n % 60;
int min = n / 60;
TextView timer = (TextView) findViewById(R.id.androidtimer);
timer.setText("" + String.format("%02d", min) + ":"
+ String.format("%02d", sec));
// timer.setText(n + " Seconds");
n++;
}
});
}
};
ourtimer.schedule(timerTask, 0, 1000);
}
public void stopTimer(View view) {
timerTask.cancel();
TextView timer = (TextView) findViewById(R.id.androidtimer);
timer.setText("--:--");
timerTask = null;
n = 0;
}
I think your problem is that timerTask is null as long as you do not start the timer.
So a simple if clause might help. If that's not the problem please post the exception.
public void stopTimer(View view) {
if(timerTask != null) {
timerTask.cancel();
}
TextView timer = (TextView) findViewById(R.id.androidtimer);
timer.setText("--:--");
timerTask = null;
n = 0;
}
I am scheduling a simple task that should update a text field in 4 seconds.
However everytime this is called the activity pauses and does not show the value in the text field until I restart the activity.
private void showDelayedValue() {
Runnable longRunningTask = new Runnable() {
public void run() {
int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
String randomValStr = Integer.toString(randomVal);
Log.i(this.getClass().getSimpleName(),
"FIRED startScheduler: " + randomValStr);
theFieldOnScreenTV.setText(randomTempStr);
}
};
//show the value in 2 seconds
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
The log shows:
FIRED startScheduler: 4
but does not update the TextView theFieldOnScreenTV
Instead onPause is called right after Fired startScheduler: is displayed in LogCat.
Many thanks!
EDIT:
This worked for me following Alex' approach:
private void showDelayedValue() {
int randomX = randomNumberGenerator.nextInt(30 - -10) - 10;
final String randomXStr = Integer.toString(randomX);
final Runnable updateFieldR = new Runnable() {
public void run() {
theFieldOnScreenTV.setText(randomXStr);
}
};
Runnable longRunningTask = new Runnable() {
public void run() {
theFieldOnScreenTV.post(updateFieldR);
}
};
scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);
}
instead of
theFieldOnScreenTV.setText(randomTempStr);
try
theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
Have a try using Handlers.
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
theFieldOnScreenTV.setText(randomTempStr);
}
});
A bit confusing this one but should make sense.
Thanks to all your help I have my app now showing a custom digital clock and a countdowntimer (02:30:00 countdown) running under it.
How do I add 02:30:00 to the current time so a new clock field shows the current time + the countdown?
Thanks
Dj
This is my digitalclock code where would i put the offset to ad 2 hours 30 mins to time...
#Override
protected void onStart() {
super.onStart();
timer = new Timer("DigitalClock");
Calendar calendar = Calendar.getInstance();
final Runnable updateTask = new Runnable() {
public void run() {
countdown.setText(getCurrentTimeString());
}
};
int msec = 999 - calendar.get(Calendar.MILLISECOND);
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(updateTask);
}
}, msec, 1000);
}
#Override
protected void onStop() {
super.onStop();
timer.cancel();
timer.purge();
timer = null;
}
private String getCurrentTimeString() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
// int second = calendar.get(Calendar.SECOND);
return String.format("%02d:%02d", hour, minute);
}
Now that I understand your question :p, I think the only way to do that is to reimplement a DigitalClock. Take its source code and play with it by adding an offset to the hours and minutes.
UPDATE:
What I would do is take that code and change this part:
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
Convert 2:30:00 to milliseconds and add it to now :
long now = SystemClock.uptimeMillis() + offset;
I use the following code to update a timer in my UI.
The problem with this code however, is that with each second passed, it updates by +1 second.
I think I understand why this happens, however I don't know how to fix it.
private Handler mHandler = new Handler();
....
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
mDifference = System.currentTimeMillis() - mStartTime;
workSum = workSum + mDifference;
TextViewTime.setText("Time so far: " + formatTime(workSum));
mHandler.postDelayed(this, 1000);
}
};
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_button:
startButton.setEnabled(false);
stopButton.setEnabled(true);
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 1000);
}
Help would be greatly appreciated!
workSum = workSum + mDifference; seems to be your problem, because mDifference is incrementing each time.
I think workSum = mDifference; will solve it, or even
mDifference = System.currentTimeMillis() - mStartTime;
TextViewTime.setText("Time so far: " + formatTime(mDifference));