How to update widget per second in android? - android

How to update widget per second ?
I used AlarmManager but it only works on below kitkat version.

Here, i am making user wait for 30 seconds on a screen and hiding the view and hitting service when it finishes. You can customize according to your need.
CountDownTimer timer = new CountDownTimer(31000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timer_text.setText("Remaining Seconds. " + millisUntilFinished / 1000 + " s");
if (count >= 30) {
} else {
count++;
}
}
#Override
public void onFinish() {
timer_text.setVisibility(View.GONE);
/// VOLLEY SERVICE
}
}.start();

AlarmManager cannot have a timeout less than 20 seconds. Any timeout less than that will be rounded up.
First off, I would question whether you actually need it updated every second. That's an incredible amount of processing power used, and pretty much against the idea of a widget. If it needs to be updated that frequently it should be an app. If your updates are coming from a server and you want to display them immediately, look into push messaging instead. Then you only need to update when you receive a message, no alarms or timers needed.
Secondly- the way you do a timer for short periods like that is via Handler.postDelayed. It can have a much smaller resolution. However it may not run if the phone is asleep.

Related

Timer anti cheat technique

Let's say I'm developing a game and there exists such thing as respawn. The user may respawn after 15 minutes. Is there any common practice to avoid time cheating? I mean, nothing can stop user from changing system time and set it to future. I know, partially this can be resolved by using server side, but nothing can stop user from disabling the network at all.
PS. the game is cross platform so the solution is interesting for both antroid and iOS. PS2. I know a couple of games that have the solution.
For something like this you could simply start your own timer completely separate from the system time. If you start a 15 minute countdown when a player dies they won't be able to modify your internal timer. I'm not as familiar with iOS dev (NSTimer looks like a possibility) but I know in Android it's as easy as:
// create 30 second internal countdown timer
new CountDownTimer(30000, 3000) {
public void onTick(long millisUntilFinished) {
// store time remaining in database every 3 seconds in case user exits the game
dbHelper.updateDeathTimer(millisUntilFinished);
}
public void onFinish() {
// player respawns now
}
}.start();
To combat the issue of players closing the game I would suggest you also set up your internal timer to cache its' current state in the database at a regular interval, say every 30 seconds or so if you were going to stick with a 15 minute timer.
Below is some psuedocode for what it might look like when a player exits the game while they are dead and our respawn timer was still in progress.
// When game resumes check database and begin updated death timer if necessary
onGameResume() {
if(dbHelper.isUserDead()) {
// resume respawn timer
new CountDownTimer(dbHelper.getRespawnTime(), 15000) {
public void onTick(long millisUntilFinished) {
// store time remaining in database every 15 seconds in case user exits the game
dbHelper.updateDeathTimer(millisUntilFinished);
}
public void onFinish() {
// player respawns now
}
}.start();
}
}
You can store the time of the event (spawn in your case), and then run a timeIntervalSinceReferenceDate against it and see if it exceeds your limit (15 minutes).
The risk on the iOS side is that the app goes to the background and the timers stop.
It's not actually the answer, but just an idea.
What if we use tickCount? Each operating system has this property.
For instance, android.os.SystemClock.elapsedRealtime() in Android and
[NSProcessInfo processInfo].systemUptime in iOS
They should give required values.

Is it possible to create alarm which run every second?

