1
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

public class LocationService extends Service {

    private LocationDatabaseHelper mLocationDatabaseHelper;
    private LocationModel mLocationModel;
    private Date mDate;
    private Handler mHandler = new Handler();
    private Timer mTimer = null;
    private int mCount = 0;

    public static final long NOTIFY_INTERVAL = 30 * 1000;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        // cancel if already existed
        if (mTimer != null) {
            mTimer.cancel();
        } else {
            // recreate new
            mTimer = new Timer();
        }

        mLocationModel = LocationModel.getInstance();
        // schedule task
        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);

    }

    @Override
    public void onDestroy() {
        mTimer.cancel();
    }

    private class TimeDisplayTimerTask extends TimerTask implements LocationListener {

        @Override
        public void run() {

            mHandler.post(new Runnable() {

                @Override
                public void run() {
                    //I send message to draw map here
                    sendMessage();
                    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                            TimeDisplayTimerTask.this);

                }

            });
        }

        @Override
        public void onLocationChanged(Location location) {
            // I get location and do work here

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

    }

    private void sendMessage() {
          Intent intent = new Intent("my-event");
          intent.putExtra("message", "data");
          LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
}

What I want is to get user location after every 30 seconds but this code does not work as I expected. It gets location very fast (I think every second).

I tried to get location this way because it can get my current location immediately after I start my app.I have tried getLastKnowLocation before, but it give me the last known location which is very far from where I am.

Please show me how fix this.Thank you!

Bụng Bự
  • 553
  • 1
  • 7
  • 15
  • use AlarmManager instead – Amy Jul 21 '15 at 07:29
  • You want it to run once after 30 seconds? Or once every thirty seconds? For the former, your timer's `scheduleAtFixedRate` should have `30*1000` as the second parameter--it's `scheduleAtFixedRate(TimerTask task,long delay,long period)` and you're not giving it a delay. **edit** Bleh, I can't read. If you want a recurring thing, LocationListener is better. – Matter Cat Jul 21 '15 at 07:32
  • use location listener..check implementation http://stackoverflow.com/questions/14478179/background-service-with-location-listener-in-android – Jaiprakash Soni Jul 21 '15 at 07:32
  • @MatterCat Sorry,I editted it. I want to get it after every 30 second. – Bụng Bự Jul 21 '15 at 07:37
  • mTimer.cancel(); does not kill your timer task. – arlen Jan 16 '17 at 17:18

3 Answers3

2

in requestLocationUpdates method second parameter is minimum time interval between location updates, in milliseconds, So you just need to do this:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 0, TimeDisplayTimerTask.this);
Beyka
  • 1,372
  • 1
  • 10
  • 15
1

According to Android Developer Reference Documentation

http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String, long, float, android.location.LocationListener)

public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)

When registering for location updates the LocationManager is invoking LocationListener onLocationChanged(Location) method with latest Location object.

And the second parameter of requestLocationUpdates method is

minTime The minimum time interval between location updates, in milliseconds

This does not mean that you will get location updates every 30 seconds constantly, because if the location cannot be obtained you will not get updates also, if the location is not being changed you will again not get any updates.

Anyway, if you would like to get location updates every 30 seconds constantly, you can keep latest location and send it using your scheduler, while updating it when the onLocationChanged method is called.

Huds0nHawk
  • 1,486
  • 16
  • 26
0

try using

TimerTask scanTask;
final Handler handler = new Handler();
mTimer = new Timer();

public void sendSMS(){

scanTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            //your method here which you want to call every 30 sec
                        }
               });
        }};

    mTimer.schedule(scanTask, 30000, 30000); 
 }
chetna
  • 94
  • 5