Come mostrare la finestra di dialogo di abilitazione della posizione come Google Maps?


129

Uso l'ultima versione di Google Play Services (7.0) e seguo i passaggi indicati nella loro guida e ho abilitato la finestra di dialogo sulla posizione come di seguito, che ha un pulsante "mai". La mia app ha bisogno della posizione obbligatoriamente, quindi non voglio mostrare "mai" all'utente, perché una volta che l'utente fa clic su "mai", non riesco più a ottenere la posizione o a richiedere nuovamente la posizione.

Dove come Google Maps ha solo il pulsante sì e no senza il pulsante mai, hai idea di come ottenere lo stesso?

L'immagine della mia app inserisci qui la descrizione dell'immagine

Immagine di Google Map inserisci qui la descrizione dell'immagine

Risposte:


149

LocationSettingsRequest.Builder ha un metodo setAlwaysShow(boolean show). Mentre il documento indica che al momento non sta facendo nulla (aggiornamento 2015-07-05: la documentazione Google aggiornata ha rimosso questa formulazione), l'impostazione builder.setAlwaysShow(true);abiliterà il comportamento di Google Maps: inserisci qui la descrizione dell'immagine

Ecco il codice che l'ha fatto funzionare:

if (googleApiClient == null) {
    googleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);

    //**************************
    builder.setAlwaysShow(true); //this is the key ingredient
    //**************************

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied. But could be fixed by showing the user
                    // a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(
                                getActivity(), 1000);
                    } catch (IntentSender.SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    break;
            }
        }
    });
}

Dalla documentazione di Android

Per Kotlin consultare qui: https://stackoverflow.com/a/61868985/12478830


1
@ MarianPaździoch è abbastanza sicuro che non è necessario, dal momento che il codice di esempio di Google su SettingsApi non lo richiede.
Kai,

1
@Kai Sì, il codice non è modificato su un Nexus 5. Usando i registri, vedo che quando i servizi di localizzazione sono inizialmente disattivati, colpisce sempre RESOLUTION_REQUIRED. Quindi una volta che accetto e abilito la posizione, colpisce SUCCESSe salta completamente onActivityResult(). Premendo Noo indietro, la finestra di dialogo scompare per un secondo, quindi si ricarica e si preme di RESOLUTION_REQUIREDnuovo. L'unico modo per sbarazzarsi della finestra di dialogo è accettare o chiudere e riaprire l'app.
pez,

2
@pez testato su Galaxy S4 con i servizi di Google Play 7.5.74 e funziona, la cancellazione non provoca la chiamata a RESOLUTION_REQUIRED. Il mio suggerimento sarebbe di aggiornare i servizi di gioco e riprovare. In caso contrario, avvia una nuova domanda StackOverflow per vedere se altri hanno riscontrato e risolto questo problema.
Kai,

2
@Kai ha funzionato per me, ma cosa succede se un utente ha premuto no. Come mostrare di nuovo la finestra di dialogo o aggiungere un codice lì se premuto no. Qualsiasi aiuto sarà molto apprezzato.
Gurpreet singh,

1
NOTA: la tua attività launchModeNON può essere impostata su singleInstancealtrimenti NON funzionerà. La finestra di dialogo non verrà mai visualizzata e onActivityResultverrà chiamata automaticamente. NON AVERE android:launchMode="singleInstance"per la tua attività in AndroidManifest. L'ho imparato in modo molto difficile dopo 3 ore
ᴛʜᴇᴘᴀᴛᴇʟ

55

Vorrei aggiungere alcune modifiche alla risposta di Kai per coloro che stanno cercando di gestire i pulsanti Sì / No.

Dichiara questa costante nella tua attività

protected static final int REQUEST_CHECK_SETTINGS = 0x1;

chiama il settingsrequest()tuo onStart ()

public void settingsrequest()
    {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                final LocationSettingsStates state = result.getLocationSettingsStates();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        // Location settings are not satisfied. But could be fixed by showing the user
                        // a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),
                            // and check the result in onActivityResult().
                            status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            // Ignore the error.
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.
                        break;
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        startLocationUpdates();
                        break;
                    case Activity.RESULT_CANCELED:
                        settingsrequest();//keep asking if imp or do whatever
                        break;
                }
                break;
        }
    }

