Stop watch timer that increments (like countdowntimer) - android

I have been using countdowntimer and it has performed perfectly. Now I want to implement the opposite (Something like stop watch) in which the time updates the screen every second and it increments forever till I stop.
Is there a way (similar in simplicity) that does the job sort of like Countdowntimer? I know I can use Timer and Timertask but this creates new thread and I read that it is not that reliable (or recommended).
Thank you

Looks like a Chronometer object is what you need.
By setting a tick listener, you will get a tick every second (unfortunately that's the minimum precision available, but from the question it looks like it's enough for your needs).

If you add the following class to you project, you can use it just like the CountDownTimer class:
public abstract class Stopwatch extends Thread {
int tickFreq;
public Stopwatch(int tickFreq) {
this.tickFreq = tickFreq;
}
abstract void onTick();
#Override
public void run() {
onTick();
try {
Thread.sleep(tickFreq);
}
catch (InterruptedException e) {
e.printStackTrace();
}
super.run();
}
}
And to use it, you would write:
new Stopwatch(1000){
#Override
void onTick() {
// Do whatever you want to do in here
}
}.start();
The param that's passed to the constructor (1000) is how often it should call onTick(). In this case, it's every 1000 milliseconds, i.e. every 1 second.

Related

Show Message According to TIme

I've a TextView where I want to set a message according to time ( hour of day). To achieve this I'm using-
Thread t2 = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(3600000);
handler.post(new Runnable() {
#Override
public void run() {
int hour=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
update(hour);
}
});
}
} catch (InterruptedException e) {
}
}
};
t2.start();
where update(hour) is used to update the message.
This works fine, however, the updating is done depending on the launching time. For example, the message should update at time 20:00. But if the app is launched at 19:59, the updating takes place at 20:59.
If I use Thread.sleep(1000) it works just as expected. But I feel like wasting resource by running the thread every second just to look for a 1 hour event. Is there any better way to do this?
Surely you need to check the current time, get the minutes past the hour, then work out from there when the next hour 00 will come. Then, just sleep time for those minutes, then for all the hours after that sleep for the full hour.
Take a look at AlarmManager.
The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running.

Android, how to measure an elapsed amount of time

I'm working on a presentation app, which displays different images. There I wanted to to let the presentation slide through my List of images, video and pdf files, after a short amount of time.
I start my different views through intents, startActivityForResult(intent, RESULT_OK);
Starting videos and closing videos was not an issue. I used onPreparedListener and setOnCompletionListener and everything worked like a charm.
With pictures however, this was completely diffrent.
I created a new Thread in my ImageView and did put that thread to sleep(), after that I called the setresult() method and finish(). But instead of waiting, the picture wasn't shown at all and the presentation was stuck there, without setting the result and finishing the activity.
So I started searching for some explanation of time in android and found this explanation:
Explanation
I read through it and tried to get a good grasp on whats explained there. But the more I thought about it, the more I got insecure, which is the best way to implement the waiting behavior for my intended purpose.
So instead of some code, I am much more interested in, what you would advise me to use and why with a, if possible, detailed explanation.
elapsedRealtime()?
uptimeMillis()?
System.currentTimeMillis()?
From android docs:
• System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.
• uptimeMillis() is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls), Object.wait(millis), and System.nanoTime(). This clock is guaranteed to be monotonic, and is suitable for interval timing when the interval does not span device sleep. Most methods that accept a timestamp value currently expect the uptimeMillis() clock.
• elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
If the time interval, you're going to measure, is relatively short, you can use pretty much any method which gives you correct time. I prefer currentTimeMillis(). In case the time interval is really long, the recommended method is to use elapsedRealtime().
Also, if you only want to do something with a delay, simply use: http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long) . It's simple and works great.
Simplest way to achieve that is CountDownTimer
private final class CountDownTimerImpl extends CountDownTimer {
//5 sec.
private static final long TIME_INTERVAL = 5000;
private final ImageView imageView;
private final List<Drawable> images;
public CountDownTimerImpl(ImageView imageView, List<Drawable> images) {
super(TIME_INTERVAL, TIME_INTERVAL);
this.imageView = imageView;
this.images = images;
//set first image from images array to imageView
imageView.setImageDrawable(images.get(0));
}
//this method is executed after TIME_INTERVAL (5 sec.)
public void onFinish() {
//remove drawable from imageView
imageView.setImageDrawable(null);
//remove this drawable from array
images.remove(0);
//if array is not empty start another count down
if (!images.isEmpty()) {
new CountDownTimerImpl(imageView, images).start();
}
}
public void onTick(long millisUntilFinished) {
//nothing to do here
}
}
You should start this CountDownTimer by:
new CountDownTimerImpl(imageView, images).start();
where images is of course an drawables array of your presentation images.
I have no time to test this solution but it should work - if not please leave a comment and I will update it later.
You can use TimerTask
int counter=0;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
counter++;
//you can do stuffs here say like if (counter==15) { do something}
}
});
}};
ourtimer.schedule(timerTask, 0, 1000);
You can do this in a different way writing a callback module
Create a activity call it BaseActivity and let all you activities to extend it
Now declare a method call is void callback(){} keep the body empty
now in onCreate create a timer as above and call the callback function your code will look like
onCreate(){
final Handler handler = new Handler();
Timer callTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
callback();
}
});
}};
callTimer.schedule(timerTask, 0, 1000);
}
Now in you activity override the callback method which will be called after the time you specified in timer,
Ex
Class a extends BaseActivity(){
#Override
onCreate(){
// playVideo
}
#Override
void onCallBack(){
//navigate to another activity
}
}

