I'm trying to get the current location icon on top of the map. However when i run the app the map looks;
The other case is when i wrote this line;
mGoogleMap.setMyLocationEnabled(true);
I could't get any 'Add Permission Check' warning like;
. So i wrote these permissions by hand.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
I don't know its right way to do that or not. Here is my full code;
private Activity activity = this;
ActionBarDrawerToggle drawerToggle;
DrawerLayout drawerLayout;
RecyclerView recyclerMenu;
AdapterMenu obAdapter;
private Tracker mTracker;
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_harita);
if (googleServicesAvailable()) {
initmap();
} else {
//No google maps layout
}
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvailable = api.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS)
return true;
else if (api.isUserResolvableError(isAvailable)) {
Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
dialog.show();
} else
Toast.makeText(this, "Can't connect to play services", Toast.LENGTH_LONG).show();
return false;
}
private void initmap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
mGoogleMap.setMyLocationEnabled(true);
}
public void geoLocate(View view) throws IOException {
EditText searchtext = (EditText) findViewById(R.id.editAra);
String location = searchtext.getText().toString();
Geocoder geocoder = new Geocoder(this);
List<Address> list = geocoder.getFromLocationName(location, 1);
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double latitude = address.getLatitude();
double longitude = address.getLongitude();
goToLocationZoom(latitude, longitude, 15);
}
private void goToLocationZoom(double latitude, double longitude, float zoom) {
LatLng LatLang = new LatLng(latitude, longitude);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LatLang, zoom);
mGoogleMap.moveCamera(update);
}
}
If user has not granted for location permissions, you should request for it explicitly (Only required for Android M and above). Then you should override onRequestPermissionsResult and manage the results.
Here you have a working example for you are asking for:
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String[] LOCATION_PERMISSIONS = {
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
private static final int LOCATION_PERMISSIONS_REQUEST_CODE = 1;
private GoogleMap mGoogleMap;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onMapReady(final GoogleMap googleMap) {
this.mGoogleMap = googleMap;
if (hasGrantedLocationPermissions()) {
showCurrentLocationMapControl();
} else {
requestForLocationPermissions();
}
}
#Override
public void onRequestPermissionsResult(final int requestCode, final #NonNull String[] permissions, final #NonNull int[] grantResults) {
if (requestCode == LOCATION_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length == LOCATION_PERMISSIONS.length) {
for (final int grantResult : grantResults) {
if (PackageManager.PERMISSION_GRANTED != grantResult) {
return;
}
}
showCurrentLocationMapControl();
}
}
}
private boolean hasGrantedLocationPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestForLocationPermissions() {
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, LOCATION_PERMISSIONS_REQUEST_CODE);
}
private void showCurrentLocationMapControl() {
if (null != this.mGoogleMap) {
this.mGoogleMap.setMyLocationEnabled(true);
}
}
}
Do not forget to define needed permissions in manifest file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Related
I am developing an android application that uses Google Maps.
The expected behavior is:
Enter the map activity
Ask user to use his location
Show nearby places
When I run the application using an emulator in Android Studio , the flow is the expected one (Pixel 2 Api 30), but when I run it on my phone, the permission is only asked for after I stop the application run.
Why is this happening?
Acitivity
public class NearbyPharmaciesActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int MY_PERMISSION_CODE = 1000;
private GoogleMap mMap;
private double latitude, longitude;
private Location lastLocation;
private Marker marker;
private GoogleMapsApi mService;
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationCallback locationCallback;
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_pharmacies);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// Init service
mService = RetrofitGoogleMaps.getApi();
// Request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_pharmacy:
nearbyPlaces("pharmacy");
break;
default:
break;
}
return true;
}
});
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
private boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) && ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
} else {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION
}, MY_PERMISSION_CODE);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_CODE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
buildLocationCallBack();
buildLocationRequest();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
}
break;
}
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(300000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setSmallestDisplacement(30);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildLocationCallBack() {
System.out.println("Reached here");
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
lastLocation = locationResult.getLastLocation();
System.out.println("last location: " + lastLocation.toString());
if (marker != null) {
marker.remove();
}
latitude = lastLocation.getLatitude();
longitude = lastLocation.getLongitude();
System.out.println("LATITUDE: " + latitude);
System.out.println("LONGITUDE: " + longitude);
LatLng latLng = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your position")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
marker = mMap.addMarker(options);
//LocationData locationData = new LocationData(latitude, longitude);*/
//mDatabase.child("location").child(userId).child(String.valueOf(new Date().getTime())).setValue(locationData);
//getMarkers();
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
};
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
mMap.setMyLocationEnabled(true);
}
}
}
private void nearbyPlaces(final String placeType) {
String url = getUrl(latitude, longitude, placeType);
System.out.println("URL: "+ url);
mService.getNearByPlaces(url)
.enqueue(new Callback<SearchResponse>() {
#Override
public void onResponse(Call<SearchResponse> call, Response<SearchResponse> response) {
if (response.isSuccessful()) {
System.out.println("Sucesso");
for (int i = 0; i < response.body().getResults().length; i++) {
System.out.println("ENTRA NO IF");
MarkerOptions markerOptions = new MarkerOptions();
Result googlePlace = response.body().getResults()[i];
double lat = Double.parseDouble(googlePlace.getGeometry().getLocation().getLat());
double lng = Double.parseDouble(googlePlace.getGeometry().getLocation().getLng());
String placeName = googlePlace.getName();
String vicinity = googlePlace.getVicinity();
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(placeName);
if (placeType.equals("pharmacy")) {
System.out.println("BEM");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
} else {
System.out.println("CONA");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
mMap.addMarker(markerOptions);
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
}
}
}
#Override
public void onFailure(Call<SearchResponse> call, Throwable t) {
}
});
}
private String getUrl(double latitude, double longitude, String placeType) {
StringBuilder builder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
builder.append("location=" + latitude + "," + longitude);
builder.append("&radius=10000");
builder.append("&type=" + placeType);
builder.append("&sensor=true");
builder.append("&key=" + "XXXXXXXXXXXXXXXXXXXXXXXX");
Log.d("getUrl", builder.toString());
return builder.toString();
}
}
Found the problem.
This happened because I asked for permissions in two separate occasions.
First I would ask for SMS permissions in my Main Activity and then, when entering this Activity I would ask for location permissions.
In android development you must ask for all permissions at once.
Im trying to get device current location using FusedLocationProviderClient in a fragment. I want the user to see current device location if they accept permissions.
The problem is in the getDeviceLocation() which checks whether getting location was successful or not.
The logcat does not show me any errors.
Here is the java code:
public class DirectionsFragment extends Fragment implements OnMapReadyCallback {
GoogleMap mMap;
Boolean mLocationPermissionGranted=false;
public String TAG="DirectionsFragment";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_CODE = 1234;
private FusedLocationProviderClient mFusedLocationProviderClient;
static final float DEFAULT_ZOOM = 15f;
private Context mContext=getContext();
OnMapReadyCallback callback=new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getContext(),"Map is Ready",Toast.LENGTH_SHORT).show();
mMap = googleMap;
if (mLocationPermissionGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
}
};
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getLocatonPermission();
}
private void getDeviceLocation() {
Log.d(getTag(), "getDeviceLocation:getting device current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationPermissionGranted=true) {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Log.d(TAG,"onComplete:found Location");
Location currentLocation=(Location)task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),DEFAULT_ZOOM);
}else{
Log.d(TAG,"onComplete:current location is null");
Toast.makeText(mContext, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException sexc){
Log.e(TAG,"getDeviceLocation:SecurityException:"+sexc.getMessage());
}
}
//What happens on map zoom
private void moveCamera(LatLng latLng,float zoom){
Log.d(TAG,"moveCamera:moving the camera to: lat:"+latLng.latitude+","+latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
}
public void initMap(){
SupportMapFragment mapFragment=(SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment!=null){
mapFragment.getMapAsync(callback);
}
}
private void getLocatonPermission() {
String[] permissions={Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
} ;
if (ContextCompat.checkSelfPermission(getContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
}
} else {
ActivityCompat.requestPermissions(getActivity(), permissions, LOCATION_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
mLocationPermissionGranted=false;
switch (requestCode){
case LOCATION_PERMISSION_CODE:{
if (grantResults.length>0){
for (int i=0;i<grantResults.length;++i){
if (grantResults[i]!=PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=false;
return;
}
}
mLocationPermissionGranted=true;
initMap();
}
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
XML code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
i think you missed checking if the location provider is enabled ex:GPS so first you have to check current location provider and if the provider is disabled request the permission of customer to enable it. it is kotlin code but i think you can figure it out
LocationServices.getSettingsClient(this)
.checkLocationSettings(LocationSettingsRequest.Builder()
.addLocationRequest(LocationRequest().apply {
priority =LocationRequest.PRIORITY_HIGH_ACCURACY
}).build())
.addOnSuccessListener {
// GPS is already enable, callback GPS status through listener
getDeviceLocation()
}
.addOnFailureListener { e ->
// ask user GPS permission
val rae = e as ResolvableApiException
rae.startResolutionForResult(this,GPS_REQUEST_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && requestCode == GPS_REQUEST_CODE) {
getDeviceLocation()
}
}
I am using google play service location api (fused location provider) to get user current location. In some cases it takes too much time to return the results and sometimes it takes quite less time to return the reslts for the same device. In both cases user was indoor. I could not understand which is the reason behind this scenario.
public class SelfAttendanceFragment extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
OnMapReadyCallback, GoogleMap.OnMapClickListener {
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final int MY_PERMISSIONS_REQUEST = 1;
private static Double LATITUDE_DHAKA;
private static Double LONGITUDE_DHAKA;
LoadingDialog mLoadingDialog;
double latitude = 0;
double longitude = 0;
Handler mHandler;
CountDownTimer countDownTimer;
FusedLocationProviderClient mFusedLocationClient;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
LocationCallback mLocationCallback;
LocationManager locationManager;
SupportMapFragment mapFragment;
Location location;
private GoogleMap mMap;
private String address;
private String remarks = "";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_self_attendance, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
/*if (!checkPermissionGranted()) {
askForPermission();
}*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED ) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST);
} else {
startAction();
}
} else {
startAction();
}
}
private void startAction(){
mLoadingDialog = new LoadingDialog(getContext(), getString(R.string.fetching_location));
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
doCheckPermissionForGps();
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
List<Location> locationList = locationResult.getLocations();
for (Location loc : locationList) {
if (loc.getLatitude() != 0 && loc.getLongitude() != 0) {
location = loc;
checkLocationandAddToMap();
break;
}
}
}
};
}
private void doCheckPermissionForGps() {
Boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGpsEnabled && mGoogleApiClient != null) {
requestLocationUpdates();
} else if (mGoogleApiClient == null) {
buildGoogleApiClient();
} else if (!isGpsEnabled) {
displayLocationSettingsRequest(getContext());
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10);
mLocationRequest.setFastestInterval(10 / 2);
}
private String getAddressByLattitudeAndLongitude() {
String address;
try {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(getContext(), Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 5); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
if (address.isEmpty()) {
address = addresses.get(0).getLocality();
}
} catch (Exception ex) {
address = "";
}
return address;
}
private void displayLocationSettingsRequest(Context context) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
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();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
#SuppressLint("MissingPermission")
private void requestLocationUpdates() {
if(isAdded() && getActivity() != null){
mLoadingDialog.showDialogWithText("Fetching location using GPS...");
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch (resultCode) {
case -1:
requestLocationUpdates();
break;
case 0:
displayLocationSettingsRequest(getContext());
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
displayLocationSettingsRequest(getContext());
} else {
requestLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
super.onDestroy();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
try{
mMap = googleMap;
mMap.clear();
LATITUDE_DHAKA = 23.777176;
LONGITUDE_DHAKA = 90.399452;
try {
boolean success = mMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
getContext(), R.raw.style_map));
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(LATITUDE_DHAKA, LONGITUDE_DHAKA)).zoom(10) // Sets the zoom
// Sets the orientation of the camera to east
.build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
doCheckPermissionForGps();
return false;
}
});
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 0, 100);
} catch (Exception ex){
}
}
private void checkLocationandAddToMap() {
//MarkerOptions are used to create a new Marker.You can specify location, title etc with MarkerOptions
if (location != null) {
CameraPosition camPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())).zoom(17) // Sets the zoom
// Sets the orientation of the camera to east
.build();
if (mMap != null)
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(camPosition));
}
}
#Override
public void onMapClick(LatLng latLng) {
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
startAction();
} else {
CustomSnackbarError.showMessageFromFragment(getContext(),"Permission is necessary" +
" to enable this feature");
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST);
}
}
/*#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED
*//* && grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[3] == PackageManager.PERMISSION_GRANTED
&& grantResults[4] == PackageManager.PERMISSION_GRANTED
&& grantResults[5] == PackageManager.PERMISSION_GRANTED
&& grantResults[6] == PackageManager.PERMISSION_GRANTED
&& grantResults[7] == PackageManager.PERMISSION_GRANTED*//*
) {
//checkForUpdate();
startAction();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}*/
private boolean checkPermissionGranted() {
/* if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_NETWORK_STATE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}*/
/* if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}*/
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
return true;
}
private void askForPermission() {
ActivityCompat.requestPermissions((Activity) getContext(),
new String[]{
/*Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.INTERNET,
Manifest.permission.CALL_PHONE,
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
},
MY_PERMISSIONS_REQUEST);
}
#Override
public void onDestroyView() {
super.onDestroyView();
dismisLoadingDialog();
}
private void dismisLoadingDialog(){
if(mLoadingDialog != null && mLoadingDialog.isShowing()){
mLoadingDialog.dismiss();
}
}
}
Most of the time GPS provider takes much time to fetch location when the user is within the building. In that case, you must have to fetch location from the network provider for faster results. GPS works very well outside the building but has trouble to fetch location from within. Please allow fetching location from both network & GPS provider for improved result.
The way android has implemented and created this fusedlocationprovider library is it takes two types of location updates:
1 -> Network Based
2 -> GPS
As when user try to fetch the location from indoor or any place where GPS has no much space for getting location from satellite it uses network.
so, when you are working indoor you will see that it is troubling fetching location. But as you said sometimes it takes lesser time and sometimes it takes much time.
The possible scenario is Whenever you request for location it will go and try to find the location if there is already location taken by other application and if there is location you will get it. Otherwise it will try to find the location by its own and next time you search for it as it has already it will give you directly.
And you have used GPS Provider, use Network provider as well.
Let me know if it helps. Thanks
Add the below code for getting the current location faster using fused location - FusedLocationProviderClient :
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val PERMISSION_ID = 1000
private lateinit var mFusedLocationClient: FusedLocationProviderClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getCurrentLocation()
}
private fun getCurrentLocation() {
if (isLocationEnabled()) {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
requestPermissions()
return
}
val tokenSource = CancellationTokenSource()
val token = tokenSource.token
mFusedLocationClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, token)
.addOnCompleteListener(this) { task ->
val location: Location? = task.result
Toast.makeText(
this,
"${location!!.latitude} and ${location.longitude}",
Toast.LENGTH_SHORT
).show()
}
} else {
Toast.makeText(this, "Please turn on location", Toast.LENGTH_LONG).show()
val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}
}
private fun isLocationEnabled(): Boolean {
val locationManager: LocationManager =
getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
LocationManager.NETWORK_PROVIDER
)
}
private fun requestPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
),
PERMISSION_ID
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSION_ID) {
if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
getCurrentLocation()
}
}
}
}
build.gradle
implementation 'com.google.android.gms:play-services-location:20.0.0'
I was trying to make google map application but when i try to build the app it gives me a weird error on some casting sentences please help
the error
the error 1
the androidstudio can not find R Class
This is the map activity where i am loading the map.............................................................................................................................
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Map is Ready");
mMap = googleMap;
if (mLocationPermissionGranted)
{
getDeviceLocation();
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;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private Boolean mLocationPermissionGranted = false;
private static final int LOCATON_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM= 15f;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private EditText mSearchText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mSearchText = (EditText) findViewById(R.id.input_search);
getLocationPermission();
/* MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
mAdView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice("7B0B6DDFA6EB4A71955387A3EA155884").build();
mAdView.loadAd(adRequest);*/
}
private void init()
{
Log.d(TAG,"initializing map");
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
if(actionId== EditorInfo.IME_ACTION_SEARCH || actionId==EditorInfo.IME_ACTION_DONE
||actionId==KeyEvent.ACTION_DOWN || actionId== KeyEvent.KEYCODE_ENTER)
{
geoLocate();
}
return false;
}
});
}
private void geoLocate()
{
Log.d(TAG,"locating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapActivity.this);
List<Address> list = new ArrayList<>();
try
{
list = geocoder.getFromLocationName(searchString,1);
}
catch(IOException e)
{
Log.e(TAG,"IOException"+ e.getMessage());
}
if(list.size()>0)
{
Address address = list.get(0);
Log.d(TAG,"found location" + address.toString());
// Toast.makeText(this,address.toString(),Toast.LENGTH_SHORT).show();
}
}
private void getDeviceLocation()
{
Log.d(TAG,"GetDeviceLocation");
mFusedLocationProviderClient= LocationServices.getFusedLocationProviderClient(this);
try
{
if(mLocationPermissionGranted)
{
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener()
{
#Override
public void onComplete(#NonNull Task task)
{
if(task.isSuccessful())
{
Log.d(TAG,"location found");
Location CurrentLocation = (Location) task.getResult();
moveCamera(new LatLng(CurrentLocation.getLatitude(),CurrentLocation.getLongitude()),DEFAULT_ZOOM);
}
else
{
Log.d(TAG,"location not found");
Toast.makeText(MapActivity.this,"unable to find location",Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e)
{
Log.e(TAG,"security exception"+e.getMessage());
}
}
private void moveCamera(LatLng latlng,float zoom)
{
Log.d(TAG,"move camera to location lat:"+latlng.latitude + ",lng" + latlng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,zoom));
}
private void initMap()
{
Log.d(TAG,"initializing map");
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission()
{
Log.d(TAG,"Getting permission");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)==PackageManager.PERMISSION_GRANTED)
{
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION)==PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = true;
initMap();
}
else
{
ActivityCompat.requestPermissions(this,permissions,LOCATON_PERMISSION_REQUEST_CODE);
}
}
else
{
ActivityCompat.requestPermissions(this,permissions,LOCATON_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
Log.d(TAG,"onRequestPermissionsResult:called");
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mLocationPermissionGranted = false;
switch(requestCode)
{
case LOCATON_PERMISSION_REQUEST_CODE:
{
if(grantResults.length>0 )
{
for(int i = 0 ; i < grantResults.length;i++)
{
if(grantResults[i]!= PackageManager.PERMISSION_GRANTED)
{
mLocationPermissionGranted = false;
Log.d(TAG,"onRequestPermissionsResult:failed");
return;
}
}
Log.d(TAG,"onRequestPermissionsResult:granted");
mLocationPermissionGranted= true;
initMap();
}
}
}
}
}
In Android Studio
Go to Build -> Clean Project Project
It surely will work.If not restart Android Studio
I have implemented location using FusedLocationProviderClient. The problem in my app is that the permission dialog does not switch on the location in settings. I have to manually turn it on before I start getting updates.
I have checked and requested permission using ContextCompat and ActivityCompat classes but nothing happens until I manually press the button. Is this a bug with FusedLocationProviderClient or bad programming on my side? I have worked with location manager and Fused Location Provider APIs and never faced this before.
Here's my code:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
private FusedLocationProviderClient providerClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
private static boolean isLocationGranted = false;
public static final int UPDATE_INTERVAL = 15000;
public static final int FASTEST_INTERVAL = 8000;
public static final int DISPLACEMENT = 10;
public static final int PLAY_SERVICES_REQ_CODE = 9009;
public static final int PLAY_SERVICES_RESOLUTION_REQ_CODE = 9090;
private SupportMapFragment mapFragment;
public HomeFragment() {
// Required empty public constructor
}
private void initViews(View view) {
toolbar = view.findViewById(R.id.toolbar);
driverStatusTV = view.findViewById(R.id.driverStatusTV);
statusSwitch = view.findViewById(R.id.statusSwitch);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
checkPerms();
providerClient = LocationServices.getFusedLocationProviderClient(getActivity());
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
driverStatusTV.setText("OFFLINE");
statusSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean b) {
if (b) {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Online", Snackbar.LENGTH_LONG).show();
if (checkPerms()) {
startLocationListener();
driverStatusTV.setText("ONLINE");
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
mGmap.setIndoorEnabled(false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mGmap.setMyLocationEnabled(false);
stopLocationListener();
driverStatusTV.setText("OFFLINE");
if (currentMarker != null){
currentMarker.remove();
}
}
}
});
return view;
}
private void stopLocationListener() {
if (providerClient != null){
providerClient.removeLocationUpdates(locationCallback);
}
}
#Override
public void onPause() {
super.onPause();
stopLocationListener();
}
private void startLocationListener() {
locationRequest = LocationRequest.create();
locationRequest.setSmallestDisplacement(DISPLACEMENT);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locationRequest);
LocationSettingsRequest settingsRequest = builder.build();
SettingsClient client = LocationServices.getSettingsClient(getActivity());
client.checkLocationSettings(settingsRequest);
displayLocation();
}
private boolean checkPerms() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
isLocationGranted = false;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
} else {
isLocationGranted = true;
Log.d(TAG, "Permission Value:\t" + isLocationGranted);
}
return isLocationGranted;
}
private void reqPerms() {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
reqPerms();
} else {
if (statusSwitch.isChecked()) {
providerClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
mGmap.setIndoorEnabled(true);
mGmap.setMyLocationEnabled(true);
} else {
mGmap.setIndoorEnabled(false);
mGmap.setMyLocationEnabled(false);
}
}
}
private LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
mLastLocation = location;
if (currentMarker != null) {
currentMarker.remove();
}
latitude = mLastLocation.getLatitude();
Log.d(TAG, "Lat:\t" + latitude);
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Long:\t" + longitude);
MarkerOptions options = new MarkerOptions();
options.position(new LatLng(latitude, longitude));
options.title("Driver");
//options.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)); // throws error
currentMarker = mGmap.addMarker(options);
rotateMarker(currentMarker, 360, mGmap);
mGmap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 18.0f));
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isLocationGranted = true;
if (checkPlayServices() && statusSwitch.isChecked()) {
startLocationListener();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), AppConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Play Services NOT Supported on Your Device", Snackbar.LENGTH_LONG).show();
getActivity().finish();
getActivity().moveTaskToBack(true);
}
return false;
}
return true;
}
private void rotateMarker(final Marker currentMarker, final float i, GoogleMap mGmap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = currentMarker.getRotation();
final int duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.postDelayed(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.elapsedRealtime() - start;
float t = interpolator.getInterpolation(elapsed / duration);
float rot = t * i + (1 - t) * startRotation;
currentMarker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
}, duration);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
startLocationListener();
}
}
Alos, the set icon on marker throws this error com.google.maps.api.android.lib6.common.apiexception.b: Failed to decode image. The provided image must be a Bitmap.
Can anyone help me solve these two problems? Thank you
your onRequestPermissionsResult will never be called, you are requesting permissions from your activity and your activity's onRequestPermissionsResult would be getting invoked. If you want permission callback in your fragment just remove Activity when you request permssions
private void reqPerms() {
requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AppConstants.LOC_PERM_CODE);
}
Your fragment has to be a supportFragment if you want to access this method