Finding location in android using Gabe Sechan's tutorial

I have tried using androidhive's standard tutorial for finding location,but it fails at certain times.So i found another tutorial on this link:

http://gabesechansoftware.com/location-tracking/

He uses two classes which implement an interface:

The first class:

package com.example.marinamapseg;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class FallbackLocationTracker  implements LocationTracker, LocationTracker.LocationUpdateListener {


    private boolean isRunning;

    private ProviderLocationTracker gps;
    private ProviderLocationTracker net;

    private LocationUpdateListener listener;

    Location lastLoc;
    long lastTime;

    public FallbackLocationTracker(Context context) {
        gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
        net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //Start both
        gps.start(this);
        net.start(this);
        isRunning = true;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;
    }


    public void stop(){
        if(isRunning){
            gps.stop();
            net.stop();
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        //If either has a location, use it
        return gps.hasLocation() || net.hasLocation();
    }

    public boolean hasPossiblyStaleLocation(){
        //If either has a location, use it
        return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
    }

    public Location getLocation(){
        Location ret = gps.getLocation();
        if(ret == null){
            ret = net.getLocation();
        }
        return ret;
    }

    public Location getPossiblyStaleLocation(){
        Location ret = gps.getPossiblyStaleLocation();
        if(ret == null){
            ret = net.getPossiblyStaleLocation();
        }
        return ret;
    }

    public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
        boolean update = false;

        //We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
        if(lastLoc == null){
            update = true;
        }
        else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
            update = true;
        }
        else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
            update = true;
        }
        else if (newTime - lastTime > 5 * 60 * 1000){
            update = true;
        }

        if(update){
            lastLoc = newLoc;
            lastTime = newTime;
            if(listener != null){
                listener.onUpdate(lastLoc, lastTime, newLoc, newTime);                  
            }
        }
    }
}

The second class:

package com.example.marinamapseg;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class ProviderLocationTracker implements LocationListener, LocationTracker {

    // The minimum distance to change Updates in meters
    private static final long MIN_UPDATE_DISTANCE =  0; 

    // The minimum time between updates in milliseconds
    private static final long MIN_UPDATE_TIME = 0; 

    private LocationManager lm;

    public enum ProviderType{
        NETWORK,
        GPS
    };    
    private String provider;

    private Location lastLocation;
    private long lastTime;

    private boolean isRunning;

    private LocationUpdateListener listener;

    public ProviderLocationTracker(Context context, ProviderType type) {
        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        if(type == ProviderType.NETWORK){
            provider = LocationManager.NETWORK_PROVIDER;
        }
        else{
            provider = LocationManager.GPS_PROVIDER;
        }
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //The provider is on, so start getting updates.  Update current location
        isRunning = true;
        lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
        lastLocation = null;
        lastTime = 0;
        return;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;

    }


    public void stop(){
        if(isRunning){
            lm.removeUpdates(this);
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        if(lastLocation == null){
            return false;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return false; //stale
        }
        return true;
    }

    public boolean hasPossiblyStaleLocation(){
        if(lastLocation != null){
            return true;
        }
        return lm.getLastKnownLocation(provider)!= null;
    }

    public Location getLocation(){
        if(lastLocation == null){
            return null;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return null; //stale
        }
        return lastLocation;
    }

    public Location getPossiblyStaleLocation(){
        if(lastLocation != null){
            return lastLocation;
        }
        return lm.getLastKnownLocation(provider);
    }

    public void onLocationChanged(Location newLoc) {
        long now = System.currentTimeMillis();
        if(listener != null){
            listener.onUpdate(lastLocation, lastTime, newLoc, now);
        }
        lastLocation = newLoc;
        lastTime = now;
    }

    public void onProviderDisabled(String arg0) {

    }

    public void onProviderEnabled(String arg0) {

    }

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

But the issue is that he has not mentioned as how to use the following two classes in the android app.So i tried the following:

FallbackLocationTracker fobj;

fobj=new FallbackLocationTracker(MainActivity.this);
    fobj.start();
    if(fobj.hasLocation())
    {
        Location locobj=fobj.getLocation();
        current_latitude=locobj.getLatitude();
        current_longitude=locobj.getLongitude();
        Toast.makeText(getApplicationContext(),current_latitude+" "+current_longitude,Toast.LENGTH_LONG).show();
        placemarkersonmap();
    }

When i debug the code the hasLocation method returns false, Because the onLocationChanged method in the first class is getting called only after the haslocation method is called.So the lastlocation object will be null and false would be returned.

But why doesnt onlocationchanged get called as soon as the following line runs:

lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);

Or is there any way somenone can tell me as how to use the code.Please help!!

onLocationChanged is a callback, meaning that it is event driven and does not run until the device detects a change of location. If you are taking location only from GPS, then it can take several minutes before you get a fix. If you are indoors without a clear view of the sky, then it may never run.

java, onLocationChanged is a callback, meaning that it is event driven and does not run until the device detects a change of location. If you are taking location only  Gabe Sechan I've been a professional programmer for over a decade. My past work includes printer firmware for HP (my code still exists in most HP printers), back end services at Amazon.com, Android developer at Facebook, and 3 successful startups (SNAPin Software, Typesoft, and Swype).

You may add the following in your actitvity's onCreate method:

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textViewHeading = (TextView) this.findViewById(R.id.text_heading);
    textViewLong = (TextView) this.findViewById(R.id.text_long);
    textViewLat = (TextView) this.findViewById(R.id.text_lat);
    textViewHeight = (TextView) this.findViewById(R.id.text_height);
    textViewAccuracy = (TextView) this.findViewById(R.id.text_accuracy);
    
    counter = (long) 0;
    
    gps = new ProviderLocationTracker(this, 
        ProviderLocationTracker.ProviderType.GPS);
    listener = new LocationUpdateListener() {

      @Override
      public void onUpdate(Location oldLoc, long oldTime, Location newLoc,
          long newTime) {
        // TODO Auto-generated method stub
       
       counter = counter + (long) 1;
       if (gps.hasLocation()) {
         text1="GPS has location ( " + counter.toString() + " )";
       } else {
         text1="GPS has no location ( " + counter.toString() + " )";
       }
       
       if (gps.hasPossiblyStaleLocation()) {
         text1 = text1 + " plus stale location";
       }
       
       Double longitude = newLoc.getLongitude();
       Double latitude = newLoc.getLatitude();
       Double height = newLoc.getAltitude();
       Float accuracy = newLoc.getAccuracy();
              
       text2 = "Longitude = " + longitude.toString();
       text3 = "Latitude  = " + latitude.toString();
       text4 = "Altitude  = " + height.toString();
       text5 = "Accuracy  = " + accuracy.toString();
              
       textViewHeading.setText(text1);
       textViewLong.setText(text2);
       textViewLat.setText(text3);
       textViewHeight.setText(text4);
       textViewAccuracy.setText(text5);
      }
      
    };
    gps.start(listener);
    
  } // end method onCreate

