Do after specific time, Android Runnable - android

Ive got an app with a class that implements Runnable. Where a thread is started and the run() methid overridden. This runs my graphics.
1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.

1.st question : how often is the run() called upon? i havent set a time for this so it must be a default value?
The run() method in your Thread is called when you call it eg. yourThread.start();
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc. What would be the best way to go about doing this, i was thinking about using an int as an counter and once it hits a specific value does what i want.
There are to options. Either you could call Thread.sleep() method (NB: Never do this in your UI thread).
Or you can do it the way you described above. So in your run() method you would have a while() loop and check on every iteration if the difference of the lastUpdate and the current time in milli seconds is bigger than the wanted period eg. 2 min, 5 min or 10 min.
I hope this helps.

Regarding question 2 - use ScheduledExecutor

1.st question : how often is the run() called upon?
You can find out for yourself, put this at the start of your Runnable:
Log.v("Running Runnable", System.currentTimeMillis() + "");
2.nd question : i want stuff to be done after a certain amount of time (2min,5min,10min) etc.
Extend a HandlerThread (it initializes the Looper for you!), add a Handler as a class variable, and use the Handler's postDelayed() or postAtTime() methods.

The exact amount of time in between calls to run() depends on the processor. The time between each call is the sort of thing that's really visible by the nanosecond. If you're trying to create a timer, I'd recommend using System.currentTimeMillis(), calling it in the run() method, and once the difference is greater than or equal to 1000 milliseconds, the actual timer decrements by one. This will keep track of seconds, and you can use it as a base for minutes and generating other events at specific times.

Related

How to run repeated tasks with handler

I have a retrofit api that checks the status of the order.
For example, store_status is the variable that i am checking.
Default value of store_status is 0.
What i want to do is:
I want to check the value of this variable again and again for example in every 2 seconds till it returns value as 1. (The status is being updated from another app)
Also, i want a timer like if after checking the status for 3 mins again and again if it does not outputs the value as 1 the handler should stop and i want to update the value of store_status as 2 in database after 3 mins.
I have read post telling how to work with handler and how to run repeated tasks but i was not able to find to stop it automatically after like 3 mins and do something after that.
Can some one help with this task in both aspects?
You can use Count Down Timer in Android which internally uses Handler, Runnable
Check it out here

AppWidget double update or static field?

I have an AppWidget that may receive two consecutive update request. To be shown it has to programmatically draw five 50x50 bitmaps, setting some PendingIntent and get some configuration (just to give you a little idea of the work load). It takes around 60 milliseconds between the two calls.
The option I have found so far to avoid the unnecessary update is to have a static field, something like:
public class myWidget extends AppWidgetProvider {
private static long lastUpdate;
#Override
public void onReceive(Context context, Intent intent) {
if((System.currentTimeMillis()-lastUpdate) > 200) {
doUpdates(context);
}
lastUpdate = System.currentTimeMillis();
}
}
With performance and "best practice" in mind...
Which do you think is the best solution in this case?
1) Use the static field (like in the example)
2) Just let the widget update twice
3) Other
In other words, is the use of the static field more harmful than just letting the widget update twice?
To be shown it has to programmatically draw five 50x50 bitmaps, setting some PendingIntent and get some configuration (just to give you a little idea of the work load). It takes around 60 milliseconds between the two calls.
Note that this will cause your UI to drop frames if you happen to have your UI in the foreground at the time the update request(s) come in.
Which do you think is the best solution in this case?
Both #1 and #2.
There is no guarantee that your process will still be around between the two subsequent update requests. Probably it will be around, given that you appear to be optimizing for two updates within 200ms. But it's not guaranteed. So, use the static data member for optimization purposes, but ensure that your code will survive the process being terminated in between.
I'd suggest using SystemClock.elapsedRealtime(), though, instead of System.currentTimeMillis(). System.currentTimeMillis() is based on the real-time clock, which can be adjusted on the fly (e.g., NITZ signals, SNTP updates, user manually changing the clock). SystemClock.elapsedRealtime() is guaranteed to be monotonically increasing, and so it is a better choice for this sort of scenario. Only use SystemClock.elapsedRealtime() when you need to tie something to "real world" time (e.g., as part of work with Calendar objects), not for interval timing.

