O problema é que nas versões acima (testei nas APIs 23, 24, 27) ,(na API 29 ta funcionando) o deburger mostra centenas de passagens pelo onLocationAvailability
pois botei um Log.i.
Isso retorna sempre TRUE como segue abaixo na versão kitkat API 19 :
I/locationAvailability :: true
I/Location pos ->: 38.4219983 -122.08430/08/2019 23:21:39
I/locationAvailability :: false
I/Location pos ->: 38.4219983 -122.08430/08/2019 23:22:10
I/locationAvailability :: true
Process 3298 terminated.
Mas nas versões acima da API 23 temos :
I/Location Active: true
I/Location Active: true
I/Location Active: true
I/Location Active: true
I/Location Active: true
I/Location Active: true
I/Location Active: true ...... ao infinito.
Nem mostra a a posição de latitude e longitude ! Será que tenho que usar outra implementação para as versões 23 e acima ??? Percebi que na versão 23, 24 e 25 o aplicativo recebe as permissões, posso ver dentro do emulador,permissões ativadas. Mas a função volta a atuar e abrir as caixas de dialogo para pedir de novo as permissões.
protected void onResume() {
super.onResume();
addDataHora();
if(Build.VERSION.SDK_INT >= VERSION_CODES.M) {
if (!hasPhonePermissions( this, Permissions )) {
ActivityCompat.requestPermissions( this,Permissions,Permission_All );
}else{
TelephonyManager tMgr = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
if (tMgr != null) {
@SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
phoneNumber = mPhoneNumber;
}
}
}
int errorcode = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable( MainActivity.this );
switch (errorcode) {
case ConnectionResult.SERVICE_MISSING:
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
case ConnectionResult.SERVICE_DISABLED:
GoogleApiAvailability.getInstance().getErrorDialog( MainActivity.this, errorcode, 0, new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
} ).show();
break;
case ConnectionResult.SUCCESS:
break;
}
if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
return;
}
client.getLastLocation().addOnSuccessListener( new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
Log.i( "location - ", "null" );
}
}
} ).addOnFailureListener( new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
} );
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval( 20000 );
locationRequest.setFastestInterval( 10000 ); //location computed for other apps
locationRequest.setPriority( LocationRequest.PRIORITY_HIGH_ACCURACY ); //uso preciso com gps.
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest( locationRequest );
SettingsClient settingsClient = LocationServices.getSettingsClient( this );
settingsClient.checkLocationSettings( builder.build() ).addOnSuccessListener( new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i( "Location Active ", locationSettingsResponse.getLocationSettingsStates().isNetworkLocationPresent() + "" );
}
} ).addOnFailureListener( new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult( MainActivity.this, 10 );
} catch (IntentSender.SendIntentException el) {
//todo
}
}
}
} );
//Listener pega sempre a nova posição do provider. Kill app se local é nulo.
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.i( "Local position -> ", "local is null");
return;
}
//procurar na lista de localização.
for (Location location : locationResult.getLocations()) {
addDataHora();
Log.i( "Location pos -> ", location.getLatitude() + " " + location.getLongitude() + DataTime );
}
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i( "locationAvailability : ", locationAvailability.isLocationAvailable() + "" );
}
};
client.requestLocationUpdates( locationRequest, locationCallback, null );
Context context = this;
SharedPreferences sharedPreferences = getSharedPreferences( PREF_NAME,MODE_PRIVATE );
String tentativas = sharedPreferences.getString( "tentativas","0" );
atemptcount = Integer.parseInt( tentativas );
// Toast.makeText( MainActivity.this, "Load config: "+ tentativas, Toast.LENGTH_LONG).show();
}
//FIM RESUME
@Override
protected void onPause() {
super.onPause();
if (locationCallback != null) {
stopLocationUpdate();
}
/** Remove recursos para liberar memória */
private void stopLocationUpdate() {
client.removeLocationUpdates( locationCallback );
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@RequiresApi(api = VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == PERMISSION_CODE){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText( MainActivity.this, "Permissão aceita" , Toast.LENGTH_SHORT).show();
}else{
Toast.makeText( MainActivity.this, "Permissão negada" , Toast.LENGTH_SHORT).show();
}
}
}