Do an operation every 100ms for 1000 ms - android

I would like to do an operation every 100ms for 1000ms.
I believe I would need to use the
handler
How do I do that?

Handler h = new Handler();
int count = 0;
int delay = 100;//milli seconds
long now = 0;
h.postDelayed(new Runnable(){
public void run(){
now = System.currentTimeMillis();
//do something
if(10>count++)
h.postAtTime(this, now + delay);
},
delay};
Please note that your operation MUST take less then 100ms to execute or it will not be able to run every 100ms, this will be the case for all methods.

Timer t = new Timer();
int count = 0;
t.scheduleAtFixedRate(new TimerTask() {
count++;
// Do stuff
if (count >= 10)
t.cancel();
}, 0, 100);
This schedules a timer to execute a TimerTask, with a 0 millisecond delay. It will execute the body of the TimerTask every 100 milliseconds. Using count to keep track of where you are in the task, after 10 iterations, you may cancel the timer.
As #Jug6ernaut mentioned, ensure your task won't take long to execute. Lengthy tasks (ones that take longer than 100 milliseconds, in your case) will cause lag/potentially undesirable results.

You can do this by using a Timer.

I don't have time to test this right now, but this should work
This is one way:
Your methods you want to call from here will probably need to be static
This class can be nested in another class
You could use % (modulus) so the timer can keep counting up and you can set things to happen at more intervals
create this timer:
private Timer mTimer = new Timer();
to start this timer:
mTimer.scheduleAtFixedRate(new MyTask(), 0, 100L);
the timer class:
/**
* Nested timer to call the task
*/
private class MyTask extends TimerTask {
#Override
public void run() {
try {
counter++;
//call your method that you want to do every 100ms
if (counter == 10) {
counter = 0;
//call method you wanted every 1000ms
}
Thread.sleep(100);
} catch (Throwable t) {
//handle this - maybe by starting it back up again
}
}
}

Related

How to stop my timer after 3 seconds?

I have a textview, and I'm highlighting it dynamically (first 110 letters are highlighted first then after 1 second next 110 letters are highlighted and so on..). Below is my code for it.
I just created background thread as timer, but it is not stopping at all. How do I stop the timer after 3 iterations? Thanks in advance...
int x=0;,y=110//global values
Timer timer = new Timer();
//Create a task which the timer will execute. This should be an implementation of the TimerTask interface.
//I have created an inner class below which fits the bill.
MyTimer mt = new MyTimer();
//We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
timer.schedule(mt, 1000, 1000);
class MyTimer extends TimerTask {
public void run() {
//This runs in a background thread.
//We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
if(x==330)
Thread.currentThread().destroy();
runOnUiThread(new Runnable() {
public void run() {
Spannable WordtoSpan = new SpannableString(names[0]);
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), x, y, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
x=x+110;
y=y+110;
textView.setText(WordtoSpan);
}
});
}
}
did you try Handler instead of timer Task?
private static int TIME_OUT = 3000;
//--------------
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// do your task here
}
}, TIME_OUT);
There are some disadvantages of using Timer
It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer. It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run

Android Timer Schedule

Following is the code snippet which I am using in my project to schedule a task
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
//Do Something
}
}, interval, interval);
This works fine. I get event after mentioned interval. But this fails to send any event if date is set smaller than current from settings.
Does any one know why this behavior is happening?
Timer fails when you change the system clock because it's based on System.currentTimeMillis(), which is not monotonic.
Timer is not an Android class. It's a Java class that exists in the Android API to support existing non-Android libraries. It's almost always a bad idea to use a Timer in your new Android code. Use a Handler for timed events that occur within the lifetime of your app's activities or services. Handler is based on SystemClock.uptimeMillis(), which is monotonic. Use an Alarm for timed events that should occur even if your app is not running.
Use this code.. this will help you..
Timer t;
seconds = 10;
public void startTimer() {
t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (seconds == 0) {
t.cancel();
seconds = 10;
// DO SOMETHING HERE AFTER 10 SECONDS
Toast.makeText(this,"Time up",Toast.LENGTH_SHORT).show();
}
seconds -= 1;
}
});
}
}, 0, 1000);
}

Call a method in variable period on everytime? [duplicate]

This question already exists:
Timer time does not change as variable?
Closed 9 years ago.
I have to call some webservice method in variable times, every time method runs it returns me next period time as long. I tried it with timer but after first calling, it can not understand new variable time.
This is the link asked yesterday something about it: Timer time does not change as variable?
Here is the sample code:
private int V_Time = 1;
.
.
.
try {
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
V_Handler.post(new Runnable() {
public void run() {
webservice_method();
V_Time = 2; // it returns from method, not manually right as shown
//and it can be change every time method calls..
}
});
}
}, 0, V_Time * 1000 * 60);
} catch (Exception hata) {
}
It works first time after 1 minute, but others does not change (eg 2 min), it works every 1 minute.
I want just it works properly, with timer or without timer with anything else...
I think I may cancel timer but I guess I cannot resume or restart it again.
It must be something to do what I want, but I do not to know how?
I want to change period time, every timer task run what return from method.
What you are trying to achieve is impossible. You have to cancel the current task and reschedule a new one with the new interval.
private TimerTask mTask = new TimerTask() {
#Override
public void run() {
V_Handler.post(new Runnable() {
public void run() {
webservice_method();
V_Time = 2; // it returns from method, not manually right as shown
//and it can be change every time method calls..
V_Timer.cancel();
V_Timer.scheduleAtFixedRate(mTask, 0, V_Time * 1000 * 60);
}
});
}
}
try {
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(mTask, 0, V_Time * 1000 * 60);
} catch (Exception hata) {
}

