问题
I am creating an app that alerts user if he has been stationary for a few minutes(say 10).
I find it easy to detect motion, using LocationListener which triggers a function if device moved a certain distance.
However, I want something different. I want a function to be called if the device did not move for a certain duration of time.
How I achieve this?
回答1:
You could easily set a timer and when the LocationListener fires, reset the timer to zero. If the timer reaches 10 minutes, then you know that the user hasn't moved. The downside to this approach is that the timer must continue to run, so you will need to install as a service.
http://developer.android.com/reference/java/util/Timer.html
回答2:
something like this might do the trick I am not sure if this code works, I haven't test it, but generally what you need to do is get the current location. then user a timer to check it in 10 minutes if it is still in the same location. if not use an intent to start a new activity.
private double locationcheck;
locationcheck = this.getcurrentlocation();
public double[] getcurrentlocation(){
double[] locations= new String[2];
l = lm.getLastKnownLocation(providers.get(i));
locations[0] = l.getLatitude();
locations[0] = l.getLongitude();
return
}
then use this method to check it :
final Handler handler = new Handler();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
if (locationcheck!=this.getcurrentlocation()) {
Intent i=new Intent(ctxt, YourActivity.class);
StartActivity(i);
}
}
});
}
}, 3000,10000);
来源:https://stackoverflow.com/questions/11212321/detect-stationary-device-using-gps