Countdowntimer works in short intervals, but not others

I am facing an interesting situation, maybe someone could explain to me why.
I am doing timer that runs at interval of 100 msec. At every tick, a textview is updated to show the time. Also there is a an edit text with a text watched in which the string is compared 2 times to different strings After each Text changed
When I use Timer class, then the thread seems to be busy because I can't type any text into the edit text . When I use handler same problem happens. But if I use countdowntimer class then it works.
Interestingly, if I increase the interval to 1 sec then all of the above works.
1-is 100 msec too short? I didint think the above computations I making would take that long.
2- why countdowntimer worked and other failed?
Thank you

Understanding Interpolation

I have been reading up on game loops and am having a hard time understanding the concept of interpolation. From what I seen so far, a high level game loop design should look something like the sample below.
ASSUME WE WANT OUR LOOP TO TAKE 50 TICKS
while(true){
beginTime = System.currentTimeMillis();
update();
render();
cycleTime = System.currentTimeMillis() - beginTime;
//if processing is quicker than we need, let the thread take a nap
if(cycleTime < 50)
Thread.sleep(cycleTime);
)
//if processing time is taking too long, update until we are caught up
if(cycleTime > 50){
update();
//handle max update loops here...
}
}
Lets assume that update() and render() both take only 1 tick to complete, leaving us with 49 ticks to sleep. While this is great for our target tick rate, it still results in a 'twitchy' animation due to so much sleep time. To adjust for this, instead of sleeping, I would assume that some kind of rendering should be going on within the first if condition. Most code samples I have found simply pass an interpolated value into the render method like this...
while(true){
beginTime = System.currentTimeMillis();
update();
render(interpolationValue);
cycleTime = System.currentTimeMillis() - beginTime;
//if processing is quicker than we need, let the thread take a nap
if(cycleTime < 50)
Thread.sleep(cycleTime);
)
//if processing time is taking too long, update until we are caught up
if(cycleTime > 50){
update();
//handle max update loops here...
}
interpolationValue = calculateSomeRenderValue();
}
I just don't see how this can work due to the 49 tick sleep time? If anyone knows of an article or sample I can check out please let me know as I am not really sure what the best approach to interpolation is...
I know its a bit late, but hopefully this article will help
http://gameprogrammingpatterns.com/game-loop.html
It explains game time scheduling very well. I think the main reason you are a bit confused is because of passing the render function the current elapsed time. Oh course this depending on which system you are using but conventionally the render doesn't modify the Scene in any way, it only draws it, therefore it doesn't need to know how much time has passed.
However the update call modifies the objects in the scene, and in order to keep them in time (e.g. playing animations, Lerps ect...) then the update function needs to know how much time has passed either globally, or since the last update.
Anyway no point me going to fair into it.... that article is very useful.
Hope this helps

Scheduling an event in Android

What is the best way to schedule an event?
I was thinking about the new Calendar API, but it requires an internet connection at least to create a new calendar.
Is there any API for creating a schedule which doesn't require internet connection?
Check out the FAQ You are more likely to keep getting help if you go back to your previous questions and accept answers that were helpful to you. Also see How does accepting an answer work? for more info.
AlarmManager will let you do that.
If you want to schedule your event for relatively soon though Handler is a better choice. You can use it to post a runnable like this:
Runnable r = new Runnable() {
public void run() {
doSomething();
}
}
Handler h = new Handler();
h.postDelayed(r, 1000);
This will execute the run method of your runnable in one second. You can change the second parameter of the postDelayed method to change the interval of time that passes. It is in milliseconds.
EDIT: Also note that the "best" way to do something is subjective, and generally depends on exactly what you are trying to do. If you can be more specific about what you are trying to schedule and how far in advance you'd like to schedule it then perhaps we can help narrow it down to the "best" choice. But without more info there is no way that we can tell you which is "best"

Categories

Resources