How to find if a function hasn't been called?

I am working on an Android application and I just want to know when a function hasn't been called. For example, lets say you have the function
void foo()
{
...//do something here;
}
What I want to do is time if the function hasn't been called for lets say, 10 seconds, and then record the time after that 10 seconds. After that, if the function is invoked and it is called, I want to record the time when it function begins again. I was thinking of using the Timer function but I wasn't exactly sure on how to test whether or not a function has been invoked.
I am working on an application in which you see whether or not a person starts or stops walking. For example, if someone has stopped walking for 10 seconds, I want to record that time. When they resume walking, I also want to record that time. Hope this makes better sense. Any help would be appreciated! Thanks!
One possible solution is to add a boolean flag to your code; maybe call it fooWasCalled. Initialize this variable to false and set it to true inside foo(). Then you can simply check the flag when you need to know whether or not the function was called.
This is a very common idiom to check whether some action has occurred.
p.s. Since you are using a Timer, you probably need to synchronize access to this boolean flag or use some other thread-safe mechanism.
This is probably what you want (not completer code, just idea)
protected boolean mIsCountDownOn;
private class CountDownTimer mCountDownTimer = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
}
};
In foo
foo
{
if (mIsCountDownOn)
{
// less than 10 seconds since the last time foo is called
mCountDownTimer.cancel();
}
else
{
// more than 10 seconds since last call
mIsCountDownOn = true; // will start the timer at the end of foo body
// Code to save mTime to wherever you want to save it.
}
// Whatever else foo supposes to do
mTime = // get the time now
mCountDownTimer.start();
}

Android AndEngine RegisterUpdateHandler variable time

I'm using andengine and I have something like this:
scene.registerUpdateHandler(new TimerHandler(anotherclass.getSpeed(), true,
new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
//Something I need done
}
}));
The thing is getSpeed() returns first time let's say 0.20f . Then getspeed would return 0.18f but I think that it is called only once when the timer is started and even though my speed from the other class changes, my timer runs at the interval init_speed.
So, I need a way to dynamically change the time period of the timer.
This question was asked once before, and I created a timer class in which you can change the interval as you want. Here is the question, and here is the timer class.
EDIT: Here is a sample:
Timer timer = new Timer(1f, new ITimerCallback() {
#Override
public void onTick() {
//Do what you need here.
}
}
Register it:
(Engine/Entity/Scene here).registerUpdateHandler(timer);
Now, save the reference to the timer. Whenever you want to change the interval, just call setInterval and the interval will be changed.
#Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {
return new FixedStepEngine(pEngineOptions, 30);
}

Android 2.2: How to update textviews automatically with a timer?

I have some TextViews in my app that I want updated automatically each 5 seconds. I have a method for refreshing them, but how do I make a timer that runs the method every 5 seconds? Thanks!
Provide another solution
Handler h=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
h.post(new Runnable(){
#Override
public void run() {
// call your function
h.postDelayed(this,5000);
}
});
Look at extending a CountDownTimer, it has an onFinish() method you can overwrite to update your TextView, and restart the timer if you wish to make it repeat. You can also bind to onTick() if you only want to update a finite number of times.
I tried the Handler solution myself, especially after reading this article on the resource pages: http://developer.android.com/resources/articles/timed-ui-updates.html. But I wanted to be able to start and stop the timer much like a stopwatch, and after resuming the timer the Handler solution started updating much less regularly - on the emulator about every five seconds. In the end I found a tip on a blog that suggested the solution with an inner class extending AsyncTask. You can make use of the publishProgress()-onProgressUpdate() functionality in AsyncTask. From onProgressUpdate(), you're allowed to make changes "directly" in your UI thread e.g. myTextView.setText(...). This publishes results much more frequently. Here's a super simple implementation of that inner class:
private class UpdateTimerLabel extends AsyncTask<Integer, Integer, Integer> {
#Override
protected Integer doInBackground(Integer... arg0) {
while (true) {
try {
Thread.sleep(1000);
publishProgress(arg0);
Log.d(tag, "AsyncTask tries to publish");
} catch (InterruptedException e) {
e.printStackTrace();
}if (1 == 0) break; // Silly but necessary I think
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
updateTimerTextView(); // Call to method in UI
}
}

Categories

Resources