Gabe Sechan Software, See more of Gabe Sechan Software on Facebook http://techcrunch.com/events​/disrupt-sf-2013/live-video/ I'll update with the exact location when the individual video is posted. Parking Rememberer - find your car quickly and easily - now on the Google Play Store. Parking Rememberer - Android Apps on Google Play. Gabe Sechan I've been a professional programmer for over a decade. My past work includes printer firmware for HP (my code still exists in most HP printers), back end services at Amazon.com, Android developer at Facebook, and 3 successful startups (SNAPin Software, Typesoft, and Swype).

It seems that this post already has an answer that shows how to use the ProviderLocationTracker. I am putting in my answer just to show how easy it get's with the FallbackLocationTracker.

I do not remember making any significant changes to the FallbackLocationTracker so I am not going to post the whole code.

public class MainActivity extends AppCompatActivity {
    private FallbackLocationTracker tracker;
    private Location location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tracker = new FallbackLocationTracker(MainActivity.this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        // Check for permission to access location and start location
        // tracking if permissions are granted and location services 
        // are enabled
        if (locationPermissionGranted && locationServicesEnabled) {
            startLocationUpdates();
        } else {
            // Handle accordingly
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    private void startLocationUpdates() {
        tracker.start(new LocationTracker.LocationUpdateListener() {
            @Override
            public void onUpdate(Location oldLocation, long oldTime, 
                         Location newLocation, long newTime) {
                // You will receive updated changes to your location here
                location = newLocation;
            }
        });        
    }

    private void stopLocationUpdates() {
        tracker.stop();
    }
}

That's it.

Gabe Sechan - Lead Android Developer, View Gabe Sechan's profile on LinkedIn, the world's largest professional maintained Guestfriend, an Android Application allowing users to interact with their  To get coordinates use getLatitude() and getLongitude() method on variable of Location class. Whenever location is changed it can be fetched inside onLocationChanged() method. Below is simple application that fetches current location on button click and displays it in textview.

Gabriel Sechan, View Gabriel Sechan's profile on AngelList, the startup and tech network - Software Engineer - New York City - Android engineer with over 17 years of professional programming experience. Log in or sign up to find connections to Gabriel. Help · Companies · Jobs by Location · Jobs by Market · Jobs by Role · Blog  Android app Development : Using GPS to find the current location in Android app Development In this video you learn how to use GPS to find the current location in Android app Development.

User Gabe Sechan, Gabe Sechan. New York, NY Facebook: http://facebook.com/​GabeSechanSoftware. top accounts Boss telling me to make hyperbolic statements, but I find it unethical. What do I do? How do I get the current GPS location programmatically in Android? Does Android Geocoder work only with internet connection? Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Set gps location android, When an app is using your phone's location via GPS, the top of your screen it even takes care of Android M runtime pythagorean theorem calc: find b, a=16, Gabe Sechan Gabe Sechan Since I want to keep compatibility to 14, I just use the​  If playback doesn't begin shortly, try restarting your device. Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to

Comments
  • It'd be nice to know how to use the fallback location tracker.
  • I was about to write an answer but thankfully you've done it! ;)