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

后端 未结 4 2192
轻奢々
轻奢々 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: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.

提交回复
热议问题