discodowney
discodowney

Reputation: 1507

Using GPS as a service in android

So im making a map app that uses GPS to track your location. we just had a class about using GPS as a service. It looks interesting so im giving it a shot.

So ive made the code for using GPS as a service. But im not sure about how to get my current location to show up on the map. Currently I have my activity implementing LocationListener and im updating the map with the route taken onLocationChanged.

What i was thinking was having the gps as a service but also leaving my activity implementing locationListener. So if the screen is locked the service will still record co-ordinates but when the activity is running the map can be updated through there. Im just wondering if there is a better way or is it okay to have the service and activity both implementing LocationListener?

Thanks.

Upvotes: 0

Views: 75

Answers (1)

user3428540
user3428540

Reputation:

You can't directly mark an marker or put route into your activity from the service...

So it is better to implement both the service and activity with a location listener...

You can track the locations in the service and store it in a variable (maybe JSON Array, String Array etc...) based on your need and store the array in the preference file...

Once after unlocking the device your activity will get restarted at that time you can get the array variable from your preference and can draw route into your activity...

You can implement like this....

Service class...

private JSONArray savedTrekLat = new JSONArray();
private JSONArray savedTrekLon = new JSONArray();

@Override
public void onLocationChanged(Location location) {
    double lat = location.getLatitude();
    double lon = location.getLongitude();
    savedTrekLat.put(Double.toString(lat));
    savedTrekLon.put(Double.toString(lon));
    edit = mPrefer.edit();
    edit.putString("SAVED_TREK_LAT", savedTrekLat.toString());
    edit.putString("SAVED_TREK_LON", savedTrekLon.toString());
    edit.commit();
}

Your activiy class...

private static SharedPreferences mPrefer;
private String mTrekedLat;
private String mTrekedLon;
private JSONArray trekedlat;
private JSONArray trekedlon;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_tile);
        mPrefer = getSharedPreferences("Your Preference Name", this.MODE_PRIVATE);
        mTrekedLat = mPrefer.getString("SAVED_TREK_LAT", null);
        mTrekedLon = mPrefer.getString("SAVED_TREK_LON", null);
        try {
            trekedlat = new JSONArray(mTrekedLat);
            trekedlon = new JSONArray(mTrekedLon);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

After this you will get the location travelled by your mobile during sleep condition and you can place the routes into the activity using your code by extracting the values from the JSON Array...

Upvotes: 1

Related Questions