0

i was building an app where i need to get the device location and heres the code i used

Double latitude = 0.0;
    Double longitude = 0.0;
    String TAG = "HomeActivity";
    Location gpsLoc = null, networkLoc = null, finallLoc = null;
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED){
                Toast.makeText(this,"Not Granted",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(this,"Granted",Toast.LENGTH_LONG).show();
            }
            try{
                gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                networkLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }catch(Exception e){
                e.printStackTrace();
            }
            if(gpsLoc!= null){
                finallLoc = gpsLoc;
                latitude = finallLoc.getLatitude();
                longitude = finallLoc.getLongitude();
            }else if(networkLoc!=null){
                finallLoc = networkLoc;
                latitude = finallLoc.getLatitude();
                longitude = finallLoc.getLongitude();
            }else{
                latitude = 0.0;
                longitude=0.0;
            }
            try{
                Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
                List<Address> addresses = geocoder.getFromLocation(latitude,longitude,1);
                if(addresses!=null && addresses.size()>0){
                    String country = addresses.get(0).getCountryName();
                    String address = addresses.get(0).getAddressLine(0);
                    String city = addresses.get(0).getLocality();

                }

            }catch (Exception e){
                e.printStackTrace();
            }

i am almost ready to deploy this app and i wanted to make sure if i can rely on this code to get the location correctly?if no what kind of improvements should i make? the code works fine just wanted to know if there's something i am missing or something that could lead to an error under certain conditions.

Jhon
  • 109
  • 1
  • 14

2 Answers2

0

You can get the last known location from gps/network with the above code. But not sure that you will get the current location or sometimes you may not get the location.

If the location is mandatory for you then you should force the user to turn on gps and get the current location. This can be achieved by using LocationManager.requestLocationUpdates

Please follow the link https://stackoverflow.com/a/10917500/3886504

shobhan
  • 1,400
  • 2
  • 12
  • 27
0

Try below code This is the standers way how to get device location,

public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
Location location;
double latitude;
double longitude;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;

public GpsTracker(Context context) {
    this.mContext = context;
    getLocation();
}


public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        //getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            //no network provider is enabled
        } else {
            try {
                this.canGetLocation = true;

                //first get location from network provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    //  Log.d("Network","Network");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (android.location.LocationListener) this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }

            } catch (SecurityException se) {
                Log.d("ERROR", se.toString());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }
    return latitude;
}


public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }
    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS Settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not Enabled.");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

and in your activity call GpsTracker class like below,

 GpsTracker gps = new GpsTracker(getActivity());
    if (gps.canGetLocation()) {
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        location = new LatLng(latitude, longitude);
        geoLocation = new GeoLocation(latitude, longitude);
        Log.d("*******latitude", String.valueOf(latitude));
        Log.d("*******longitude", String.valueOf(longitude));

    }
}

and dont for get to add permission in manifest file,

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

and dont forget to request run time permission . Now you have device current location latitude and longitude. Use it to get current address from GeoCoder.

Sajith
  • 687
  • 6
  • 21