Countdown timer problem on android - android

Hi I have a countdown timer in my activity oncreate method as follows
start1 = new CountDownTimer(level1time, 1000)
//timer updated every second
{
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//switch activities
}
}
.start();
}
I then call start1.cancel later in my code. This works when this particular activity is started once but when this activity is created again later the activities switch instantly due to the first timer finishing.
My understanding is that a new timer should be created each time the activity is created but that does not seem to be the case. Does anyone know how to fix this problem?

In any case it's better to use Handlers instead of Timers. I generally create a final Runnable object that has what I want run after a certain time, create a new Handler in onCreate(), and post the Runnable to it after a certain delay with postDelayed(Runnable, int). If the user leaves the activity or you ever want it to not execute, you can simply call Handler.removeCallbacks(Runnable) with your defined Runnable to stop the "timer" on it.
That's a high-level approach to your question. Get familiar with the Handler class and this becomes a very easy problem.

Related

Android - Interact with the main thread every few milliseconds

I'm new to Android, so apologies if I'm missing anything obvious.
I'm writing an app that does something every few hundred milliseconds. The frequency varies, but no more often than every 300 or so.
Currently I have a class DoEvery that implements Runnable that is scheduled every X milliseconds using scheduleAtFixedRate from the main thread. That is working, but I want to add an animation that is started every time DoEvery.run executes using Drawable.start() and from what I've read it doesn't seem like that is possible since Drawable.start() needs to be run on the main thread. Using scheduleAtFixedRate also seems to make it difficult to change the frequency later.
Is there a way to start the animation from the DoEvery class? Or is there a better way to run something on a regular basis like this?
You could try this.
new Thread(new Runnable() {
#Override public void run() {
//I'm in the thread.
//if you are not in the Activity, pass the activity instance to your class
// and use myActivity.runOnUiThread(...)
runOnUiThread(new Runnable() {
#Override public void run() {
//I'm in the main thread
}
});
}
}).start();

Android UI Update Thread - saving and restoring it

How do I properly do that?
I have a stopwatch and I'm saving it's state in onSaveInstance and restoring it's state in onRestoreInstance...
Now I've following problem: if I stop the thread in onSaveInstance and the screen get's locked or turned off, onRestoreInstance is not called and the stopwatch is not continuing...
If I don't stop it, the stopwatch is running in background on and on even when the screen is off or the activity is not active anymore...
So what's the usual way to handle such a thing?
PS:
I even have a working solution, a local variable to save the running state in the onStop event and restarting the thread in the onStart event... But I still want to know if there's a "default" solution using the android system itself....
Ok. I better now understand what you're doing. I thought you were using the thread to count. Right now it sounds like you're using it to update the UI.
Instead, what you probably should be doing is using a self-calling Handler. Handlers are nifty little classes that can run asynchronously. They're used all over the place in Android because of their diversity.
static final int UPDATE_INTERVAL = 1000; // in milliseconds. Will update every 1 second
Handler clockHander = new Handler();
Runnable UpdateClock extends Runnable {
View clock;
public UpdateClock(View clock) {
// Do what you need to update the clock
clock.invalidate(); // tell the clock to redraw.
clockHandler.postDelayed(this, UPDATE_INTERVAL); // call the handler again
}
}
UpdateClock runnableInstance;
public void start() {
// start the countdown
clockHandler.post(this); // tell the handler to update
}
#Override
public void onCreate(Bundle icicle) {
// create your UI including the clock view
View myClockView = getClockView(); // custom method. Just need to get the view and pass it to the runnable.
runnableInstance = new UpdateClock(myClockView);
}
#Override
public void onPause() {
clockHandler.removeCallbacksAndMessages(null); // removes all messages from the handler. I.E. stops it
}
What this will do is post messages to the Handler which will run. It posts every 1 second in this case. There is a slight delay because Handlers are message queues that run when available. They also run on the thread that they're created on, so if you create it on the UI thread you will be able to update the UI without any fancy tricks. You remove the messages in the onPause() to stop updating the UI. The clock can continue to run in the background, but you won't be showing it to the user anymore.
I just got into Android programming, but I don't think onRestoreInstance will be called in that situation because you're not switching from one activity to another. I think your best bet is to call onPause which will then call onSaveInstance if you need it to, but use onResume which might or might not call onRestoreInstance.

