如何在Android中每5分钟获取一次GPS位置?

7

大家好,能否提供一段每五分钟获取位置的样例代码?我已经尝试过点击按钮获取位置,但我需要每五分钟自动获取一次位置。

谢谢!

这是我的代码:

public void checkLocation(View v) {

        //initialize location manager
        manager =  (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //check if GPS is enabled
        //if not, notify user with a toast
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "GPS is disabled.", Toast.LENGTH_SHORT).show();
        } else {

            //get a location provider from location manager
            //empty criteria searches through all providers and returns the best one
            String providerName = manager.getBestProvider(new Criteria(), true);
            Location location = manager.getLastKnownLocation(providerName);

            TextView tv = (TextView)findViewById(R.id.locationResults);
            if (location != null) {
                tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
            } else {
                tv.setText("Last known location not found. Waiting for updated location...");
            }
            //sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
            manager.requestLocationUpdates(providerName, 15000, 1, this);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        TextView tv = (TextView)findViewById(R.id.locationResults);
        if (location != null) {
            tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
        } else {
            tv.setText("Problem getting location");
        }
    }

    @Override
    public void onProviderDisabled(String arg0) {}

    @Override
    public void onProviderEnabled(String arg0) {}

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    // Find the closest Bart Station
    public String findClosestBart(Location loc) {
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        double curStatLat = 0;
        double curStatLon = 0;
        double shortestDistSoFar = Double.POSITIVE_INFINITY;
        double curDist;
        String curStat = null;
        String closestStat = null;

        //sort through all the stations
        // write some sort of for loop using the API.

        curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
                        ((lon - curStatLon) * (lon - curStatLon)) );
        if (curDist < shortestDistSoFar) {
            closestStat = curStat;
        }

        return closestStat;

        }   

使用处理函数和每五分钟更新。将按钮按下的代码放入该函数中。 - SubbaReddy PolamReddy
如何使用处理函数?你能编辑这段代码吗? - Gopi.cs
4个回答

13

这是获取位置并设置GPS监听以获取当前位置的代码,可以在几分钟内获取位置和距离。我还使用了可运行对象来每隔几分钟获取位置。

Location gpslocation = null;

private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter

/*
   for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/

private void obtainLocation(){
if(locMan==null)
    locMan = (LocationManager) getSystemService(LOCATION_SERVICE);

    if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(isLocationListener){
             locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                        GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
                }
            }
        }
}

现在使用这个方法获取当前位置,监听器会在每1分钟和1000米的距离变化时调用位置变化。

要每5分钟获取一次位置,您可以使用此处理程序和可运行程序以在设置的时间间隔内获取该位置:

private static final int HANDLER_DELAY = 1000*60*5;

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
        public void run() {
            myLocation = obtainLocation();
            handler.postDelayed(this, HANDLER_DELAY);
        }
    }, START_HANDLER_DELAY);

这里是用于位置更改事件的GPS监听器:

private LocationListener GPSListener = new LocationListener(){
    public void onLocationChanged(Location location) {
        // update location
        locMan.removeUpdates(GPSListener); // remove this listener
    }

    public void onProviderDisabled(String provider) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
};

您可以设置监听器和处理程序的间隔时间相同,以获取GPS位置信息。

当用户关闭应用程序时,位置跟踪将停止。我们如何使用服务来实现这一点? - Kwnstantinos Nikoloutsos

2

嗨,使用下面的计时器代码。

你可以使用以下选项 选项1 这将获取移动100米后的位置。

    captureFrequencey=3*60*1000;   
LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, captureFrequencey, 100, this);

请查看此链接 http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29

选项2

   TimerTask refresher;
        // Initialization code in onCreate or similar:
        timer = new Timer();    
        refresher = new TimerTask() {
            public void run() {
              handler.sendEmptyMessage(0);
            };
        };
        // first event immediately,  following after 1 seconds each
        timer.scheduleAtFixedRate(refresher, 0,1000); 
        //=======================================================


final Handler handler = new Handler() {


        public void handleMessage(Message msg) {
              switch (msg.what) {
              case REFRESH: 
                  //your code here 

                  break;
              default:
                  break;
              }
          }
        };

计时器会在指定时间内调用处理程序(将1000更改为所需时间)。
希望这能对您有所帮助。

1
我使用runnable来完成这个任务。
    final Runnable r = new Runnable() {
        public void run() {
    //Here add your code location listener call
    handler.postDelayed(this, 300000 );
        }
    };

    handler.postDelayed(r, 300000 );

0

尝试像这样:

 private Handler handler = new Handler(); 

 handler.postDelayed(runnable, 300000);

 private Runnable runnable = new Runnable() {   
    public void run() {
        if (location != null) {

            onLocationChanged(location);
        } else {
            System.out.println("Location not avilable");
        }

        handler.postDelayed(this, 300000);
    } 
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接