Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to count time over a long period

In my app I want measure the amount of time that the accelerometer is at rest.

For example, if I set a threshold of 0.4 m/s and the accelerometer speed is always below this than it means that the phone is at rest (threshold is to account for jitter in values).

I want to be able to count the amount of time that the phone is at rest and upon reaching a certain amount of time at rest, then react to that event.

I already have the accelerometer working fine, I just need to count this time and I'm unfamiliar with how to do this, can anyone help me out here? Thanks in advance

Solution:

  start = System.currentTimeMillis();

    if (vectorTotal > 10.1 || vectorTotal < 9.5){
        timelimit = (System.currentTimeMillis()+ 10000);
    }
    else if (start >= timelimit){
        checkUser();
        timelimit = (System.currentTimeMillis()+ 10000);
    }
like image 685
bobby123 Avatar asked Feb 08 '11 14:02

bobby123


2 Answers

Is your app at the foreground?

At start:

long start = System.currentTimeMillis();

Save this value in database or in preferences if necessary.

At end:

long end = System.currentTimeMillis();

Then:

long passedTime = end - start;
like image 166
DKIT Avatar answered Nov 08 '22 09:11

DKIT


You could set an alarm each time you're above the threshold and when the alarm finally fires you do whatever you want.

Do something like this when you start your activity:

am = (AlarmManager) getSystemService(ALARM_SERVICE);
timeoutInMillis = 60000;
Intent timeoutIntent = <create the intent you want to run here>;
timeoutPendingIntent = PendingIntent.getService(this, 0, timeoutIntent, PendingIntent.FLAG_UPDATE_CURRENT);

and then everytime the accelerometer is above your threshhold:

am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeoutInMillis, timeoutPendingIntent );

don't forget to clear the alarm when you exit your activity:

am.cancel(timeoutPendingIntent);
like image 37
getekha Avatar answered Nov 08 '22 08:11

getekha