Timer anti cheat technique - android

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.

Related

High frequency UI update - Android

I want to make 8 squares change colors between red/black periodically.
I acomplish this using timer.schedule with period time in milliseconds and it work
BUT then I realized that I need to use small time between this transitions (example nanoseconds).
To accomplish that I wrote this code:
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run(){
//CODE OF THE TASK.
}
});
}
};
//To make schedule this task in 5 nanoseconds I use this!
exec = new ScheduledThreadPoolExecutor(1);
exec.scheduleAtFixedRate(timerTask, 0, 5, TimeUnit.NANOSECONDS);
But when I run this, the UI is not updating (seems to be stuck), but in logcat, all the logs are printing very fast. How can I achieve to make a task periodically x nanoseconds?
The entire Android UI runs at 60Hz- 60 updates per second. This means the minimum time between redraws is 16 ms. You cannot run it at a higher framerate. Nor are human eyes capable of seeing changes at a much higher frequency than that.
iOS and most video game consoles also work on a 60 Hz refresh rate. You'd find very few to no systems that go faster.
I'm not sure what exactly you're trying to accomplish, but I'm fairly certain you're trying to do it the wrong way.
ALSO: I notice your timer task posts to a handler. That means your timer task is going to tell the main thread to run something, and the timer task is running in nanoseconds. YOu're basically going to choke your main thread full of "run this task" messages, then eventually crash with an OOM error when the event queue becomes so massive it can't add any more (which may take several minutes), because there's no way you're processing them fast enough with the thread switching overhead.
After doing a lot of research, I realized that in order to get the view to refresh so quickly, I needed the use of SurfaceView and a Thread to make the UI redraw very fast, I really had no knowledge of this. Thanks for the help

How to update widget per second in 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.

Android Sensor Data Collection is not working properly

I developed a Data collector which collects data from Accelerometer, Gyroscope, Magnetometer and it worked fine for a while. Then I added Linear Acceleration to it as well (After 4 months, this week). Now both the version are behaving very strangely. Sometime they log the data perfectly when I do some physical activities like walking etc. However, sometimes it doesn't update sensors values and just repeat old values i.e each sensor value is updated lets after 5 seconds, 2 sec etc randomly and I need a sampling rate of 50 samples per second. I experimented with 10-15 participants and all my data was invalid because of this. The strange things is that the same app has worked perfectly before. I can't find any problem in it. I am placing some of the snapshots here. May be if someone can point to any bug or something ?
The buffered Writter:
FileWriter fow;
BufferedWriter bow;
extfile = new File(extfilepath, message + ".csv");
fow = new FileWriter(extfile);
bow = new BufferedWriter(fow);
This bow.writer is then being used in timertask thread to log data every 20 milliseconds.
Can anyone please comment or help me with this ? This weird behavior of this app is beyond my understanding.
Check that you have a wake lock acquired if your application goes to background. I've used PowerManager.PARTIAL_WAKE_LOCK successfully in a data collection application.
When your display turns off, your application is at least paused (and system might even stop it). The partial wake lock "Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off." So reading between the lines it means that otherwise your CPU might go to sleep for small periods of time in order to save power.
Did you forget to paste in:
else if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION){} ?
Are you using the accelerometer data, then subtracting gravity?
OK. What's your code look like to call the timer?? Something like this?
Timer updateTimer = new Timer("linear accel");
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
updateGUI();
}
}, 0, 100);
}
private void updateGUI() {
runOnUiThread(new Runnable() {
public void run() {} } ?

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();

Problem synchronizing sound and display

I have an app that plays an mp3 file and I'm trying to update a custom field in synchrony with certain times we have tabulated for the sound playback (kind of like a karaoke effect). I'm using a Handler to schedule these updates. In my custom field class, I define a Runnable that is supposed to run the update at the right time:
private final Runnable mTrigger = new Runnable() {
#Override
public void run() {
int now = mPlayer.getCurrentPosition();
if (mState == STATE_PLAYING && mUpdateAction != null) {
if (mTriggerTime - now > MAX_PREMATURE_TRIGGER) {
// Sound is lagging too much; reschedule this trigger
mHandler.postDelayed(this, mTriggerTime - now);
} else {
// Run the update
mUpdateAction.run();
}
}
}
};
When I call mPlayer.start() I schedule the first update by calling mHandler.postDelayed(mTrigger, timeToFirstUpdate). Each update action decides what the next update will be and schedules it (by calling mHandler.postDelayed(mTrigger, timeToNextUpdate)). The updates times are typically a few hundred milliseconds apart.
The problem is that, while some updates are happening promptly at the scheduled times, others can be delayed by 200 milliseconds or more, which is quite noticeable to the user. I'm not doing anything in my app between these updates other than playing the sound. (No background worker threads; no other display updates.) The delays appear to be random and vary considerably each time through.
I didn't think that the timing for postDelayed would be this imprecise! I don't know if this is an emulator issue or a problem with my approach. Does sound playback screw up the timing of the UI thread loop? Should I move the timing into a background thread (and is it safe to call mPlayer.getCurrentPosition() from a background thread)? Something else?
After much experimenting, it seems like the problem is the emulator. When I ran everything on a speedier workstation, the problem seems to have gone away.

Categories

Resources