I use Goole play service location APIs and fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,looper); to get current location.
But sometimes it get a last location on Chinese phone like oppo、Xiaomi.(It has google plays on these phones)
Do have anyway to solve this question?
This is my code:
implementation 'com.google.android.gms:play-services-location:17.0.0'
Permissio:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
main code:(listener is a interface which created by me)
Intent locationServiceIntent = new Intent(context, LocationService .class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(locationServiceIntent);
} else {
context.startService(locationServiceIntent);
}
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
if(listener!=null) listener.RequestFail("當前位置無法獲取定位信號!");
cancel();
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
updateLoc(location);
cancel();
}
}
};
Looper looper = Looper.myLooper();
fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback,looper);
handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(listener!=null) listener.RequestFail("當前位置無法獲取定位信號!");
cancel();
}
},20000);
private void updateLoc(Location l) {
if (l != null) {
this.lng = l.getLongitude();
this.lat = l.getLatitude();
if(listener!=null){
listener.LocationUpdate(l.getLatitude()+","+l.getLongitude());
}
}
}