How can I invoke a method every 5 seconds in android?

后端 未结 4 2093
轻奢々
轻奢々 2020-12-11 11:38

I\'m working in an application which must send a GPS location every 5 seconds to the server when I choose (auto send button on). I\'m new with android so I don\'t know how I

相关标签:
4条回答
  • 2020-12-11 12:01

    Look at the AlarmManager class http://developer.android.com/reference/android/app/AlarmManager.html and particularly the setRepeating function. Its going to be a bit more complicated than you'd like though.

    0 讨论(0)
  • 2020-12-11 12:05

    Ridcully is right, there is probably no reason to send the current location every 5 seconds. Here is the rational behind that:

    You really only care about 2 things about the users location:

    1. Where are they right now?

    2. Have they moved since I got their first location?

    So once you get a satisfactory initial location, you can just register to get callbacks whenever the users moves like this:

    private LocationListener mLocationListener;
    
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                updateLocation(location);
            }
    
            @Override
            public void onStatusChanged(final String provider,
                    final int status, final Bundle extras) {
            }
    
            @Override
            public void onProviderEnabled(final String provider) {
            }
    
            @Override
            public void onProviderDisabled(final String provider) {
            }
        };
    }
    

    That being said, you could obviously do what these others have said and run the timer every 5 seconds. The thing is, most good locations take 10-20 seconds to run, so you might only want to run it in that interval. Also FYI, this WILL kill battery

    0 讨论(0)
  • 2020-12-11 12:09

    I have faced exactly the same problem, sending location periodically. I've used a handler and its postDelayed method.

    The periodic call part of my code looks like this:

    private final int FIVE_SECONDS = 5000;
    public void scheduleSendLocation() {
        handler.postDelayed(new Runnable() {
            public void run() {
                sendLocation();          // this method will contain your almost-finished HTTP calls
                handler.postDelayed(this, FIVE_SECONDS);
            }
        }, FIVE_SECONDS);
    }
    

    Then you just need to call scheduleSendLocation when you want to start your period calls.

    0 讨论(0)
  • 2020-12-11 12:12

    You can use a Timer. But I think it would be better if you only send the position of it has changed a certain distance from the last one you sent. This way you'd send way less data without losing any information.

    0 讨论(0)
提交回复
热议问题