1
ottenuto dalla documentazione ufficiale: developers.google.com/android/reference/com/google/android/gms/… se è necessario aggiungere solo mappe, per utilizzare ciò è necessario aggiungere quelle librerie (senza importare l'intera libreria dei servizi di gioco ): compila "com.google.android.gms: play-services-maps: 9.0.2" compila "com.google.android.gms: play-services-location: 9.0.2 '
MatPag,

come gestire l'evento click di questa finestra di dialogo e non devo mai mostrare il pulsante mai nella finestra di dialogo
M.Yogeshwaran,

rimuovere la riga settingsrequest () dalla custodia dell'interruttore in ActivityOnResult .. È quello che stai chiedendo ???
Veer3383,

Se clicco su nessun pulsante della finestra di dialogo, quella finestra di dialogo continua continuamente. Rimuovo già la riga settingsrequest () dalla custodia dell'interruttore in ActivityOnResult .. quindi perché viene visualizzata continuamente?
Asmi,

Potrebbe essere necessario pulire il progetto.
Veer3383,

25

LocationServices.SettingsApi è obsoleto, quindi usiamo SettingsClient

    LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10);
        mLocationRequest.setSmallestDisplacement(10);
        mLocationRequest.setFastestInterval(10);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new 
        LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);

Quindi controlla se le impostazioni della posizione corrente sono soddisfatte. Creare l'attività LocationSettingsResponse:

        Task<LocationSettingsResponse> task=LocationServices.getSettingsClient(this).checkLocationSettings(builder.build());

Quindi aggiungi Listener

task.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
                    public void onComplete(Task<LocationSettingsResponse> task) {
                        try {
                            LocationSettingsResponse response = task.getResult(ApiException.class);
                            // All location settings are satisfied. The client can initialize location
                            // requests here.

                        } catch (ApiException exception) {
                            switch (exception.getStatusCode()) {
                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                    // Location settings are not satisfied. But could be fixed by showing the
                                    // user a dialog.
                                    try {
                                        // Cast to a resolvable exception.
                                        ResolvableApiException resolvable = (ResolvableApiException) exception;
                                        // Show the dialog by calling startResolutionForResult(),
                                        // and check the result in onActivityResult().
                                        resolvable.startResolutionForResult(
                                                HomeActivity.this,
                                                101);
                                    } catch (IntentSender.SendIntentException e) {
                                        // Ignore the error.
                                    } catch (ClassCastException e) {
                                        // Ignore, should be an impossible error.
                                    }
                                    break;
                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                    // Location settings are not satisfied. However, we have no way to fix the
                                    // settings so we won't show the dialog.
                                    break;
                            }
                        }
                    }
                });

