Ayush Kshitij
Ayush Kshitij

Reputation: 125

How to get last location of a device?

I am trying to get user's last known location but when i open the app it just shows a blank screen in the textViews where it should show latitude longitude and time. I can't find any flaws or error. So, I need some help. This code worked when I ran it yesterday, but it isn't working now. The following is my

MainActivity.java:

public class MainActivity extends AppCompatActivity implements LocationListener {
final String TAG = "GPS";
private final static int ALL_PERMISSIONS_RESULT = 101;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 ;

TextView tvLatitude, tvLongitude, tvTime;
LocationManager locationManager;
Location loc;
ArrayList<String> permissions = new ArrayList<>();
ArrayList<String> permissionsToRequest;
ArrayList<String> permissionsRejected = new ArrayList<>();
boolean isGPS = false;
boolean isNetwork = false;
boolean canGetLocation = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvLatitude = (TextView) findViewById(R.id.tvLatitude);
    tvLongitude = (TextView) findViewById(R.id.tvLongitude);
    tvTime = (TextView) findViewById(R.id.tvTime);

    locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
    isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
    permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
    permissionsToRequest = findUnAskedPermissions(permissions);

    if (!isGPS && !isNetwork) {
        Log.d(TAG, "Connection off");
        showSettingsAlert();
        getLastLocation();
    } else {
        Log.d(TAG, "Connection on");
        // check permissions
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (permissionsToRequest.size() > 0) {
                requestPermissions(permissionsToRequest.toArray(new String[permissionsToRequest.size()]),
                        ALL_PERMISSIONS_RESULT);
                Log.d(TAG, "Permission requests");
                canGetLocation = false;
            }
        }

        // get location
        getLocation();
    }
}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "onLocationChanged");
    updateUI(location);
}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {}

@Override
public void onProviderEnabled(String s) {
    getLocation();
}

@Override
public void onProviderDisabled(String s) {
    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
}

private void getLocation() {
    try {
        if (canGetLocation) {
            Log.d(TAG, "Can get location");
            if (isGPS) {
                // from GPS
                Log.d(TAG, "GPS on");
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (loc != null)
                        updateUI(loc);
                }
            } else if (isNetwork) {
                // from Network Provider
                Log.d(TAG, "NETWORK_PROVIDER on");
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (loc != null)
                        updateUI(loc);
                }
            } else {
                loc.setLatitude(0);
                loc.setLongitude(0);
                updateUI(loc);
            }
        } else {
            Log.d(TAG, "Can't get location");
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

private void getLastLocation() {
    try {
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        Log.d(TAG, provider);
        Log.d(TAG, location == null ? "NO LastLocation" : location.toString());
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

private ArrayList findUnAskedPermissions(ArrayList<String> wanted) {
    ArrayList result = new ArrayList();

    for (String perm : wanted) {
        if (!hasPermission(perm)) {
            result.add(perm);
        }
    }

    return result;
}

private boolean hasPermission(String permission) {
    if (canAskPermission()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED);
        }
    }
    return true;
}

private boolean canAskPermission() {
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}

@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case ALL_PERMISSIONS_RESULT:
            Log.d(TAG, "onRequestPermissionsResult");
            for (String perms : permissionsToRequest) {
                if (!hasPermission(perms)) {
                    permissionsRejected.add(perms);
                }
            }

            if (permissionsRejected.size() > 0) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
                        showMessageOKCancel("These permissions are mandatory for the application. Please allow access.",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                            requestPermissions(permissionsRejected.toArray(
                                                    new String[permissionsRejected.size()]), ALL_PERMISSIONS_RESULT);
                                        }
                                    }
                                });
                        return;
                    }
                }
            } else {
                Log.d(TAG, "No rejected permissions.");
                canGetLocation = true;
                getLocation();
            }
            break;
    }
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    alertDialog.setTitle("GPS is not Enabled!");
    alertDialog.setMessage("Do you want to turn on GPS?");
    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    });

    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(MainActivity.this)
            .setMessage(message)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

private void updateUI(Location loc) {
    Log.d(TAG, "updateUI");
    tvLatitude.setText(Double.toString(loc.getLatitude()));
    tvLongitude.setText(Double.toString(loc.getLongitude()));
    tvTime.setText(DateFormat.getTimeInstance().format(loc.getTime()));
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (locationManager != null) {
        locationManager.removeUpdates(this);
    }
}
}

}

Upvotes: 0

Views: 3053

Answers (2)

Dan
Dan

Reputation: 110

Fused Location Provider Client is the best way to do it. Try with this code for the getLastLocation() method:

FusedLocationProviderClient mLocationProvider = LocationServices.getFusedLocationProviderClient(activity);
        mLocationProvider.getLastLocation().addOnSuccessListener(activity, location -> {
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();    
            }
        }).addOnFailureListener(e -> {
                //some log here
        });

Upvotes: 1

Flutterian
Flutterian

Reputation: 1781

Can you try below solution and let me know, because it's working fine for me.

Change your provider as

String provider = LocationManager.NETWORK_PROVIDER;

You have mentioned this provider in getLastLocation() method.

Also add below permissions to your manifest files

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.BIND_TELECOM_CONNECTION_SERVICE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Upvotes: 0

Related Questions