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 android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; /** * 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) { } }
Help: https://developer.android.com/training/location/retrieve-current.html

"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.