Run thread periodically - android

I have a runnable class like this:
public class GetUpdatesThread implements Runnable{
#Override
public void run() {
//call a webservice and parse response
}
}
Which I want fire every 10 seconds for instance...
I would like to know how can I manage handlers or runnables or timers in my activity to acomplish this?
Thanks in advance!

You can use TimerTask and can implement like this.
int delay = 5000; // delay for 5 sec.
int period = 10000; // repeat every 10 secs.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("repeating");
}
}, delay, period);

You can use the timer method called scheduleAtFixedRate from this link. I am already using it inside my project and it works like charm. You just have to give a starting delay time and a period for it then it works.

You can use Handler and calling the sendEmptyMessageDelayed method. Here's a tutorial or two on using Handler. Also check out Updating the UI from a Timer from the official doc - it covers both approaches with TimerTask and Handler.

The best way to do this thing is to use AlarmManager class.
1) schedule a AlarmManager with serRepeat method. link for AlarmManager
2) set Broadcast receiver in Alarmmanager, it will call Receiver every particular time duration, now from Receiver you can start your thread .
if you use Timer task and other scheduler, Android will kill them after some time.

Related

java.lang.IllegalStateException: TimerTask is scheduled already: Rationally using of Timer and TimerTask in Android

I write an application that connects to server and sends him ping commands, server answer with pong commands.
I want to implement connection timeout mechanism. I think it will be following:
Client send ping and start timer with timertask and delay
When client receive pong, timertask is cancelled.
Also, I want to optimize memory. So, not to recreate TimerTask every time I send ping command. I try code below:
private final Timer mSystemLogoutTimer = new Timer();
private final TimerTask mLogoutTask = new TimerTask() {
#Override
public void run() {
mMessageInterface.onConnectionTimeout();
cancel();
}
};
private void ping() {
sendRequest(RequestBuilder.formPing());
mSystemLogoutTimer.schedule(mLogoutTask, CoreConst.PING_ANSWER_DELAY);
}
private void onPong() {
mLogoutTask.cancel();
}
But I get following error when try to schedule TimerTask second time:
java.lang.IllegalStateException: TimerTask is scheduled already
at java.util.Timer.scheduleImpl(Timer.java:572)
at java.util.Timer.schedule(Timer.java:459)
I don't understand, because I call cancel() on TimerTask.
Please tell me what I am doing wrong.
Thank you for answers!
TimerTask.cancel() does not necessarily prevent the execution of the task. According to the SDK documentation, it returns true when the execution was actually prevented, false otherwise.
Looks like this it what happens with your code as the first time true is returned, but not the second, leading an IllegalStateException to be thrown when calling Timer.schedule() right after.
You should check TimerTask.cancel()'s return code, and recreate your TimerTask when false is returned: the TimerTask is burnt and cannot be reused at that stage.

Taking a picture with 2 secs of delay

Is there a way to take a picture two seconds after the Camera.takePicture method is invoked? For some reason, I do not want to use handler/timer to schedule the invocation of takePicture.
Precisely, I would like to use a different solution than the following one:
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
<here takePicture is invoked>
}
});
}
}, 2000);
You could use AlarmManager with a PendingIntent and handle taking the camera capture in your Activity.onNewIntent method, but it is a very confusing solution for what you are trying to solve (a much better use of AlarmManager is to schedule tasks so that they are performed even if the user exits your application). This solution also requires more code and is less precise/reliable and less efficient than using a Handler.
EDIT: You can also use a ScheduledThreadPoolExecutor along with a Runnable.
(Personal opinion following) If you are exploring the APIs available in Android for performing timed tasks, that is ok, but I wouldn't use AlarmManager to schedule timed tasks within an Activity that's already running.
If you just want to have the code a bit more organised, you can make an inner class that implements Runnable and schedule your action like this:
class MyCameraActivity extends Activity
{
class TakePictureTask implements Runnable
{
public void run()
{
MyCameraActivity.this.takePicture();
}
}
void scheduleCameraShot()
{
(new Handler(this.getMainLooper())).postDelayed(new TakePictureTask(), 2000);
}
}

Setting a scheduled task inside an activity

I have an activity (MapActivity actually) that has a linearLayout with a mapView and a textView, for displaying current speed, among other things. The thing is that I would like the textView to be updated every 0.5 seconds, for example.
I know this can be done with a service (at least that is how I learnt to do it), but I was wondering if it is possible to do so using a Timer inside the MapActivity itself. I tried this approach:
onCreate{
...
updateTimer = new Timer();
updateTimer.scheduleAtFixedRate(doRefresh, 0, updateInterval);
}
private Timer updateTimer;
private TimerTask doRefresh = new TimerTask()
{
public void run()
{
updateData();
}
};
private void updateData()
{
//update the textView with the data
}
private int updateInterval = 500;
However, it gives me the following error:
04-10 22:24:56.529: ERROR/AndroidRuntime(9434): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
Then, is it possible to do what I'm trying in an easy way, without using a service class?
Thank you and regards,
=)
Call postDelayed() on some widget, supplying a Runnable and 500 as the delay. The Runnable should do whatever work you want done, then call postDelayed() again with itself as the Runnable and 500 as the delay.
This avoids background threads and services, which are not needed for simple timing events in an activity.

Service Timer Notification

HI!
I want make service in OnCreate(), and every five minute, the service show notification..
can you show me about it??
thanks before :)
You can use the TimerTask class with the postDelayed method.
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
//Whatever you want
postDelayed(this, REPEAT_INTERVAL); // rinse and repeat...
}
};
And in your OnCreate launching the TimerTask for first time:
postDelayed(mTask, INITIAL_DELAY);
You can find some information in this android article
http://developer.android.com/resources/articles/timed-ui-updates.html

android timer question

Hello I am building an application that is going to execute a block of code at fixed periods of time (e.g. every 30 minutes). I would like that period to be strict,what I mean is that I would like to be guaranteed that the period will be 30 minutes and not 28 minutes or whenever the os whants to execute it.
I have a Timer object and use it as follows:
timer=new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval());
where GetLastLocation is the handler class wich extends TimerTask.
This works fine,but I would like to be able to change the interval,what I am currently doing is using timer.scheduleAtFixedRate twice and changing the interval parameter to lets say a newInterval but I think that this is just having two timers execute every interval and new
Interval now, am I correct?
also I have tries cancelling the timer and then using the the method scheduleAtFixedRate() but this throws an exception as stated in the documentation.
what can I do to fix this?
regards maxsap
you can not schedule on a timer which was already cancelled or scheduled. You need to create a new timer for that.Timer timer;
synchronized void setupTimer(long duration){
if(timer != null) {
timer.cancel();
timer = null;
}
timer = new Timer();
timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}Now you can call setupTimer whenever you want to change the duration of the timer.PS: In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Define your task inside a TimerTask (as you did) and schedule the timer.
public final void checkFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
//Execute code...
}
};
t.schedule(tt, 10*1000); /* Run tt (your defined TimerTask)
again after 10 seconds. Change to your requested time. */
}
Just execute the function wherever you want, for example in onCreate or in onResume/onStart.
You can also use handler instead of timertask.
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if(what.msg==1)
{
what.msg==2;
}
}
};
mHandler.sendEmptyMessageDelayed(1, 10* 1000);//10*1000 10 sec.specify your time

Categories

Resources