Android - Run a thread repeatingly within a timer

First of all, I could not even chose the method to use, i'm reading for hours now and someone says use 'Handlers', someone says use 'Timer'. Here's what I try to achieve:
At preferences, theres a setting(checkbox) which to enable / disable the repeating job. As that checkbox is checked, the timer should start to work and the thread should be executed every x seconds. As checkbox is unchecked, timer should stop.
Here's my code:
Checking whether if checkbox is checked or not, if checked 'refreshAllServers' void will be executed which does the job with timer.
boolean CheckboxPreference = prefs.getBoolean("checkboxPref", true);
if(CheckboxPreference == true) {
Main main = new Main();
main.refreshAllServers("start");
} else {
Main main = new Main();
main.refreshAllServers("stop");
}
The refreshAllServers void that does the timer job:
public void refreshAllServers(String start) {
if(start == "start") {
// Start the timer which will repeatingly execute the thread
} else {
// stop the timer
}
And here's how I execute my thread: (Works well without timer)
Thread myThread = new MyThread(-5);
myThread.start();
What I tried?
I tried any example I could see from Google (handlers, timer) none of them worked, I managed to start the timer once but stoping it did not work.
The simpliest & understandable code I saw in my research was this:
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
// your code here
}
},
5000
);
Just simply use below snippet
private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
runnable.run();
To stop it use
handler.removeCallbacks(runnable);
Should do the trick.
Use a CountDownTimer. The way it works is it will call a method on each tick of the timer, and another method when the timer ends. At which point you can restart if needed. Also I think you should probably be kicking off AsyncTask rather than threads. Please don't try to manage your own threads in Android. Try as below. Its runs like a clock.
CountDownTimer myCountdownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// Kick off your AsyncTask here.
}
public void onFinish() {
mTextField.setText("done!");
// the 30 seconds is up now so do make any checks you need here.
}
}.start();
I would think to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html
If checkbox is on call method where
AlarmManager alarmManager = (AlarmManager)SecureDocApplication.getContext()
.getSystemService(Context.ALARM_SERVICE);
PendingIntent myService = PendingIntent.getService(context, 0,
new Intent(context, MyService.class), 0);
long triggerAtTime = 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 5000 /* 5 sec*/,
myService);
If checkbox is off cancel alarm manager
alarmManager.cancel(myService);
"[ScheduledThreadPoolExecutor] class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required."
per...
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
It's not much more than the handler, but has the option of running exactly every so often (vice a delay after each computation completion).
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
...
final int THREAD_POOL_SIZE = 10;
final int START_DELAY = 0;
final int TIME_PERIOD = 5;
final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
ScheduledThreadPoolExecutor pool;
Runnable myPeriodicThread = new Runnable() {
#Override
public void run() {
refreshAllServers();
}
};
public void startTimer(){
pool.scheduleAtFixedRate(myPeriodicThread,
START_DELAY,
TIME_PERIOD,
TIME_UNIT);
}
public void stopTimer(){
pool.shutdownNow();
}
Thanks to everyone, I fixed this issue with using Timer.
timer = new Timer();
timer.scheduleAtFixedRate(
new java.util.TimerTask() {
#Override
public void run() {
for (int i = 0; i < server_amount; i++) {
servers[i] = "Updating...";
handler.sendEmptyMessage(0);
new MyThread(i).start();
}
}
},
2000, 5000);

How to change a TextView every second in Android

I've made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make the activity Runnable and put this in run():
int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
Thread.sleep(1000);
position = MPService.getSongPosition();
} catch (InterruptedException e) {
return;
}
// ... convert position to formatted minutes:seconds string ...
currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?
new code:
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
public void run() {
final int start = startTime;
int millis = appService.getSongPosition() - start;
int seconds = (int) ((millis / 1000) % 60);
int minutes = (int) ((millis / 1000) / 60);
Log.d("seconds",Integer.toString(seconds)); // no problem here
if (seconds < 10) {
// this is hit, yet the text never changes from the original value of 0:00
currentTime.setText(String.format("%d:0%d",minutes,seconds));
} else {
currentTime.setText(String.format("%d:%d",minutes,seconds));
}
timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
}
};
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService();
// start playing the song, etc.
if (startTime == 0) {
startTime = appService.getSongPosition();
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime,1000);
}
}
what about this:
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
//your code
}
}, delay, period);
Use a Timer for this (instead of a while loop with a Thread.Sleep in it). See this article for an example of how to use a timer to update a UI element periodically:
Updating the UI from a timer
Edit: updated way-back link, thanks to Arialdo: http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html
Edit 2: non way-back link, thanks to gatoatigrado: http://android-developers.blogspot.com/2007/11/stitch-in-time.html
You have to use a handler to handle the interaction with the GUI. Specifically a thread cannot touch ANYTHING on the main thread. You do something in a thread and if you NEED something to be changed in your main thread, then you call a handler and do it there.
Specifically it would look something like this:
Thread t = new Thread(new Runnable(){
... do stuff here
Handler.postMessage();
}
Then somewhere else in your code, you do
Handler h = new Handler(){
something something...
modify ui element here
}
Idea its like this, thread does something, notifies the handler, the handler then takes this message and does something like update a textview on the UI thread.
This is one more Timer example and I'm using this code in my project.
https://stackoverflow.com/a/18028882/1265456
I think the below blog article clearly gives a very nice solution. Especially, if you are a background service and want to regularly update your UI from this service using a timer-like functionality.
It really helped me, much more than the 2007 blog link posted by MusiGenesis above.
https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/

Categories

Resources