Hello Guys
I want to create an alarm which run every second . I have searched many code but fond no solution , Please suggest some references .
Thanks
Amit Sharma
You can do this, create a CountDownTimer , say how long you want it to last for in the first param (in milliseconds), then set a period of time to run a piece of code in the second param. In the onTick() method, this is the code that will run in the interval specified in the second param, onFinish() is called when the period of the countdown is finished. Call the start() method on the CountDownTimer object when you want it to run.
int howLongTimerLastsInMilliseconds = 3000 // 3000 milliseconds
int tickEverySecond = 1000 // 1000 milliseconds == 1 second
CountDownTimer countDownTimer = new CountDownTimer(howLongTimerLastsInMilliseconds,tickEverySecond ) {
#Override
public void onTick(long millisUntilFinished) {
//do some work every second
}
#Override
public void onFinish() {
//do something when the time is up
}
};
countDownTimer.start();
According to the documentation:
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS
will shift alarms in order to minimize wakeups and battery use. There
are new APIs to support applications which need strict delivery
guarantees; see setWindow(int, long, long, PendingIntent) and
setExact(int, long, PendingIntent). Applications whose
targetSdkVersion is earlier than API 19 will continue to see the
previous behavior in which all alarms are delivered exactly when
requested.
Also this question was rised at code.googls.com and here is an explanation of it:
Suspiciously short interval 5000 millis; expanding to 60 seconds
This is working as intended, though is at present inadequately
documented (and we're aware of that side of the problem). Speaking
very generally: short-period and near-future alarms are startlingly
costly in battery; apps that require short-period or near-future work
should use other mechanisms to schedule their activity.
So, there is no inbuild way how to solve your issue using Alarm. And you should look out for another mechanisms or (very rough solution) use 60 independent alarms

How to make Android custom clock time accurate?

I made a appWidget which show the current time of the server(2012-08-29, 12:00:08 for example). I request the server time every fix duration(1 hour for example). If receives the server time, updates the appWidget display. During the duration, I launch a Handler to update the time like this:
mTick = new Runnable() {
public void run() {
mMillis += 1000;
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
}
mTicker.run();
My questions:
1 After a long time(one day elapsed), The time displayed in AppWidget is slow than the real server time.
I doubt that my method used above is not accurate enough to update the time.
Any suggestions about this problem?
You should not use SystemClock.uptimeMillis() because it does not include time spent in deep sleep, thats why your app widget is out of sync.
You should use SystemClock.elapsedRealtime() call instead
Upd: sorry, I think I misunderstand the problem here. What you are trying to do is to use postAtTime to post runnable after some time in future. Please notice that postAtTime does not include time when device is in deep sleep.
What you need is to track accurate ammount of deltas between redrawing of your widget. You should use SystemClock.elapsedRealtime() for that.
Algorithm should be like this:
long serverTime = getServerTime();
long lastTime = SystemClock.elapsedRealtime();
// Somewhere in updateWidget() or call on timer:
serverTime = serverTime + SystemClock.elapsedRealtime() - lastTime;
lastTime = SystemClock.elapsedRealtime();
// At this moment in serverTime variable you have "server" time adjusted by the time which passed on device, including time spent in deep sleep

Precision of delay

I have a problem with this code used for Android (Java)
handler.postDelayed(new Runnable(){
public void run(){
// Your code goes here...
}
}, 500);
If the delay is about 500ms then the program seems to repeat the task at 0.5s, but if I change to less than 100ms or even less it does not follow any more. I test the brightness change and for a while it can repeat the change of brightness at that rate, but then slow down and come back to normal flash rate again. It seems unstable. Do you have any code that give exact delay regardless of the load of the phone's CPU.
Many thanks
Not from Java, no; stock Java isn't a real-time system.
Timing precision is subject to the whims of the JVM and the OS's scheduler. You may be able to get incrementally more precise, but there's no guarantee of the kind of precision you're looking for.
You might be able to do something more precise if you use a CountDownTimer which has a periodic tick. Essentially you set it to count down for a period which can be hours if need be, and there are two methods one method is called on each tick, and the other at the end of the timer at which point you could start another one. Anyway you could set the tick to be very fast, and then only kick off the code at the delay point by check the actual time difference in the click. I think thats about the best you could do. Essentially inside the tick you would issue a signal if the right amout of time had actually passed. That signal would either kick off the thread or release something the already running thread was waiting on. What is the value of the CountDownTimer, I guess its just that you can do a very frequent polling, and elapsed time check. Although its not guaranteed, the time between the ticks you can set it to a high frequency and check/poll very frequently. This could lead to a smooth performance not unlike a realtime system. Its more likely to be accurate because its just issuing a signal and not taking up the resources of threading just to issue the signal. You might also try an IntentService to perform the tasks and just call startService(intentToIntentService) each call. See if the threading works better inside a service like IntentService which does queue them up I believe.
Date startDate = new Date();
long startTime = startDate.getTime();
// Tick called every 10th of a second. OnFinish called at Signal.
CountDownTimer ctDownTimer = new CountDownTimer(30000, 100) {
long startIntervalTime=startTime;
public void onTick(long millisUntilFinished) {
Date now = new Date();
long nowTime = now.getTime();
if ((startIntervalTime - nowTime) > 100)
{
issueSignal();
intervalStartTime=nowTime;
}
now=null;
}
public void onFinish() {
Log.d("MyClass", "Done") // Maybe start out.
}
}.start();

Metronome Timer slowdown (via Handler, or Threads too)

I have a simple, classic, statement that every 200 milliseconds plays a sound (a metronome).
I wrote it using Handlers, and then in another way, using Threads.
The problem is the same in both ways: when I press hardware home button, or also simply when I press a button to open a ListView, the metronome terribly slowdown for a while.
This problem (not so strong, but however present) presents also doing nothing and leaving the application in foreground.
Any ideas?
Here's the code:
public class Metronome implements Runnable{
private Handler mHandler = new Handler();
public static long mStartTime;
Main mainContext;
public Metronomo(Main context) {
mainContext = context;
}
public void play() {
mStartTime = System.currentTimeMillis();
mHandler.postDelayed(this, 100);
}
public final void stop(){
mHandler.removeCallbacks(this);
}
public void run(){
//play the ogg file in position 1
mSoundManager.playSound(1);
//reschedule the next playing after 200ms
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 200);
}
};
Are you using some kind of pause statement to wait between beats? You could try basing the timing on multiples of a system clock value instead. That way you may still get beats that occur late (or not at all) but you wouldn't get a slow down. Hope that makes some kind of sense.
This is more of a comment but I don't have enough rep to leave comments just yet.
My phone seems to be able to play midi files, which are a pretty compact way to represent sound, perhaps you could dynamically create one and use that for the metronome? I'm assuming that the synthesis is handled at a lower level than would ordinarily be accessible to you so that the timing would be better, but I don't know that for a fact.
When this play sound is called
mSoundManager.playSound(1);
Android waits until that call is finished, then you call
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 200);
however, if you reverse those calls, you may find that the timing is more accurate.
mHandler.postAtTime(this, SystemClock.uptimeMillis() + 200);
mSoundManager.playSound(1);
You can't count on your sound taking exactly the same amount of time to play, so telling the handler to post first is a bit better. Still not ideal, however.
Another consideration is that you're re-computing uptime and adding some more time to that (200 in this case). Why not use the modulus operator on your uptime, to ensure that your next requested post time is more precisely scheduled?
long divisions = SystemClock.uptimeMillis() % 200; // precisely scheduled event timings since system boot.
long nextDivision = divisions + 1; // the next desired event timing
mHandler.postAtTime(this, nextDivision * 200); // scaled back up to number of milli seconds
// now do more heavy lifting that would otherwise have affected uptimeMillis call
mSoundManager.playSound(1);

Categories

Resources