Where to save Android GPS (Latitude , Longitude) points?

后端 未结 5 780
一生所求
一生所求 2020-12-05 10:59

On onLocationChanged event I want to save my GPS route (Latitude , Longitude). Later I want to load this data and draw the route.

Who is the best way to do this, by

5条回答
  •  离开以前
    2020-12-05 11:32

    Use SharedPreferences and Editor.

    Check out this open source code, it will probably help you a lot: OsmandSettings.java

    I'll explain the important parts of the code:

    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    
    // These settings are stored in SharedPreferences, replace com.osmand.settings 
    // with your own package name, or whatever String you want.
    public static final String SHARED_PREFERENCES_NAME = "com.osmand.settings";
    public static final String LATITUDE = "latitude";
    public static final String LONGITUDE = "longitude";
    

    To write to SharedPreferences:

    public void onLocationChanged(Location location){
        SharedPreferences prefs = Context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
        Editor editor = prefs.edit();
        //Save it as a float since SharedPreferences can't deal with doubles
        edit.putFloat(LATITUDE, (float) Location.getLatitude());
        edit.putFloat(LONGITUDE, (float) Location.getLongitude());
        edit.commit();
    }
    

    To read from SharedPreferences:

    public void onLocationChanged(Location location){
        SharedPreferences prefs = Context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_WORLD_READABLE);
        double lat = (double)prefs.getFloat(LATITUDE, 0);
        double lon = (double)prefs.getFloat(LONGITUDE, 0);
    }
    

提交回复
热议问题