Best way to execute a thread after a period of time in android

I am having a service in my application that puts a runnable (in another java file) in a thread and starts it.
That is working fine for once, but i want it to be repetitive due to a certain period.
I need a good way to handle that.
Reason why I didn't use the answers to other questions is that I don't want it to repeat infinity nor I know how many times it'll repeat the task. It'll simply stop due to a button click in the UI.
I was thinking of using a loop with a sleep and if statement. But I think that's really bad design for my application. Is there a standard way for doing such thing?
Thanks...
You can use a handler that somehow acts like a timer but I think it is better for your situation.
You initialize it like this:
Handler delayhandler = new Handler();
Set the time it fires like this (in ms):
delayhandler.postDelayed(mUpdateTimeTask, 500);
And it calls this:
private Runnable mUpdateTimeTask = new Runnable()
{ public void run()
{ // Todo
// This line is necessary for the next call
delayhandler.postDelayed(this, 100);
}
}
You can also remove the next call with:
delayhandler.removeCallbacks(mUpdateTimeTask);
Use a TimerTask and have it execute your thread/method.
http://android.okhelp.cz/timer-simple-timertask-java-android-example/
http://developer.android.com/reference/java/util/TimerTask.html - You can use the Cancel() method to stop the TimerTask from executing.
Use the Timer it will run the thread after a given time period and when you want to stop just stop timer or set it to infinite time period.

Programmatically 'press' button every 60 seconds

In my app, I've been asked to add an auto update function. What I'm trying to do is have a timer event so that if the user hasn't pressed the update button in the last 60 seconds, do a 'refreshButton.performClick();'.
I've been searching but I can't find an example where the timer interacts with the UI. I keep getting errors like 'only the original thread that created a view hierarchy'.
If the user does press the button, I want to reset the timer.
Is this even possible?
You only can interact with aView from the UI thread.
You can make something like this in your timer task;
Define this variable in your class:
Handler handler = new Handler();
In your timer task call:
handler.post(new Runnable(){
public void run(){
refreshButton.performClick();
}
});
I think you are going in the wrong direction. Instead of trying to press the button, just set a timer to call the same method that is called once the button is pressed, it will make it way simpler, and will not involve the UI for no reason.
You can use AlaramManager class and a background service to run your code on every 60 second.
Here is an example see AlarmService_Service.java

android: what's the difference between a timertask and a service?

I'm using a timertask in the main activity in order to update some data repeatedly every X seconds.
This data is of static form, so it's a public static method
is this a bad technique? I mean, using static methods like this
I know there's this thing called Service, but there aren't really many examples online on how to use it in order to update every X seconds a variable that should be then accessed by some activity
so my question is, what's the difference between using a timer task and a service? is a timertask just a time counter and nothing else? does it run in parallel if it's being used with a handler or not? and what happens if you have something like this:
handler = new Handler();
t = new Timer();
task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
//do stuff;
}
});
}
};
t.schedule(task, 0, 10000);
how exactly does this code work? what does it do? does it run in parallel? why even if I leave the activity where this code is first being called, it still runs? what makes it run in this case?
thanks in advance
TimerTask is part of standard Java and can be use for delayed or repeated execution for some piece of (Runnable) code. It's use is discouraged on Android. You can use a Handler instead.
A Service can be used as a independent and UI-less part of your Android application. It can run and create it's own threads and can be started for UI or with Intents through a AlarmManager for example.
It think want you want is a Service which creates it's own thread and does some work. When the work is done, memory will be freed on Android when the garbage collector kicks in, something you do not control and that's a good thing.

Categories

Resources