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

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 ;
}

Related

What is SystemClock.elapsedRealtime - millisecond?

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

Self Prepuating Timer That Modifies GUI in Android

I'm making an application and a certain part in my application I store a list of prices along with the time that the prices last for (they do not all last the same amount of time). So a price lasts a certain time then once that price's time is up it changes to another price (this part changes the UI or basically it updates a textview with the new price). So what I need is a timer that sets the timer again with the new time length and once it's done make the UI change. For instance say that each of the pairs represent the price amount and the time (in seconds): { {$2.53,1.4s}, {$4.57,4.45s}, {$1.23,3.6s}...}
So when the timer starts off the textview displays $2.53 and the timer lasts 1.4s and then it should grab the next price $4.57 and be set again but this time for 4.45s. This process continues on and on until the game is finished. I was thinking of using the CountDownTimer and resetting itself once the onFinish() method is called (I haven't verified if this idea works yet). Are there any other ideas?
You can use a countdown timer and onFinish method you call back the function and it starts another timer:
private void startWheatPrices(long gameTime)
{
//other stuff executed
StartWheatTimer(GameTimeDifference);//starts the timer for the first time
}
private void StartWheatTimer(long TimerAmount)
{
WheatTimer = new CountDownTimer(TimerAmount, 10) {
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
//other stuff executed
WheatPricesTV.setText(Float.toString(PriceList.get(0).get(WheatPriceIndex).price));//price is changed
if(InGameplayMode)
StartWheatTimer(convertToMilliseconds(PriceList.get(0).get(WheatPriceIndex).timeLength));//call back the function to start the timer again
}
}.start();
}

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

Android, how to measure an elapsed amount of time

I'm working on a presentation app, which displays different images. There I wanted to to let the presentation slide through my List of images, video and pdf files, after a short amount of time.
I start my different views through intents, startActivityForResult(intent, RESULT_OK);
Starting videos and closing videos was not an issue. I used onPreparedListener and setOnCompletionListener and everything worked like a charm.
With pictures however, this was completely diffrent.
I created a new Thread in my ImageView and did put that thread to sleep(), after that I called the setresult() method and finish(). But instead of waiting, the picture wasn't shown at all and the presentation was stuck there, without setting the result and finishing the activity.
So I started searching for some explanation of time in android and found this explanation:
Explanation
I read through it and tried to get a good grasp on whats explained there. But the more I thought about it, the more I got insecure, which is the best way to implement the waiting behavior for my intended purpose.
So instead of some code, I am much more interested in, what you would advise me to use and why with a, if possible, detailed explanation.
elapsedRealtime()?
uptimeMillis()?
System.currentTimeMillis()?
From android docs:
• System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.
• uptimeMillis() is counted in milliseconds since the system was booted. This clock stops when the system enters deep sleep (CPU off, display dark, device waiting for external input), but is not affected by clock scaling, idle, or other power saving mechanisms. This is the basis for most interval timing such as Thread.sleep(millls), Object.wait(millis), and System.nanoTime(). This clock is guaranteed to be monotonic, and is suitable for interval timing when the interval does not span device sleep. Most methods that accept a timestamp value currently expect the uptimeMillis() clock.
• 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.
If the time interval, you're going to measure, is relatively short, you can use pretty much any method which gives you correct time. I prefer currentTimeMillis(). In case the time interval is really long, the recommended method is to use elapsedRealtime().
Also, if you only want to do something with a delay, simply use: http://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long) . It's simple and works great.
Simplest way to achieve that is CountDownTimer
private final class CountDownTimerImpl extends CountDownTimer {
//5 sec.
private static final long TIME_INTERVAL = 5000;
private final ImageView imageView;
private final List<Drawable> images;
public CountDownTimerImpl(ImageView imageView, List<Drawable> images) {
super(TIME_INTERVAL, TIME_INTERVAL);
this.imageView = imageView;
this.images = images;
//set first image from images array to imageView
imageView.setImageDrawable(images.get(0));
}
//this method is executed after TIME_INTERVAL (5 sec.)
public void onFinish() {
//remove drawable from imageView
imageView.setImageDrawable(null);
//remove this drawable from array
images.remove(0);
//if array is not empty start another count down
if (!images.isEmpty()) {
new CountDownTimerImpl(imageView, images).start();
}
}
public void onTick(long millisUntilFinished) {
//nothing to do here
}
}
You should start this CountDownTimer by:
new CountDownTimerImpl(imageView, images).start();
where images is of course an drawables array of your presentation images.
I have no time to test this solution but it should work - if not please leave a comment and I will update it later.
You can use TimerTask
int counter=0;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
counter++;
//you can do stuffs here say like if (counter==15) { do something}
}
});
}};
ourtimer.schedule(timerTask, 0, 1000);
You can do this in a different way writing a callback module
Create a activity call it BaseActivity and let all you activities to extend it
Now declare a method call is void callback(){} keep the body empty
now in onCreate create a timer as above and call the callback function your code will look like
onCreate(){
final Handler handler = new Handler();
Timer callTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
callback();
}
});
}};
callTimer.schedule(timerTask, 0, 1000);
}
Now in you activity override the callback method which will be called after the time you specified in timer,
Ex
Class a extends BaseActivity(){
#Override
onCreate(){
// playVideo
}
#Override
void onCallBack(){
//navigate to another activity
}
}

Categories

Resources