Android 6 problem with map.setMyLocationEnabled(true)

Asked

Viewed 379 times

4

I have a problem with the Google Api 23+ specifically in the method mapa.setMyLocationEnabled(true);

You need permission to run, and on android 6.0+, I can’t implement the new permissions method.

 @Override
public void onMapReady(GoogleMap googleMap) {

    mapa = googleMap;
    mapa.setOnCameraChangeListener(getCameraChangeListener());
    verificaConexao();

    Toast.makeText(getActivity(), "versão 0.007", Toast.LENGTH_SHORT).show();

    try {
        mapa.setMyLocationEnabled(true);
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                TEMPO_MINIMO_UPDATE,
                DISTANCIA_MINIMA_PARA_UPDATE,
                new MyLocationListener()
        );  //LocationManager.NETWORK_PROVIDER ou LocationManager.GPS_PROVIDER ou LocationManager.PASSIVE_PROVIDER

    } catch (SecurityException ex) {
        Toast.makeText(getActivity(), "Minha localização entrou em catch" + ex, Toast.LENGTH_LONG).show();
    }

1 answer

4


If the application needs to access the user’s location, it is necessary to request permission by adding the relevant Android location permission to the application.

Add permissions to the application manifest

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Request runtime permissions

Android 6.0 (Marshmallow) introduced a new permissions processing model that optimizes the process for users when they install and update applications. If the application is directed at API level 23 or later, you can use the new permissions template.

create the class Allow Location **The class will show the dialog and necessary information that the user needs to know.

public class PermitirLocalizacao {

public static void requestPermission(MapsActivity activity, int requestId,
                                     String permission, boolean finishActivity) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
        PermitirLocalizacao.RationaleDialog.newInstance(requestId, finishActivity)
                .show(activity.getSupportFragmentManager(), "dialog");
    } else {
        ActivityCompat.requestPermissions(activity, new String[]{permission}, requestId);

    }
}

public static boolean isPermissionGranted(String[] grantPermissions, int[] grantResults,
                                          String permission) {
    for (int i = 0; i < grantPermissions.length; i++) {
        if (permission.equals(grantPermissions[i])) {
            return grantResults[i] == PackageManager.PERMISSION_GRANTED;
        }
    }
    return false;
}

public static class PermissionDeniedDialog extends DialogFragment {

    private static final String ARGUMENT_FINISH_ACTIVITY = "finish";

    private boolean mFinishActivity = false;

    public static PermissionDeniedDialog newInstance(boolean finishActivity) {
        Bundle arguments = new Bundle();
        arguments.putBoolean(ARGUMENT_FINISH_ACTIVITY, finishActivity);

        PermissionDeniedDialog dialog = new PermissionDeniedDialog();
        dialog.setArguments(arguments);
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mFinishActivity = getArguments().getBoolean(ARGUMENT_FINISH_ACTIVITY);

        return new AlertDialog.Builder(getActivity())
                .setMessage("Este exemplo requere uma permissão para acessar \\'a minha localização\\' layer. Please try again and grant access to use the location.\\nIf the permission has been permanently denied, it can be enabled from the System Settings &gt; Apps &gt; \\'Google Maps API Demos\\'")
                .setPositiveButton(android.R.string.ok, null)
                .create();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mFinishActivity) {
            Toast.makeText(getActivity(), "A permissão é necessária para continuar.",
                    Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }
    }
}

public static class RationaleDialog extends DialogFragment {

    private static final String ARGUMENT_PERMISSION_REQUEST_CODE = "requestCode";

    private static final String ARGUMENT_FINISH_ACTIVITY = "finish";

    private boolean mFinishActivity = false;

    public static RationaleDialog newInstance(int requestCode, boolean finishActivity) {
        Bundle arguments = new Bundle();
        arguments.putInt(ARGUMENT_PERMISSION_REQUEST_CODE, requestCode);
        arguments.putBoolean(ARGUMENT_FINISH_ACTIVITY, finishActivity);
        RationaleDialog dialog = new RationaleDialog();
        dialog.setArguments(arguments);
        return dialog;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle arguments = getArguments();
        final int requestCode = arguments.getInt(ARGUMENT_PERMISSION_REQUEST_CODE);
        mFinishActivity = arguments.getBoolean(ARGUMENT_FINISH_ACTIVITY);

        return new AlertDialog.Builder(getActivity())
                .setMessage("O acesso ao serviço de localização é necessário para demonstrar a funcionalidade.")
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(getActivity(),
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},                              requestCode);
                        mFinishActivity = false;
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .create();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mFinishActivity) {
            Toast.makeText(getActivity(),
                    "permissão Localização é necessário para esta demonstração",
                    Toast.LENGTH_SHORT)
                    .show();
            getActivity().finish();
        }
    }
}

}

On your map Activity:

public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback {

private GoogleMap mMap;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;


@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    enableMyLocation();
}


private void enableMyLocation() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        PermitirLocalizacao.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                Manifest.permission.ACCESS_FINE_LOCATION, true);
    } else if (mMap != null) {
        mMap.setMyLocationEnabled(true);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
        return;
    }

    if (PermitirLocalizacao.isPermissionGranted(permissions, grantResults,
            Manifest.permission.ACCESS_FINE_LOCATION)) {
        enableMyLocation();
    } else {resume.
        mPermissionDenied = true;
    }
}

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    if (mPermissionDenied) {
        showMissingPermissionError();
        mPermissionDenied = false;
    }
}

private void showMissingPermissionError() {
    PermitirLocalizacao.PermissionDeniedDialog
            .newInstance(true).show(getSupportFragmentManager(), "dialog");
}

That code solved my problem, I hope it solves yours too, strong hug.

Source: Google Android Developers

  • thank you very much Maico perfect answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.