I want my app to make a call to server always in background checking for any updates , I am new to android and not sure how to perform this to start with. I just want a single call always running in background. Please guide me with this to start with.
You can use Async Task for that. In your doInBackground() method, call your service providing some timespan.
Snippet to add timestamp:
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
new AddStringTask().execute();
} }, 0, 5000);
Related
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.
I'm trying to develop a small android App. In that app I need to use Timer control, which will be fired at button click. What problem I'm getting is, First timer task call is working fine but when I'm calling it again my app getting crashes. Code using for timer task is:
Timer timer = new Timer();
TimerTask refreshRam;
final Handler handler = new Handler();
refreshRam = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
txtFreeRam.setText(String.valueOf(getFreeRam()).toString());
}
});
}};
}
timer.schedule(refreshRam, 400);
I want to call my timer task only when I'm clicking on a button. It shouldn't be repeated...
Thanks
Use timer.scheduleatfixedrate instead of schedule
timer.scheduleAtFixedRate(refreshRam,400, 5000);
When you reschedule a Timer, it throws:
java.lang.IllegalStateException: TimerTask is scheduled already
It seems that you can only use a timer for once.
In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:
.
.
.
//first time; works fine!
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);
//second time; also works fine!
//be sure to terminate the timer task that is running by calling timer.cancel()
timer.cancel();
timer = new Timer();
refreshRam = new TimerTask() { ... }
timer.schedule(refreshRam, 400);
On button click I want to begin a timer of 5 minutes and then execute a method that will check for certain conditions and set off alerts if conditions are right. I've seen examples with timers and postDelay, but don't really understand why one would use one vs another. What is the best way to accomplish what I am trying to do? I don't want to lock up the UI during the 5 minutes. The user should be free to use the app as normal during the countdown.
EDIT: I am trying the postDelayed suggestion but visual studio is not liking something about my code. It looks exactly like examples I've found. My be a mono for android thing.
Handler h = new Handler();
Runnable r = new Runnable(){
public void run()
{
Dialog d = inst2.showBuilder(this, "test", "test");
d.Show();
}
};
h.postDelayed(r, 5000);
Specifically the code block inside of run throws all kinds of "} expected" and "a namespace cannot directly contain members such as fields or methods" exceptions.
Try using Timer Object :
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask()
{
#Override
public void run()
{
// Your code goes here
}
}, 1000); // 1sec
final Handler handler = new Handler();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
handler.post(new Runnable()
{
public void run()
{
// YOUR Code
}
});
}
}, 1000); // 1sec
You can start a simple Thread that will sleep in background for 5 minutes and then call a function. While the thread sleeps in background the UI will not freeze. When the thread finish executing what you want you can set off alerts by sending some intents as notifications and receive them in some Broadcast Receivers.
Hope this helps
Use Handler.postDelayed(Runnable block); method to execute delay, as android also not recommend to use timer.
Handler h = new Handler();
Action myAction = () =>
{
// your code that you want to delay here
};
h.PostDelayed(myAction, 1000);
I'm calling my TimerTask (m_timer) upon a button click:
m_timer.schedule(m_progressUpdater, 0, 500);
Which kicks off my run method:
#Override
public void run() {
//do some stuff
progressBar.setProgress(currentProgress);
if (progress >= 100) {
handler.post(new Runnable() {
#Override
public void run() {
CompleteTask();
}
});
}
}
I can call this once and it works perfectly. When I call it again, my app stops responding. I'm thinking that I need to cancel the task in my CompleteTask() method, but I've tried cancelling both the TimerTask and the Timer, and it still crashes. Anyone know what the problem might be?
Have you tried creating new TimerTask instance for the second call? And by the way, don't cancel the timer otherwise it will cancel all of its task. And what did the log say?
When you reschedule a Timer, it throws:
java.lang.IllegalStateException: TimerTask is scheduled already
It seems that you can only use a timer for once.
In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:
// if you have already started a TimerTask,
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
m_timer.cancel();
m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);
I am currently trying to set up a WiFi Scan in my Android application that scans for WiFi access points every 30 seconds.
I have used Timer and TimerTask to get the scan running correctly at the intervals which I require.
However I want to be able to stop and start the scanning when the user presses a button and I am currently having trouble stopping and then restarting the Timer and TimerTask.
Here is my code
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
wifiManager.scan(context);
Log.d("TIMER", "Timer set off");
}
});
}};
t.schedule(scanTask, 300, 30000);
}
public void stopScan(){
if(scanTask!=null){
Log.d("TIMER", "timer canceled");
scanTask.cancel();
}
}
So the Timer and Task start fine and the scan happens every 30 seconds however I cant get it to stop, I can stop the Timer but the task still occurs and scanTask.cancel() doesn't seem to work either.
Is there a better way to do this? Or am I missing something in the Timer/TimerTask classes?
You might consider:
Examining the boolean result from calling cancel() on your task, as it should indicate if your request succeeds or fails
Try purge() or cancel() on the Timer instead of the TimerTask
If you do not necessarily need Timer and TimerTask, you can always use postDelayed() (available on Handler and on any View). This will schedule a Runnable to be executed on the UI thread after a delay. To have it recur, simply have it schedule itself again after doing your periodic bit of work. You can then monitor a boolean flag to indicate when this process should end. For example:
private Runnable onEverySecond=new Runnable() {
public void run() {
// do real work here
if (!isPaused) {
someLikelyWidget.postDelayed(onEverySecond, 1000);
}
}
};
using your code, instead of
scanTask.cancel();
the correct way is to cancel your timer (not timerTask):
t.cancel();
The Android documentation says that cancel() Cancels the Timer and all scheduled tasks. If there is a currently running task it is not affected. No more tasks may be scheduled on this Timer. Subsequent calls do nothing. Which explains the issue.