Reputation: 345
I am using google play services to get my last location. the project is working fine without force closing, however, it never gets any location. i assume it doesn't require GPS or Mobile network as google play services already has my last location based on these two strategies. my code is supposed to set my location in the text field. but it doesn't
public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
TextView tvLatlong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLatlong = (TextView) findViewById(R.id.textView1);
buildGoogleApiClient();
if(mGoogleApiClient!= null){
mGoogleApiClient.connect();
}
else
Toast.makeText(this, "Not connected...", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this, "Failed to connect...", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnected(Bundle arg0) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
tvLatlong.setText("Latitude: "+ String.valueOf(mLastLocation.getLatitude())+"Longitude: "+
String.valueOf(mLastLocation.getLongitude()));
}
}
@Override
public void onConnectionSuspended(int arg0) {
Toast.makeText(this, "Connection suspended...", Toast.LENGTH_SHORT).show();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
Upvotes: 1
Views: 1791
Reputation: 1297
NOTE: I am writing this answer in the year 2020 and the simplest way to get the current location/the last known location (both are more or less the same) is using "FusedLocationProviderClient".
First, we need to implement the following google play service dependency for location in our build.gradle file:
implementation com.google.android.gms:play-services-location:17.0.0
Add the permissions in the manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Then declare some variable and constant in our activity as below:
private lateinit var fusedLocationClient: FusedLocationProviderClient
private val PERMISSIONS_REQUEST_LOCATION = 1
Then in onCreate, get the FusedLocationProviderClient from LocationServices:
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
And then we can use the below "getCurrentLocation()" method to ask the location permissions from the user and get the current location once user allows the permissions:
private fun getCurrentLocation() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
),
PERMISSIONS_REQUEST_LOCATION
)
return
}
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
Toast.makeText(this, "Latitude: ${location?.latitude}, Longitude: ${location?.longitude}", Toast.LENGTH_SHORT).show()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
if (requestCode == PERMISSIONS_REQUEST_LOCATION) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation()
} else {
Toast.makeText(this, "You need to allow the permissions for Location", Toast.LENGTH_SHORT).show()
return
}
}
}
For more details please refer: https://developer.android.com/training/location/retrieve-current
Upvotes: 1
Reputation: 1147
GetLastLocation
is called by the FusedLocationApi and stores the last location based on the last client that had used it. If your app is the first client to use it, it probably will not have gotten the last location as quickly as you call your "OnConnected()" function.
Here you have some potential options:
1. Create A Checking Thread
You could implement a thread that checks for the last known location every X amount of seconds. Then, regardless of whether or not your app was the first to launch, you will eventually receive the last location.
2. Implement Location Listening
You could also implement Location Listening in your activity and update your location every time the OnLocationChanged
event is fired.
Upvotes: 2
Reputation: 3520
First onConnected does not get called immediately. It takes some time depending on various factors. So keep a log statement and check when onConnected is called.
Also if the device location is turned off then you will never receive any data back. It will be null.
Also it is not necessary that the google api client will hold your last location irrespective of whether you are connected to internet or not. It might and it might not. It only caches the last location and cache can be cleared anytime by the android OS.
Upvotes: 1