What is SystemClock.elapsedRealtime - millisecond? - android

I have some doubts I had in mind regarding a section of code that I retrieved from some answers given which were used to prevent the user from clicking the same button multiple times. Can someone explain to me what this section code does and give examples?
The Codes are
private long mLastClickTime = 0;
//Avoid the user clicking more than one
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
the if condition is placed below every button.setonclicklistener
I just want to understand what this section of code does only :)

I'll explain it using more detailed variable names.
private long mLastClickTime = 0;
private long theUserCannotClickTime = 1000; // milliseconds. the time that must pass before the user's click become valid
long currentTime = SystemClock.elapsedRealtime(); // not necessarily the current realworld time, and it doesn't matter. You can even use System.currentTimeMillis()
long elapsedTime = currentTime - mLastClickTime; // the time that passed after the last time the user clicked the button
if (elapsedTime < theUserCannotClickTime)
return; // 1000 milliseconds hasn't passed yet. ignore the click
}
// over 1000 milliseconds has passed. do something with the click
// record the time the user last clicked the button validly
mLastClickTime = currentTime;

elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
For futher check this method
https://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime()

Related

How to know the time that a user has been somewhere?

I am using Android LocationManager to check if a user is around a Location that I have defined.
I am using addProximityAlert method so that I receive an intent when the user is where I expect.
However, what I would like to do is to know if a user is in the given place for a period of time because if a user is crossing through the location I am checking, I may also receive the intent.
My first approach is that after some time (some minutes) I can check it again. Is there a better approach? Is there any way to receive the intent only after some time has passed?
Thank you.
To solve this problem, you could use an if statements to store the elapsed time of the user being in a certain distance. You could use System.currentTimeMillis() to get the current time and then subtract the original start time from it, to give you the elapsed time. Here is something you could do:
long startTime = 0;
long elapsedTime;
// Set up LocationManager here
Location targetPlace;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Location location = locationManager.getLastKnownLocation(provider);
// Checks to see if the user was already there when they opened the activity
if(location.distanceTo(targetPlace) == 5) {
startTime = System.currentTimeMillis();
}
targetPlace = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
if(startTime != 0) {
// Check to see if the user is in a given place
if (location.distanceTo(targetPlace) == 5) {
elapsedTime = (System.currentTimeMillis() - startTime) / 1000; // Time in seconds
} else {
// User is not near that location
}
} else {
startTime = System.currentTimeMillis();
}
}
Change '5' in the if statement to whatever you want the radius to be. Hope this helps!

How to get the idle time or the time since last button being pressed?

In my module I have to perform some idle state events.I have gone through this How to detect USER INACTIVITY in android and Android Best Way to Detect and Handle User INACTIVITY this tutorial..
now I just wanted to know how to get the last button pressed time so that if the any other button of my app is not being pressed for several seconds the idle state events should start..
please help me ....
you can use
public long startTime;
startTime = System.currentTimeMillis();
then later on
public long elapsedTime;
elapsedTime = ( System.currentTimeMillis() - startTime);
then to break it down
int hour = (int)((((elapsedTime/1000)/60)/60)%60);
int minutes = (int)(((elapsedTime/1000)/60)%60);
int seconds = (int)((elapsedTime/1000)%60);

android chronometer intervals and resetting

I'm working as a football (soccer) referee in Israel and I was asked to write an application that simulates our fitness test for the upcoming season.
The test is an interval test, and the user can enter how much time does he run, walk and for how many sets.
There is a beep sound for each time you should start/stop running (beep variable is of type MediaPlayer). The chronometer should reset each time you finish running / walking.
The following code almost works - The beep sounds are heard in the right time and stop after the right number of sets, but the screen gets stuck right after the chronometer starts...
I would really appreciate your kind help!
Thanks, Yaad
private void testLoop() {
int i = 0;
boolean flag = true; //true = running, false = walking
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
//run, walk, rep = integers that are set by user input
beep.start();
tvRunWalk.setText("Running");
tvRepNum.setText(String.format("Repetition Number: %d", i + 1));
while (i < rep) //rep = number of repetitions
{
if (SystemClock.elapsedRealtime() - chronometer.getBase() == run * 1000 && flag) //if running time is over and you are now running
{
chronometer.setBase(SystemClock.elapsedRealtime());
flag = false;
tvRunWalk.setText("Walking");
beep.start();
}
else if (SystemClock.elapsedRealtime() - chronometer.getBase() == walk * 1000 && !flag) //if walking time is over and you are now walking
{
chronometer.setBase(SystemClock.elapsedRealtime());
flag = true;
i++;
tvRunWalk.setText("Running");
tvRepNum.setText(String.format("Repetition Number: %d", i + 1));
beep.start();
}
}
}
Your while loop is blocking the UI. You better use AsyncTask and put your loop in its doInBackground() method in order to properly update the UI.
More info here: http://developer.android.com/reference/android/os/AsyncTask.html

