Android - Get user location with Google Api Client

/*Usage: LocatorGPS locatorGPS = LocatorGPS.getInstance(this); Location location = locatorGPS.getLocation(); */ package com.stonemanhero.navijac; import android.Manifest; import android.content.Context; import; import android.location.Location; import android.os.Bundle; import; import; import; import; import; import; /** * Created by stone on 10.6.16.. * Singleton class to get user location via Google Api Client */ public class LocatorGPS implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private static LocatorGPS instance; private static GoogleApiClient mGoogleApiClient; private static Context context; private LocatorGPS() {} static { instance = new LocatorGPS(); } public static LocatorGPS getInstance(Context _context) { context = _context; mGoogleApiClient = new GoogleApiClient.Builder(context) .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) context) .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) context) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); return instance; } //Check if permission is granted and get Location public Location getLocation() { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return null; } else { if(mGoogleApiClient.isConnected()) { Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); return location; } else { return null; } } } @Override public void onConnected(@Nullable Bundle bundle) { } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } }

"To access the fused location provider, your app's development project must include Google Play services."
"Apps that use location services must request location permissions."

1 Response

thanks for shared.

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.