12

I want to make my map focus on my current location when opening the MapActivity. I have a problem with a specific line:

mMap.setMyLocationEnabled(true);  

Call requires permission which may be rejected by user:code should explicitly check to see if permission is availabe with ('checkPermission') or explicitly handle with potential 'SecurityException'.

How can I resolve this problem? I've read some things when I searched this issue and I couldn't find something helpful.

This is the full code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String FIREBASE_URL="https://haerev.firebaseio.com/";
private Firebase firebaseRef;
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps2);
    Firebase.setAndroidContext(this);
    firebaseRef = new Firebase(FIREBASE_URL);


    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    setUpMapIfNeeded();

}

private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {


            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub

                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });

        }
    }
}

After reading some comments, and read this issue:http://developer.android.com/training/permissions/requesting.html

I added these lines:

 private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();

        if (ContextCompat.checkSelfPermission(MapsActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {


            if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

               checkSelfPermission("You have to accept to enjoy the most hings in this app");
            } else {


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

            }
        }

        mMap.setMyLocationEnabled(true);
        // Check if we were successful in obtaining the map.
        if (mMap != null) {


            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub

                    mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                }
            });

        }
    }
}

But now I have a new problem. It isn't recognize the line

"MY_PERMISSION_REQUEST_ACCESS_FINE_LOCATION".

I guess I'm using it in a wrong way. How should I use it?

Ralph
  • 9,284
  • 4
  • 32
  • 42
Gilad Neiger
  • 319
  • 1
  • 3
  • 14
  • what is the problem with that line? – tyczj Mar 18 '16 at 17:57
  • @tyczj sorry I forgot that line. I added the error above. – Gilad Neiger Mar 18 '16 at 18:08
  • 1
    you should look at how to deal with runtime permissions http://developer.android.com/training/permissions/requesting.html – tyczj Mar 18 '16 at 18:10
  • @tyczj I now checked my build.gradle file and I saw that it compiles sdk 23 version. Maybe this is the problem? When I created my project I set my API project to 15. What should I do? – Gilad Neiger Mar 18 '16 at 18:27
  • you should always target the latest sdk version and fix your code according to that version – tyczj Mar 18 '16 at 18:30
  • @tyczj ok, I added more code above, please read :) – Gilad Neiger Mar 18 '16 at 18:36
  • may i ask you? why u used in your app firebase(he help you to add your markers or somthing else)? – Morozov Nov 15 '16 at 18:51
  • @GiladNeiger I don't know if you still need this, but you should take a look at this: [Permissions](http://stackoverflow.com/questions/32224534/access-fine-location-permission-error-emulator-only), the second answer. You should create an `onRequestPermissionResult()` in order for the solution to work. – Kryptonous Jan 11 '17 at 15:58

4 Answers4

13

After massive research on the web, this is what is working for me:

 private void setUpMapIfNeeded() {
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
            Toast.makeText(MapsActivity.this, "You have to accept to enjoy all app's services!", Toast.LENGTH_LONG).show();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
            }
        }

        if (mMap != null) {


            mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

                @Override
                public void onMyLocationChange(Location arg0) {
                    // TODO Auto-generated method stub

                    CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
                    CameraUpdate zoom=CameraUpdateFactory.zoomTo(12);

                    mMap.moveCamera(center);
                    mMap.animateCamera(zoom);
                }
            });

        }
    }
}
Gilad Neiger
  • 319
  • 1
  • 3
  • 14
3

More clear Implementation:

    @Override
public void onMapReady(GoogleMap googleMap) {
    MapsInitializer.initialize(getContext());
    mGoogleMap = googleMap;
    if(checkPermission())
    mGoogleMap.setMyLocationEnabled(true);
    else askPermission();
}



 // Check for permission to access Location
    private boolean checkPermission() {
        Log.d(TAG, "checkPermission()");
        // Ask for permission if it wasn't granted yet
        return (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED );
    }
    // Asks for permission
    private void askPermission() {
        Log.d(TAG, "askPermission()");
        ActivityCompat.requestPermissions(
                getActivity(),
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                REQ_PERMISSION
        );
    }

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.d(TAG, "onRequestPermissionsResult()");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch ( requestCode ) {
            case REQ_PERMISSION: {
                if ( grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED ){
                    // Permission granted
                    if(checkPermission())
                    mGoogleMap.setMyLocationEnabled(true);

                } else {
                    // Permission denied

            }
            break;
        }
    }
}
LOG_TAG
  • 19,894
  • 12
  • 72
  • 105
0

Actually, this code was auto-generated by Android Studio after I watched the solutions. I'm working in a Fragment and so I had to change the "this" to "getContext"

try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

mMapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap mMap) {
            googleMap = mMap;


            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
               Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
               return; 
}
-1

try this
Either set

targetSdkVersion 22

Or ask for runtime permission refer here:-http://coderzpassion.com/android-new-runtime-permissions/ Hope it helps thanks

Jagjit Singh
  • 1,909
  • 1
  • 14
  • 19