How to get when the last touch on the screen happened?

I have an activity and I have a thread that runs when the activity is started. The thread call one method called getTimeOfLastEvent,
public long getTimeOfLastEvent(){
return 0;
}
I want this method to return me for example milliseconds from the time when the last event happened to this moment(the moment when the method is called). with the word 'event' I refer to any touch on the screen. And for example if the user touches the screen and then leave the phone for a 4 seconds and in that moment the getTimeOfLastEvent is called I want this method to return me 4 seconds (probably in unit milliseconds)
If I leave the phone after 10 seconds the screen is turned off, but if I touch the screen just before the 10 seconds pass, the timer i reset and I got another 10 seconds..., my problem is that I do not know how to read this timer.
static long timeLastEvent ;//initialize with appropriate value
public long getTimeOfLastEvent()
{
long duratin = System.currentTimeMillis() - timeLastEvent ;
timeLastEvent = System.currentTimeMillis();
return duration ;
}

Short, varying interval timer in Android

I am trying to create a kind of a metronome for Android. It shall play some audible beeps at certain intervals to give people a rhythm. Hence, timing is quite critical. Essentially it shall do the following
(start)
Play beep type 1 (about 0.1s long)
Wait for x milliseconds (between 500 and 1000)
Play beep type 2 (about 0.1s long)
Wait for y milliseconds (between 500 and 1000)
Play beep type 3 (about 0.1s long)
Wait for y milliseconds (between 500 and 1000)
Go back to start
The UI activity will have some buttons to adjust the wait intervals.
From reading all the various blogs, tutorials and discussions it seems that I should be using a postdelayed() Runnable and set the delay to my desired wait time x or y. After that I should start playing the sound. This should allow me to not take the length of the wav sound file into account.
Am I roughly on the right track? I realise that the timing will not be perfect as there are other services running which might delay the execution of my timers. In order to improve that I'd be happy to use the phone in flight mode or turn of some other services as I don't need anything else when using this app.
Are there any full examples for such code out there? I am a beginner when it comes to Android. My eyperience is more with straight C embedded systems. Putting all the classes and their functions together is quite daunting.
Any help appreciated,
Michael
An idea that just came to my mind regarding the waiting between the beeps would be to launch a separate Java thread where you enter in an infinite loop and call Thread.sleep(interval) like
public MyLooper extends Runnable{
private boolean shouldRun = true;
private int interval = 1; //ms
#Override
public void run(){
while(shouldRun){
//play the beep
Thread.sleep(interval);
}
}
public void stop(){
this.shouldRun = false;
}
public void setInterval(int interval){
this.interval = interval;
}
}
When you launch your activity (depending on your needs) usually in the onResume event, you'd create the Java thread. Inside the button clicks you could then adjust the interval by calling the setInterval(...) method.
Could be a possible solution...
This is what you need:
Updating the UI from a Timer
EDIT: That tutorial is specifically targeting a UI-update scenario, but it gives a simple description of what you really want: a TimerTask
class UpdateTimeTask extends TimerTask {
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
timeLabel.setText(String.format("%d:%02d", minutes, seconds));
}
}
and
if(startTime == 0L) {
startTime = evt.getWhen();
timer = new Timer();
timer.schedule(new UpdateTimeTask(), 100, 200);
}

Categories

Resources