如何保存以前的gps坐标

时间:2015-05-22 15:29:01

标签: android

我正在android中创建一个程序,当位置发生变化时我会获得gps坐标。我需要在位置发生变化时保存先前的纬度和经度。然后我将能够计算距离。任何人都可以帮我如何以编程方式保存当前坐标和以前的坐标。谢谢。这是我的代码。忽略按钮和计时器我必须在位置改变时存储先前的坐标。

package com.example.higher.myosmand;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends Activity {

private LocationManager locationManager;
private LocationListener locationListener;
private Location currentLocation;
private TextView latlon;
private TextView distance;
ArrayList<String> list = new ArrayList<>();
ListView listView;
private TextView listText;
private float results[] = new float[2];
double lat;
double lon;
double currentLat;
double currentLon;
double accuracy;
double speed;
double altitude;
double time;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    latlon = (TextView) findViewById(R.id.latlon);
    distance = (TextView) findViewById(R.id.distanceText);
    listView = (ListView)findViewById(R.id.listView);
    listText = (TextView)findViewById(R.id.listText);

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location loc) {
            //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            lat = loc.getLatitude();
            lon = loc.getLongitude();
            accuracy = loc.getAccuracy();
            speed = loc.getSpeed();
            altitude = loc.getAltitude();
            time = loc.getTime();
            /*currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            currentLat = currentLocation.getLatitude();
            currentLon = currentLocation.getLongitude();*/
            listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));

            list.add("latitude: " + lat + " longitude: " + lon);
            //list.add("speed: " + speed + " accuracy: " + accuracy);
            distance.setText("size: " + list.size());
        }

        @Override
        public void onProviderDisabled(String arg0) {
            //TODO auto generated method stub
        }

        @Override
        public void onProviderEnabled(String arg0) {
            //TODO auto generated method stub
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            //TODO auto generated method stub
        }
    };
}

public void setMyTimer(){

    Timer myTimer = new Timer();
    TimerTask myTask = new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listView.setAdapter(new ArrayAdapter<String>(MainActivity.this, R.layout.activity_simplelist, R.id.listText, list));
                    list.add("latitude: " + lat + " longitude: " + lon);

                    //distance.setText("Current Location:\n Latitude: " + currentLat +" Longitude: " + currentLon);
                }
            });
        }
    };
    myTimer.schedule(myTask, 5000, 5000);
}

public void startButton(View view) {
    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    latlon.setText("latitude: " + lat + " \nlongitude: " + lon + " \naccuracy: " + accuracy +
            "\nspeed: " + speed + "\naltitude: " + altitude + "\ntime: " + time);
}

public void endButton(View view) {
    //locationManager.removeUpdates(locationListener);

    //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

}

public void resetButton(View view) {
    list.clear();
}

@Override
protected void onResume() {
    super.onResume();
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}

@Override
protected void onPause() {
    super.onPause();
    //locationManager.removeUpdates(locationListener);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

3 个答案:

答案 0 :(得分:1)

在onLocationChanged方法中使用此代码。它将您之前的位置坐标存储到prev变量中:

private LatLng prev;
private int flag=0;

 @Override
        public void onLocationChanged(Location location) {
                LatLng current = new LatLng(location.getLatitude(), location.getLongitude());
            if(flag==0)  
            {
                prev=current;
                flag=1;
            }
    //Do whatever you want here
            prev=current;
            current = null;
}

答案 1 :(得分:1)

使用this link进行简单的键值存储。

// saving
PreferenceManager.getDefaultSharedPreferences(context).edit()
    .putLong("current_latitude", latitude)
    .putLong("current_longitude", longitude)
    .apply();

// loading
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
long latitude = prefs.getLong("current_latitude", 0);
long longitude = prefs.getLong("current_longitude", 0);

答案 2 :(得分:1)

为了简化embloo的回答,您可以在更新到onLocationChanged方法中的当前位置之前将当前位置保存到之前的位置变量。像这样:

@Override
public void onLocationChanged(Location location) {
    mPreviousLocation = mCurrentLocation;
    mCurrentLocation = location;

    // update values or UI below here 
}