Connect to Current Location Android Studio

Asked

Viewed 2,956 times

1

I’m developing a App Android that contains a map and that picks up my location, but in some devices it does not activate this function, for it to work you need to click the button Local for example Samsung J5. How can I make this button automatically activate when I open the map?

Note: It is a simple map, only some markers and my location.

From the Android 6.0 I already have permission to open the map in the demarcated position, only my location does not. I put a link with the image of what I want you to call automatically. Remember that when I open the map it asks for permission but does not activate the location only the map.

enter image Description here

This is my map:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;

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


    ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
            MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

}


@Override
public void onRequestPermissionsResult(
        int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MapsActivity.this,
                        "Atenção! Ative o Local...",Toast.LENGTH_LONG).show();

            } else {
                Toast.makeText(MapsActivity.this,
                        "Permissão de Localização Negada, ...:(",Toast.LENGTH_LONG).show();
            }
            return;
        }
    }
}


@Override
public void onMapReady(GoogleMap map) {
    // Tipo do Mapa
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  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.
        return;
    }
    //Minha Posição Atual
    map.setMyLocationEnabled(true);

    // Posicao inicial onde o mapa abre
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(
            new LatLng(-27.3246787, -53.4387937), (float) 14.5));

    LatLng sydney = new LatLng(-27.356857, -53.396316);

    map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));

    map.moveCamera(CameraUpdateFactory.newLatLng(sydney));


    LatLng fw = new LatLng(-27.369282, -53.402667);
    map.addMarker(new MarkerOptions()
            .position(fw)
            .title("Marker in Sydney")
            .snippet("Population: 4,137,400"));
    }
}
  • You want to focus on the map where you created the Marker (-27.3246787, -53.4387937) or on your current gps position of the user’s device?

  • I want the https://i.stack.Imgur.com/Wxa6o.jpg button on this link

  • I’m sorry Rafa, I don’t understand where this button is, would it be in the phone settings area? Is that button that activates or disables the location service?

  • That’s right, I’ve reviewed the net and I found nothing that activates the button, I found some examples like Activate wifi for example, but this did not find anything

  • So Rafa, I get it. I don’t think there is a public and reliable API for that, you have to delegate this task to the user. The most you can do reliably is to take the user to the location settings screen and instruct him to activate the location service.

1 answer

4


So, you cannot activate the "Fine Location" of your user’s smartphone. This goes against good Android practice, where the software cannot interact with the hardware without the user actively allowing it (by clicking a button, for example)

From what I see of your app 'Fine Location' is very important, right?

This method here solves your problem in an elegant way:

private void createNoGpsDialog(){
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        Intent callGPSSettingIntent = new Intent(
                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(callGPSSettingIntent);
                        break;
                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mNoGpsDialog = builder.setMessage("Por favor ative seu GPS para usar esse aplicativo.")
                .setPositiveButton("Ativar", dialogClickListener)
                .create();
        mNoGpsDialog.show();

    }

Basically you create a Dialog and ask your user to activate his GPS. Ai, when it clicks on "Activate" it will go to the "Settings" of the phone and can activate the GPS.

Put it inside your onCreate or your onMapReady and it’ll work great.

  • Sensational, very good even I had not thought of it, it worked very well, but he asks every time I enter the map to activate even being active, how could I fix it?

  • I managed to solve with this, I did a test and treatment of exception. Thank you very much helped me very much. Strong Embrace Try { checkGps(); } catch (Exception e) { createNoGpsDialog(); } //----------------------------------- public void checkGps() throws Exception { Locationmanager; manager = (Locationmanager) getSystemService(Context.LOCATION_SERVICE); if (!manager.isProviderEnabled(Locationmanager.GPS_PROVIDER)) { throw new Exception("gps off"); } }

Browser other questions tagged

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