Android get User Location once

2019-08-05 09:22发布

问题:

I know that there are a lot of things around this but even after I read them all (almost) I still can't figure it out the issue.

Basically I want to get the user FINE LOCATION when I open the app or press a button and save on Shared Preferences. My old code worked but since was slow to get the coordinates, it fails to save on sharedpreferences (GPS icon don't show on bar).

OLD:

 public void askLocation() {
    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        try {
            mLocation = locationManager.getLastKnownLocation(provider);
        } catch (SecurityException e) {
            //
        }

        String currentCoordinates = somename.getString("LastLocation", "0,0");

        if (mLocation != null) {
            double currentLatitude = mLocation.getLatitude();
            double currentLongitude = mLocation.getLongitude();

            currentCoordinates = currentLatitude + "," + currentLongitude;
        }

        SharedPreferences.Editor editor = somename.edit();
        editor.putString("LastLocation", currentCoordinates).commit();

        Log.d("SomeName", "lastLocation start: " + currentCoordinates);
    }
}

My New code, used from a post on Stackoverflow, is not getting properly (GPS icon display on bar):

public void askLocation() {
    if (ContextCompat.checkSelfPermission(MainActivity.this,                                                 Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)         {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

        // Now create a location manager
        LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Looper looper = null;
        locationManager.requestSingleUpdate(criteria, locationListener, looper);

        String currentCoordinates = somename.getString("LastLocation", "0,0");
        Log.d("SomeName", "lastLocation askLocation: " + currentCoordinates);
    }
}

final LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        mLocation = location;
        String currentCoordinates = somename.getString("LastLocation", "0,0");

        if (location != null) {
            double currentLatitude = location.getLatitude();
            double currentLongitude = location.getLongitude();

            currentCoordinates = currentLatitude + "," + currentLongitude;
        }

        SharedPreferences.Editor editor = somename.edit();
        editor.putString("LastLocation", currentCoordinates).commit();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.d("Status Changed", String.valueOf(status));
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.d("Provider Enabled", provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        Log.d("Provider Disabled", provider);
    }
};

Thank you.

回答1:

You can try this method to get the location once when open the app or press a button and save on Shared Preferences.

               if (Constants.isOnline(getApplicationContext())) {
                        gps = new GPSTracker(v.getContext(),this);
                        if (gps.canGetLocation()) {

                            latitude = gps.getLatitude();
                            longitude = gps.getLongitude();
                            Log.e("Location ", "latitude : " + latitude + "longitude :" + longitude);

                        } else {
                            gps.showSettingsAlert();
                        }
                }

And the isOnline() is to check user has intenet connection on or not.

 public static boolean isOnline(Context c) {
    ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        Toast.makeText(c, "No Internet Connection.", Toast.LENGTH_SHORT).show();
    }
return false;

}