I am looking for the method to update the screen at a constant rate, say every 50mSec.
In the embedded world I would configure a timer to trigger an interrupt every 50mSec and the ISR would handle the update. What I have in mind for Android is to have a FrameLayout with a number of view items registered to react to some sort of callback from a timer function.
Hopefully someone will understand my question and point me in the right direction.
You may use handler.postDelayed in a Runnable to call it after certain time period.
For example:
handler.post(new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 50);
//do your task
}
});
Make sure you handler is attached to a separate (non-UI) thread and when it comes to update UI elements you always do it on a UI thread.
Related
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();
Given that posting a task with post() puts the Runnable in a queue, is there any difference between
protected void onCreate(Bundle savedInstanceState) {
Log.d("UI thread", "Do something");
}
and
protected void onCreate(Bundle savedInstanceState) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d("UI thread", "Do something");
}
});
}
?
In both cases, there should only be one thread running and no concurrency happening - right?
Then what's the benefit in creating a handler that attaches to the UI thread and running tasks on it?
The timing is different. In the first snippet the code is executed as part of the onCreate execution so it is guaranteed to finish before onCreate returns, in the second snippet, it is executed some time later (maybe after several other callbacks).
Then what's the benefit in creating a handler that attaches to the UI thread and running tasks on it?
Your example provides only a minimal "use case" which most developers may never experience. In your example, you might want to start a background service but you wanted to ensure that the method that starts the service completes before performing that work, your example would accomplish that. Additionally, you might want to ensure that the service construction is prioritized on the main/UI thread. This approach means you don't have to add a comment like "put this code at the end of this method" or have other "inherent code dependencies" - the call to the handler guarantees post-method/end of method execution. Not really "normal" so...
A more useful example is when you have a background thread that needs to update the UI. It can do the necessary processing in the background, then create a handler that will execute on the UI thread appropriately. This is very common and is implemented in AsyncTask for example (in its getMainHandler() method - https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/AsyncTask.java#L282)
Also, handlers allow for post-delayed execution of Runnables. A post-delayed execution is often beneficial for situations where immediate screen display is more important than complete screen display. In most cases a developer should "bake-in" a delay and have the screen show a loading spinner or some other UI/UX decoration, but if there isn't a requirement to specify the length of the delay, the example you gave would post the runnable on the main thread looper queue to execute ASAP. That might be exactly what you want to do, or it might be confusing to other developers that might have to maintain your code (for example, the reason you asked this question).
I have a set of instructions that needs to be executed repeatedly.
The repeat delay is variable (the delay is taken from a file).
The repeat time must be very precise (milliseconds precision).
I have tried to use a Handler with postDelayed but the accuracy is lost in time. This happens because the repeat frequency is more than 10 times/second.
Any idea is more than welcomed!
Here is the Handler example:
new Runnable() {
#Override
public void run() {
mHandler.postDelayed(this, delay);
barometerResult.gotBarometer(barometerValueModelList.get(i).getBarometerValue());
}
}.run();
I don't think it's a good idea using Handler, it runs in the UI thread with many other things to do in the queue, so that's not guarantee your runnable code would be executed so precisely.
If your work in the Runnable is just some logic task not involved in update UI.Consider using a Timer to do that but be ware that it will run on a separated thread.
I'm new to android, I need to start a Thread Multiple times to do a regular work as the listen a thing. But I searched and found that can't do this. So I decided to put
while(true){
listen some thing
do another something depends for listen
}
in the run() method.
But How can I implements this idea? Is it possible ? and How?
You should use Handler.post() whenever you want to do operations in the UI thread.
So let's say in the callback (which is running in separate thread) you want to change a TextView's text, you should use Handler.post(). In Android, as in many other UI frameworks, UI elements (widgets) can be only modified from main thread.
mHandler = new Handler();
new Thread(new Runnable(
#Override
public void run () {
// Perform long-running task here
// (like audio buffering).
// you may want to update some progress
// bar every second, so use handler:
mHandler.post(new Runnable() {
#Override
public void run () {
// make operation on UI - on example
// on progress bar.
}
});
}
)).start();
Of course, if the task you want to perform is really long and there is a risk user might switch to some another app in the meantime, you should consider using Service.
If you start your thread inside a while loop with true condition, it'll kill your device. You'r device will hang. Your code should be event triggered. You can have a Service running in the background to do that and listen for your events.
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.