Wear OS - Как предложить пользователю диалоговое окно, чтобы включить или нет GPS - PullRequest
0 голосов
/ 19 марта 2019

Я пытаюсь предложить пользователю своего рода диалоговое окно, чтобы включить или нет GPS, не заходя в настройки, после запроса разрешения на использование местоположения (запрос разрешения уже работает). Что я делаю неправильно? Из официальной документации и некоторых ответов StackOverflow я написал этот код:

public class Indicazioni extends WearableActivity {

    private static final int REQUEST_CHECK_SETTINGS = 0x1;
    private GoogleApiClient googleApiClient;
    private boolean wearableConnected = false;
    private FusedLocationProviderClient fusedLocationClient;
    protected static final int REQUEST_LOCATION = 2;
    private TextView text1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_indicazioni);

        text1 = findViewById(R.id.text1);
        text1.setVisibility(View.GONE);

        // Enables Always-on
        setAmbientEnabled();

        //Se non ha il gps integrato, questa funzione non è disponibile
        //Check if there is builtin gps
        if (!hasGps()) {
            Log.d("Gps_HW_Error", "This hardware doesn't have GPS.");
            // Fall back to functionality that does not use location or
            // warn the user that location function is not available.
            Toast.makeText(this, "Gps integrato non rilevato, questa funzionalità è disattivata", Toast.LENGTH_LONG).show();
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
            finish();
        }
        //Se ha il gps integrato
        //if yes
        else {
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

            //Verifico i permessi per leggere la posizione
            //Check location permission
            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
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

            } else {

                //Creo una richiesta di configurazione gps
                LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                        .addLocationRequest(createLocationRequest());

                builder.setAlwaysShow(true);

                //Controllo se le condizioni della configurazione gps sono soddisfatte
                SettingsClient client = LocationServices.getSettingsClient(this);
                Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

                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.
                            fusedLocationClient.getLastLocation()
                                    .addOnSuccessListener(Indicazioni.this, location -> {
                                        // Got last known location. In some rare situations this can be null.
                                        if (location != null) {
                                            // Logic to handle location object
                                            double x = location.getLatitude();
                                            double y = location.getLongitude();
                                            //TODO verifica la correttezza dei dati x e d y
                                            //TODO cercare le fermate più vicine a questa coordinate
                                            System.out.print(x + ", " + y);
                                        }
                                    });

                        } catch (ApiException exception) {
                            /*MY PROBLEM IS HERE*/
                            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(
                                                Indicazioni.this,
                                                REQUEST_CHECK_SETTINGS);
                                    } 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;
                            }
                        }
                    }
                });
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final LocationSettingsStates states = LocationSettingsStates.fromIntent(getIntent());
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        // All required changes were successfully made ...
                        // ***REQUEST LAST LOCATION HERE***
                        Intent i = new Intent(this, Indicazioni.class);
                        startActivity(i);
                        finish();
                        break;
                    case Activity.RESULT_CANCELED:
                        // The user was asked to change settings, but chose not to ...
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode) {
            case REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Intent intent = new Intent(this, Indicazioni.class);
                    startActivity(intent);
                    finish();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "Il GPS è richiesto per utilizzare questa funzione", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(this, MainActivity.class);
                    startActivity(i);
                    finish();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    }

    private boolean hasGps() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);
    }

    protected LocationRequest createLocationRequest() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000); //Ogni quanti ms ricevere update
        locationRequest.setFastestInterval(5000); //Massimo intervallo in ms che l'app riesce a gestire
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        return  locationRequest;
    }
}

Возможно, ошибка в переключателе «switch (exception.getStatusCode ())», поскольку код состояния не существует (ошибка «не реализована в этой платформе»)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...