My requirement is to call an async task repeatedly every 10 seconds so that the webservice will fetch data an do the update (updating of a map and image) accordingly.
I searched throughout and found out that one can use a tasktimer for this. The problem I am facing is that a parameter is passed into my asynctask. But I am not able to pass that parameter into the tasktimer.
I found out that for this a separate class should be created which extends timer task. But I have no idea how to get that done according to my need.
Please be kind enough to help me. The code for passing a parameter to the async task is given below.
new AsyncLoadGpsDetails().execute(userName);
I want to repeatedly perform the async task. PLease help me, I don't know how to create the class which extends tasktimer as I'm a newbie to this.
Thanks & Regards in advance
You can use either use scheduleAtFixedRate or scheduleWithFixedDelay...
scheduleAtFixedRate
// this task for specified time it will run Repeat
repeatTask.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Here do something
// This task will run every 10 sec repeat
}
}, 0, 10);
scheduleWithFixeDelay
scheduler.scheduleWithFixedDelay(new TimerTask() {
#Override
public void run() {
// Here do something
// This task will run every 10 sec Delay
}
},, 0, 10, TimeUnit.SECONDS);
Find the difference between them Here
Here is an example of a Timer and TimerTask:
private Timer mTimer;
private TimerTask mTimerTask;
private void launchTimerTask() {
mTimer = new Timer();
mTimerTask = new TimerTask() {
#Override
public void run() {
// Perform your recurring method calls in here.
new AsyncLoadGpsDetails().execute(userName);
}
};
mTimer.schedule(mTimerTask, // Task to be executed multiple times
0, // How long to delay in Milliseconds
10000); // How long between iterations in Milliseconds
}
private void finishTimerTask() {
if (mTimerTask != null) {
mTimerTask.cancel();
}
if (mTimer != null) {
mTimer.purge();
mTimer.cancel();
}
}
For the TimerTask you will need the following imports:
import java.util.Timer;
import java.util.TimerTask;
If possible, I would use a ScheduledExecutor (Java Timer vs ExecutorService?). There are many examples around, but here is a quick snippet:
private ScheduledExecutorService mService;
private ScheduledFuture mFuture;
private void launchScheduledExecutor() {
mService = Executors.newSingleThreadScheduledExecutor();
mFuture = mService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// Perform your recurring method calls in here.
new AsyncLoadGpsDetails().execute(userName);
}
},
0, // How long to delay the start
10, // How long between executions
TimeUnit.SECONDS); // The time unit used
}
private void finishScheduledExecutor() {
if (mFuture != null) {
mFuture.cancel(true);
}
if (mService != null) {
mService.shutdown();
}
}
Be sure to shutdown the ExecutorService when you're done.
For the above snippet you'll need the following imports:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
You can call launch anywhere (an onClickListener or onCreate perhaps). Just be sure to call 'finish' at some point or they will run indefinitely (in the onDestroy for example)
Related
We have an app who should process a task every 10 seconds. This should be more or less exact, which means that a difference of 1 or 2 seconds is OK, but not gaps of 20 seconds or more.
This should work regardless if the app is open, in foreground or in background.
We implement this via AlarmManager, but it is not working properly. If the smartphone is not plugged in and it is running in background, there are gaps in the execution.
With Android 4.3., we have gaps (about 30 seconds) from time to time, with Android 5.x we have fewer gaps, but gaps about 5 or 10 minutes long!
I think there must be a way to implement this, an alarm clock is also possible and is exact.
More about the app: It works in a service and a broadcast receiver is implemented. This means the service is restarted if I wipe away the app or restart the handy. This works correctly. The only problem is the 10 second task.
Any hints? How is an alarm clock implemented? Which calls, API?
I tried different ways until now without success.
Thanks
Hans
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
PerformBackgroundTask performBackgroundTask = new PerformBackgroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000); //execute in every 10000 ms
}
You can do it with handler and runnable, which I think is preferred by Android..
public class ActivityMain extends Activity
{
private Handler mainHandler = new Handler();
private Runnable backgroundTask = new Runnable() {
#Override
public void run() {
//do your background task
mainHandler.postDelayed(this, 10000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainHandler.postDelayed(backgroundTask, 10000);
}
}
Use of "AlarmManager" with "broadcast Receiver" and "service". These 3 component will make your requirement fulfill.
Using Alarm Manager to generate a Broadcast Receiver, and from BroadcastReceiver start a Service where you can put your desired code of logic to get your task done in every 10 Seconds.
I want to make an application about mini game.
Detail : In 2 seconds you must to answer a question if you don't answer or the answer is wrong -> Game Over . But if your answer is true the Timer will reset become 0 and countdown again with diffirent question.
I have already seen many code about timer in website but I don't understand clearly about it :(
So I want to ask : How can i set up a timer run only 2 seconds and how can i reset it and continue with a new question ?
Please help me.
you can use CountDownTimer in android like this:
public class Myclass {
myTimer timer =new myTimer(2000,1000);
public void creatQuestion(){
timer.start();
//method you init question and show it to user
}
public void getUserAnswer(/*evry thing you expected*/)
{
//if answer is true call timer.start()
//else call timer.onFinish(); to run onfinish in timer
}
public class myTimer extends CountDownTimer {
public myTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
// you can update ui here
}
#Override
public void onFinish() {
this.cancel();
//fire game over event
}
}
}
i hope it make you satisfy
I've done something similar using Thread/Runnable.
Thread t = new Thread(new Runnable() {
public void run() {
final long startTime = getTime();
final long maxEndTime = startTime + 2000L;
try {
while (shouldContinueWaiting()) {
if (getTime() > maxEndTime) {
throw new TimeoutException();
}
sleep();
}
} catch (InterruptedException e) {
handleInterrupt();
} catch (TimeoutException e) {
handleTimeout();
}
}
boolean shouldContinueWaiting() {
// Has the user already answered?
}
void handleInterrupt() {
// The user has answered. Dispose of this thread.
}
void handleTimeout() {
// User didn't answer in time
}
void sleep() throws InterruptedException {
Thread.sleep(SLEEP_DURATION_IN_MILLIS);
}
void getTime() {
return System.currentTimeMillis();
}
then you can start/restart the thread by:
t = new Thread(same as above...);
t.start();
and stop by:
t.interrupt();
We want to use the Timer class.
private Timer timer;
When you're ready for the timer to start counting -- let's say it's after you press a certain button -- do this to start it:
timer = new Timer();
timer.scheduleAtFixedRate(incrementTime(), 0, 100);
The first line is us creating a new Timer. Pretty standard. The second line, however, is the one I wanted you to see.
incrementTime() is a method that is called at the end of every "tick" of the clock. This method can be called whatever you want, but it has to return an instance of TimerTask. You could even make an anonymous interface if you want, but I prefer moving it off into its own section of code.
The 0 is our starting location. We start counting from here. Simple.
The 100 is how large a "tick" of the clock is (in milliseconds). Here, it's every 100 milliseconds, or every 1/10 of a second. I used this value at the time of writing this code because I was making a stopwatch application and I wanted my clock to change every 0.1 seconds.
As for your project, I'd suggest making the timer's task be your question switch method. Make it happen every 2000 milliseconds, or 2 seconds.
You can use a Handler.
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
//this will happen after 2000 ms
}
}, 2000);
Maybe this can help you:
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// FIRE GAME OVER
handler.postDelayed(this, 2000); // set time here to refresh textView
}
});
You can fire your game over after 2000 milliseconds.
If you get the question correct -> remove callback from handler and reset it when the next question starts.
I have this AsyncTask, that sleeps 0.1 second each time that executes "doInBackground", before that I was using a CountDownTimer to control my time.
My problem is: I want to achieve a timer that can Pause without calling .cancel() and when starts creating another timer.
Is there a way to achieve this is android? I didn't found how to do it in a different way. Can you example it?
Where I've found examples canceling the timer:
How to stop the Timer in android?
Android timer? How-to?
http://www.androidhub4you.com/2013/04/countdown-demo-in-android-custom-timer.html
EDIT
Answering Kevin Krumwiede: This project is a kind of game, that I must hit blocks in a determinated time, so I want to achieve a way to stop the timer when the player use some kind of special power (hit a button specified).
EDIT2
Answering Kushal: I don't know if you have compiled this code, but I can't use the task1 variable. Here goes the code:
public void doIt(){
final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
final Runnable task =
new Runnable() {
#Override
public void run() {
timerAsyncTask.execute();
if(true) {
exec.shutdown(); // shutdown this execution
//exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);
}
}
};
exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS);
}
Here exec = Executors.newSingleThreadScheduledExecutor(); it shows me an error:
Error:(33, 21) error: cannot assign a value to final variable exec
What I think it's pretty okay, once the exec is a final variable.
And here exec.scheduleAtFixedRate(task, 0, 100, TimeUnit.MILLISECONDS); I got another error:
Error:(34, 46) error: variable task might not have been initialized
Can you explain, how can I use this piece of code? I'm quite new to android.
Thanks.
I suggest you avoid Timers in Android altogether. Android has a light weight and better solution called Handler
You can find a comparison between these two here. To sum up
Comparison Handler VS Timer
While rescheduling Handler is very easy, you can not reschedule Timer
In Handler you can attach to any Runnable but Timer schedule for only
one TimerTask
TimerTask is purely background task so you can not update
UserInterface, but that's not true for Handler's Runnables
Timer Causes Execptions
Timer tends to leak more memory compare to Handler see the graph of
object retains by timer and Handler. It will increase rapidly for
Timer if you are creating and scheduling new task.
As the post suggests, the Handler usage is pretty simple. Here is an example code
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
public class TestActivity extends AppCompatActivity {
private static int INITIAL_TIMER_DELAY = 100;
private static int TIMER_PERIOD = 100;
private android.os.Handler handler;
private Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler(Looper.getMainLooper());
runnable = new Runnable() {
#Override
public void run() {
// Do something and reschedule ourself
handler.postDelayed(this, TIMER_PERIOD);
}
};
handler.postDelayed(runnable, INITIAL_TIMER_DELAY);
}
#Override
protected void onDestroy() {
super.onDestroy();
cancelTimer();
}
private void cancelTimer() {
if (handler != null) {
handler.removeCallbacks(runnable);
}
}
private void rescheduleRunnable() {
handler.postDelayed(runnable, INITIAL_TIMER_DELAY)
}
}
You can achieve your requriment using ScheduledExecutorService class
Basic difference between ScheduledExecutorService and Timer class is :
Using Timer class, you cannot check how your execution is going. You can start and stop execution but cannot check execution based on condition
ScheduledExecutorService provides way to check how execution is running in between start and stop call. If any execution of the task encounters an exception, subsequent executions are suppressed
How we can achieve your requirement :
We need 0.1 second delay between doInBackground() execution
We shall be able to pause our execution when other execution starts
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
Runnable task1 = new Runnable() {
public void run() {
// start your AsyncTask here
new <your_task>().execute();
if (<check_your_condition_when_to_pause>) {
exec.shutdown(); // shutdown this execution
exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(task1, 0, 100, TimeUnit.MILLISECONDS);
// here i have passed task1 for example
// here we need to pass next task runnable which
// we want to run after 0.1 seconds
} else {
// continue normal
}
}
};
exec.scheduleAtFixedRate(task1, 0, 100, TimeUnit.MILLISECONDS);
Credit reference : Answer 1 and Answer 2
I hope this will help to solve some of your doubts
What I want to do is just a basic implementation of handler example. I have a TextView on the mainActivity, and once the page loads the handler is supposed to run and show the user value coming from SystemClock.uptimeMillis. But ıt doesn't work more than once. How can I make this code run?
public class MainActivity extends Activity {
long uptoMS=0L;
TextView tv;
Handler handler=new Handler();
long swaptime=0L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
uptoMS=SystemClock.uptimeMillis();
tv.setText(String.valueOf(uptoMS));
handler.post(runner);
}
private Runnable runner=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
swaptime+=uptoMS;
tv.setTag(String.valueOf(swaptime));
handler.post(this);
}
};
}
See this below example
scheduler(){
TimerTask tasknew = new TimerSchedulePeriod();
Timer timer = new Timer();
// scheduling the task at interval
timer.schedule(tasknew,100, 100);
}
// this method performs the task
public void run() {
System.out.println("timer working");
}
timer = new Timer();
refreshTask = new TimerTask() {
#Override
public void run() {
swaptime+=uptoMS;
tv.setTag(String.valueOf(swaptime));
handler.post(this);
}
};
timer.schedule(refreshTask,
100, 100);
Well, there some problems with your code.
Firstly, you use setTag() instead of setText(), so the value will never update.
tv.setTag(String.valueOf(swaptime));
Secondly, you get uptoMS once in onCreate(), and then you use it in every "handler loop". I don't know what you try to achive but it's unlike that you want this.
Thirdly, you instantly repost your Runnable, so the main thread's message queue will be busy. You should give some break instead of instant reposting. For example you can wait 100 ms between the updates, so the TextView will be updated 10 times in every second.
handler.postDelayed(this, 100);
And finally, however others suggest you using Timer, just ignore them. Handler is the Android way to achieve tasks like this.
public void scheduleAtFixedRate (TimerTask task, long delay, long period). This looks promising but i have no idea how to use it. Any help would be appreciated.It was on android developer site.
Maybe this demo helps you:
import java.util.*;
public class TimerDemo {
public static void main(String[] args) {
TimerTask tasknew = new TimerScheduleFixedRateDelay();
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
}
public void run() {
System.out.println("working at fixed rate delay");
}
}
You need to have a method called "run" in your class, that will be repeately executed.
Source.
You can create a timer task and schedule it at a fixed rate like this:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
// This method is called in a fixed interval
}
};
timer.scheduleAtFixedRate(task, delay, period);
If you need to interact with the UI in the TimerTask you should do it like this:
TimerTask task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// Interact with UI here
}
});
}
};
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Android doc here.
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
The task (TimerTask) is the code which will be executed forever, every period milliseconds. Delay is the time (in ms or Date if you want) which the Timer should wait until the start of the TimerTask.
You should remember Timer will run in a different thread from UI thread, so if you need to update the UI you should use runOnUiThread etc. (See Xaver Kapeller answer)
It could be an example
TimerTask tasknew = new TimerTask()
{
#Override
public void run()
{
/* Something here */
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 500, 1000);
I noticed here everyone just posted an example so it's just an extension with an explanation.