Aggiunto onActivityResult

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case 101:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        Toast.makeText(HomeActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(HomeActivity.this,"Canceled",Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

Fare riferimento al collegamento SettingsClient


1
Controllare stackoverflow.com/a/53277287 @BadLoser Utilizzando SettingsClient
Ketan Ramani

Qual è il nome della dipendenza da importare? Impossibile risolvere il simbolo Attività.
Denis,

L'ho trovato: implementazione "com.google.android.gms: play-services-task: 16.0.1"
Denis

@Denis, potrei usare implementation 'com.google.android.gms:play-services-location:16.0.0'invece.
CoolMind

25

Funziona in modo simile a Google Maps?
Codice sorgente: https://drive.google.com/open?id=0BzBKpZ4nzNzUOXM2eEhHM3hOZk0

Aggiungi dipendenza nel file build.gradle:

compile 'com.google.android.gms:play-services:8.3.0'

O

compile 'com.google.android.gms:play-services-location:10.0.1'

inserisci qui la descrizione dell'immagine

public class LocationOnOff_Similar_To_Google_Maps extends AppCompatActivity {

    protected static final String TAG = "LocationOnOff";


    private GoogleApiClient googleApiClient;
    final static int REQUEST_LOCATION = 199;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setFinishOnTouchOutside(true);

        // Todo Location Already on  ... start
        final LocationManager manager = (LocationManager) LocationOnOff_Similar_To_Google_Maps.this.getSystemService(Context.LOCATION_SERVICE);
        if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
            finish();
        }
        // Todo Location Already on  ... end

        if(!hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)){
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not Supported",Toast.LENGTH_SHORT).show();
        }

        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(LocationOnOff_Similar_To_Google_Maps.this)) {
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps not enabled",Toast.LENGTH_SHORT).show();
            enableLoc();
        }else{
            Log.e("keshav","Gps already enabled");
            Toast.makeText(LocationOnOff_Similar_To_Google_Maps.this,"Gps already enabled",Toast.LENGTH_SHORT).show();
        }
    }


    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null)
            return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null)
            return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void enableLoc() {

        if (googleApiClient == null) {
            googleApiClient = new GoogleApiClient.Builder(LocationOnOff_Similar_To_Google_Maps.this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(Bundle bundle) {

                        }

                        @Override
                        public void onConnectionSuspended(int i) {
                            googleApiClient.connect();
                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(ConnectionResult connectionResult) {

                            Log.d("Location error","Location error " + connectionResult.getErrorCode());
                        }
                    }).build();
            googleApiClient.connect();

            LocationRequest locationRequest = LocationRequest.create();
            locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            locationRequest.setInterval(30 * 1000);
            locationRequest.setFastestInterval(5 * 1000);
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(locationRequest);

            builder.setAlwaysShow(true);

            PendingResult<LocationSettingsResult> result =
                    LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult(LocationOnOff_Similar_To_Google_Maps.this, REQUEST_LOCATION);

                                finish();
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }
    }

}

è un piacere
Keshav Gera,

1
Vedi Broadcast Receiver Post Molto utile e come me stackoverflow.com/questions/15698790/…
Keshav Gera,

Soluzione perfetta
Lalit Sharma,

Grazie Lalit Sharma
Keshav Gera il

Puoi aggiornare il link, adesso è rotto, pubblica invece il codice in GitHub
Manoj Perumarath,

7

Ola Cabs utilizza l'API delle impostazioni appena rilasciata per ottenere questa funzionalità. Come per la nuova API, l'utente non è tenuto a navigare nella pagina delle impostazioni per abilitare i servizi di localizzazione fornendo una perfetta integrazione per la stessa. Si prega di leggere sotto per maggiori dettagli:

https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi


questo sembra uguale alla risposta veer3383. per favore, correggimi se sbaglio
rakesh kashyap,

@rakeshkashyap sì, è lo stesso
MatPag,

Volevo sapere se è possibile fare quanto segue: * impostare un timeout per ottenere la posizione. * controlla nell'API delle impostazioni GPS, se tutti i sensori richiesti sono abilitati e mostra il messaggio di conseguenza. * Se questo è possibile, come impostare un timeout.? Non sono stato in grado di trovare una tale impostazione durante la creazione dell'API
rakesh kashyap il

Ciao, ho problemi con il caricamento della mappa una seconda volta dopo aver acceso il GPS dallo stato Off, per favore, qualcuno mi aiuti: stackoverflow.com/questions/44368960/… Grazie.
Jaimin Modi,

3
SettingsAPIè stato deprecato, ora utilizzi SettingsClient developers.google.com/android/reference/com/google/android/gms/…
Saik Caskey

7

Dipendenza

compile 'com.google.android.gms:play-services-location:10.0.1'

Codice

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    public static final int REQUEST_LOCATION=001;

    GoogleApiClient googleApiClient;

    LocationManager locationManager;
    LocationRequest locationRequest;
    LocationSettingsRequest.Builder locationSettingsRequest;
    Context context;


    PendingResult<LocationSettingsResult> pendingResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "Gps is Enabled", Toast.LENGTH_SHORT).show();

        } else {
            mEnableGps();
        }

    }

    public void mEnableGps() {
        googleApiClient = new GoogleApiClient.Builder(context)
                .addApi(LocationServices.API).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        googleApiClient.connect();
        mLocationSetting();
    }

    public void mLocationSetting() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(1 * 1000);
        locationRequest.setFastestInterval(1 * 1000);

        locationSettingsRequest = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

        mResult();

    }

    public void mResult() {
        pendingResult = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, locationSettingsRequest.build());
        pendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                Status status = locationSettingsResult.getStatus();


                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        // All location settings are satisfied. The client can initialize location
                        // requests here.

                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                        try {

                            status.startResolutionForResult(MainActivity.this, REQUEST_LOCATION);
                        } catch (IntentSender.SendIntentException e) {

                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        // Location settings are not satisfied. However, we have no way to fix the
                        // settings so we won't show the dialog.


                        break;
                }
            }

        });
    }


    //callback method
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
        switch (requestCode) {
            case REQUEST_LOCATION:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made
                        Toast.makeText(context, "Gps enabled", Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to
                        Toast.makeText(context, "Gps Canceled", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        break;
                }
                break;
        }
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

4

Puoi anche aggiungere diverse richieste di localizzazione per Builder per ottenere la finestra di dialogo "Usa GPS, Wi-Fi e reti mobili per la posizione" anziché semplicemente "Usa GPS per la posizione"

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY))
                .addLocationRequest(createLocationRequest(LocationRequest.PRIORITY_HIGH_ACCURACY))
                .setAlwaysShow(true);

PendingResult<LocationSettingsResult> result =
                LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

Nel mio caso è sufficiente utilizzare PRIORITY_HIGH_ACCURACY per ottenere la frase "Usa GPS, Wi-Fi e reti mobili per la posizione". Ma è strano che funzioni su un dispositivo reale ma nel simulatore no. Nella frase del simulatore è sempre senza "Usa GPS" all'inizio, anche se vedo che il dispositivo simulatore ha il GPS.
mikep,

0

In Kotlin, usa questo codice:

import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.common.api.PendingResult
import com.google.android.gms.common.api.Status
import com.google.android.gms.location.*

class MainActivity : AppCompatActivity() {
    private var googleApiClient: GoogleApiClient? = null
    private val REQUESTLOCATION = 199
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableLoc()
    }
    private fun enableLoc() {
        googleApiClient = GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks {
                override fun onConnected(bundle: Bundle?) {}
                override fun onConnectionSuspended(i: Int) {
                    googleApiClient?.connect()
                }
            })
            .addOnConnectionFailedListener {
            }.build()
        googleApiClient?.connect()
        val locationRequest = LocationRequest.create()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        locationRequest.interval = 30 * 1000.toLong()
        locationRequest.fastestInterval = 5 * 1000.toLong()
        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)
        builder.setAlwaysShow(true)
        val result: PendingResult<LocationSettingsResult> =
            LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build())
        result.setResultCallback { result ->
            val status: Status = result.status
            when (status.statusCode) {
                LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
                    status.startResolutionForResult(
                        this@MainActivity,
                        REQUESTLOCATION
                    )
                } catch (e: IntentSender.SendIntentException) {
                }
            }
        }
    }
    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUESTLOCATION -> when (resultCode) {
                Activity.RESULT_OK -> Log.d("abc","OK")
                Activity.RESULT_CANCELED -> Log.d("abc","CANCEL")
            }
        }
    }
}

0

Controlla la mia soluzione molto semplice per ottenere la posizione dell'utente in primo piano.

  1. Finestra di dialogo Impostazioni GPS
  2. Posizione dell'utente con dati in tempo reale.
  3. La classe LocationUtility è consapevole del ciclo di vita delle attività per mettere in pausa / riprendere gli aggiornamenti della posizione.
  4. Posizione con l'ultimo FusedLocationProviderClient

https://github.com/Maqsood007/UserLocation-Android/blob/master/app/src/main/java/jetpack/skill/userlocation_android/utils/LocationUtility.kt

inserisci qui la descrizione dell'immagine

inserisci qui la descrizione dell'immagine

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.