Location Permission Not Switching on With Device - android

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

Related

Change the position of the marker when the camera is moving in google maps

I have added google maps SDK to my project and have added a marker at the current position. If the user moves the camera the marker also changes its position by setting marker.setPosition(lat, long); in onCameraMove() callback,
But I am getting a flicker when the marker changes its position. I want to make it smooth as in Ola app.
Attaching the code for reference
public class StoreAddressActivity extends BaseActivity<FragmentStoreAddressBinding, WebsiteCreationViewModel> implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener, OnMapReadyCallback, ActivityCompat.OnRequestPermissionsResultCallback,
GoogleMap.OnMarkerClickListener, OnCameraMoveListener, GoogleMap.OnCameraIdleListener, Navigator.StoreAddressNavigator {
private static final String TAG = StoreAddressActivity.class.getSimpleName();
#Inject
ViewModelProviderFactory factory;
private WebsiteCreationViewModel websiteCreationViewModel;
private FragmentStoreAddressBinding fragmentStoreAddressBinding;
private FusedLocationProviderClient mFusedLocationClient;
private Location mLastLocation;
private UiSettings mUiSettings;
private Marker currentLocationMarker;
private static final int DEFAULT_ZOOM = 15;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean locationPermissionGranted = false;
private GoogleMap map;
private StringBuilder mResult;
private int previousLength;
private boolean backSpace;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentStoreAddressBinding = getViewDataBinding();
fragmentStoreAddressBinding.setNavigator(this);
init();
}
private void init() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
String apiKey = getString(R.string.google_maps_key);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), apiKey);
}
PlacesClient placesClient = Places.createClient(this);
fragmentStoreAddressBinding.mapLocationEdittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
previousLength = s.length();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
backSpace = previousLength > s.length();
if (!backSpace) {
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363), //dummy lat/lng
new LatLng(-33.858754, 151.229596));
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
//.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setCountry("IN")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(s.toString())
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener(response -> {
mResult = new StringBuilder();
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
mResult.append(" ").append(prediction.getFullText(null) + "\n");
Log.d(TAG, prediction.getPlaceId());
Log.d(TAG, prediction.getPrimaryText(null).toString());
}
Log.d(TAG, mResult.toString());
// mSearchResult.setText(String.valueOf(mResult));
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
});
}
}
});
}
#Override
public WebsiteCreationViewModel getViewModel() {
websiteCreationViewModel = new ViewModelProvider(this, factory).get(WebsiteCreationViewModel.class);
return websiteCreationViewModel;
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_store_address;
}
#Override
public boolean onMyLocationButtonClick() {
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
mUiSettings = map.getUiSettings();
mUiSettings.setZoomControlsEnabled(true);
mUiSettings.setMyLocationButtonEnabled(false);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setOnMarkerClickListener(this);
map.setOnCameraMoveListener(this);
map.setOnCameraIdleListener(this);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true;
map.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
locationPermissionGranted = true;
map.setMyLocationEnabled(true);
}
getDeviceLocation();
}
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(StoreAddressActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true;
if (map != null) {
map.setMyLocationEnabled(true);
}
} else {
// Permission to access the location is missing. Show rationale and request permission
requestPermissionsSafely(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
locationPermissionGranted = true;
enableMyLocation();
} else {
locationPermissionGranted = false;
}
}
#Override
public void onPause() {
super.onPause();
}
/**
* Demonstrates converting a {#link Drawable} to a {#link BitmapDescriptor},
* for use as a marker icon.
*/
private BitmapDescriptor vectorToBitmap(#DrawableRes int id) {
Drawable vectorDrawable = ResourcesCompat.getDrawable(getResources(), id, null);
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (locationPermissionGranted) {
Task<Location> locationResult = mFusedLocationClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
mLastLocation = task.getResult();
if (mLastLocation != null) {
LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(),
getApplicationContext(), new GeocoderHandler());
// currentLocationMarker = map.addMarker(new MarkerOptions()
// .position(latLng)
// .icon(vectorToBitmap(R.drawable.ic_location_marker))
// .title("MOVE PIN TO ADJUST")
// .draggable(false));
MarkerOptions markerOpt = new MarkerOptions();
markerOpt.position(latLng)
.title("MOVE PIN TO ADJUST").icon(vectorToBitmap(R.drawable.ic_location_marker));
//Set Custom InfoWindow Adapter
CustomInfoWindowAdapter adapter = new CustomInfoWindowAdapter(StoreAddressActivity.this);
map.setInfoWindowAdapter(adapter);
currentLocationMarker = map.addMarker(markerOpt);
currentLocationMarker.showInfoWindow();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
latLng, DEFAULT_ZOOM));
}
}
}
});
}
} catch (SecurityException e) {
}
}
#Override
public boolean onMarkerClick(Marker marker) {
return false;
}
#Override
public void onCameraMove() {
LatLng target = map.getCameraPosition().target;
//currentLocationMarker.setPosition(target);
animateMarker(currentLocationMarker, target, false);
// CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(target, DEFAULT_ZOOM);
// map.animateCamera(cameraUpdate, 4000, null);
}
#Override
public void onCameraIdle() {
Log.d(TAG, "Camera is idle");
LatLng target = map.getCameraPosition().target;
if (currentLocationMarker != null)
currentLocationMarker.setPosition(target);
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(target.latitude, target.longitude,
getApplicationContext(), new GeocoderHandler());
fragmentStoreAddressBinding.currentLocationTextview.setText(getString(R.string.go_to_current_location));
}
#Override
public void currentLocationClick() {
if (mLastLocation != null) {
fragmentStoreAddressBinding.currentLocationTextview.setText(getString(R.string.this_is_current_location));
LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM);
map.moveCamera(cameraUpdate);
map.animateCamera(cameraUpdate, 4000, null);
LocationAddress locationAddress = new LocationAddress();
locationAddress.getAddressFromLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude(),
getApplicationContext(), new GeocoderHandler());
}
}
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("address");
break;
default:
locationAddress = null;
}
fragmentStoreAddressBinding.mapLocationEdittext.setText(locationAddress);
}
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
if(currentLocationMarker == null)
return;
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = map.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 250;
final LinearInterpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
// double lng = t * toPosition.longitude + (1 - t)
// * startLatLng.longitude;
// double lat = t * toPosition.latitude + (1 - t)
// * startLatLng.latitude;
marker.setPosition(new LatLng(toPosition.latitude, toPosition.longitude));
// if (t < 1.0) {
// // Post again 16ms later.
// handler.postDelayed(this, 16);
// } else {
// if (hideMarker) {
// marker.setVisible(false);
// } else {
// marker.setVisible(true);
// }
// }
}
});
}

How do i call non activity class in MainActivity class?

I have Fused Location Api class which extends AppCompatActivity right now. I want to make it non-activity class and call it in MainActivity or in any other activity class. How can i do that? I am a newbie . So please any constructive criticism would be really appreciated.
public class GpsLocation extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private Location location;
private TextView locationTv;
private GoogleApiClient googleApiClient;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private LocationRequest locationRequest;
private static final long UPDATE_INTERVAL = 5000, FASTEST_INTERVAL = 5000; // = 5 seconds
// lists for permissions
private ArrayList<String> permissionsToRequest;
private ArrayList<String> permissionsRejected = new ArrayList<>();
private ArrayList<String> permissions = new ArrayList<>();
// integer for permissions results request
private static final int ALL_PERMISSIONS_RESULT = 1011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_hotkey_navigation);
locationTv = findViewById(R.id.location);
// we add permissions we need to request location of the users
permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
permissionsToRequest = permissionsToRequest(permissions);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (permissionsToRequest.size() > 0) {
requestPermissions(permissionsToRequest.toArray(
new String[0]), ALL_PERMISSIONS_RESULT);
}
}
// we build google api client
googleApiClient = new GoogleApiClient.Builder(this).
addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this).build();
}
private ArrayList<String> permissionsToRequest(ArrayList<String> wantedPermissions) {
ArrayList<String> result = new ArrayList<>();
for (String perm : wantedPermissions) {
if (!hasPermission(perm)) {
result.add(perm);
}
}
return result;
}
private boolean hasPermission(String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (googleApiClient != null) {
googleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
if (!checkPlayServices()) {
locationTv.setText("You need to install Google Play Services to use the App properly");
}
}
#Override
protected void onPause() {
super.onPause();
// stop location updates
if (googleApiClient != null && googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
googleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST);
} else {
finish();
}
return false;
}
return true;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
// Permissions ok, we get last location
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
}
startLocationUpdates();
}
private void startLocationUpdates() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "You need to enable permissions to display location !", Toast.LENGTH_SHORT).show();
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locationTv.setText("Latitude : " + location.getLatitude() + "\nLongitude : " + location.getLongitude());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case ALL_PERMISSIONS_RESULT:
for (String perm : permissionsToRequest) {
if (!hasPermission(perm)) {
permissionsRejected.add(perm);
}
}
if (permissionsRejected.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissionsRejected.get(0))) {
new AlertDialog.Builder(GpsLocation.this).
setMessage("These permissions are mandatory to get your location. You need to allow them.").
setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
requestPermissions(permissionsRejected.
toArray(new String[0]), ALL_PERMISSIONS_RESULT);
}
}).setNegativeButton("Cancel", null).create().show();
return;
}
}
} else {
if (googleApiClient != null) {
googleApiClient.connect();
}
}
break;
}
}
}
I need to get its gps coordinates and send it to MainActivity class.So please help me. Any help would be much really appreciated.
why are you extending AppCompat at all if you want a regular class? Create a normal class and instantiate it in your activity.
What exactly are you trying to do in this class, that it cant be a method in your Activity?
The fused Location Client can me created anywhere by calling
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

Android app crash after sign in and logcat screen shows error?

I am making an app like uber and i have to put driver location with marker on app and
after sign in it shows loading and then crashes?
i have imported all libraries properly but my logcat screen
i have tried going to similar questions on stackOverflow but nothing seems working and this bug just shows again and again and i am not unable to start my app .
Welcome Activity
{
private GoogleMap mMap;
//Play Services
private static final int MY_PERMISSION_REQUEST_CODE=7000;
private static final int PLAY_SERVICE_RES_REQUEST= 7001;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FATEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference drivers;
GeoFire geoFire;
Marker mCurrent;
MaterialAnimatedSwitch location_switch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Init View
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline)
{
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are Online",Snackbar.LENGTH_SHORT)
.show();
}
else
{
stopLocationUpdates();
mCurrent.remove();
Snackbar.make(mapFragment.getView(),"You are Offline",Snackbar.LENGTH_SHORT)
.show();
}
}
});
//Geo Fire
drivers = FirebaseDatabase.getInstance().getReference("Drivers");
geoFire = new GeoFire(drivers);
setUpLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
}
private void setUpLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
//Request runtime Permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
if(location_switch.isChecked())
displayLocation();
}
}
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode != ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show();
else {
Toast.makeText(this, "This Device is not Supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
if (location_switch.isChecked())
{
final double latitude = mLastLocation.getLatitude();
final double longitude = mLastLocation.getLongitude();
//Update to Firebase
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
//Add Marker
if (mCurrent != null)
mCurrent.remove(); //Remove already Marker
mCurrent = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.lender))
.position(new LatLng(latitude,latitude))
.title("You"));
//Move the camera to this position
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f));
//Draw Animation Rotate Marker
rotateMarker(mCurrent,-360,mMap);
}
});
}
}
else
{
Log.d("ERROR","Cannot Get Your Location");
}
}
private void rotateMarker(final Marker mCurrent, final float i, GoogleMap mMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = mCurrent.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start ;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
mCurrent.setRotation(-rot > 180?rot/2:rot);
if(t<1.0)
{
handler.postDelayed(this,16);
}
}
});
}
private void startLocationUpdates() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

Show User Location on Map Failed with API Client Connection Error

I want to show the user's location on a map whenever a toggle button is pressed. I have written the code like below and it works only to show the map but not the user's location and sometimes throws error like:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
on this line: LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
I am able to get the location in logcat but can't show on map. Here's the fragment code:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
public static GoogleApiClient apiClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
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);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
setUpLocation();
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();
startLocationListener();
displayLocation();
driverStatusTV.setText("ONLINE");
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
stopLocationListener();
driverStatusTV.setText("OFFLINE");
//currentMarker.remove();
}
}
});
return view;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
for (int gr : grantResults) {
if (gr == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
makeLocationRequest();
initAPIClient();
if (statusSwitch.isChecked()) {
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
} else {
getActivity().finish();
getActivity().moveTaskToBack(true);
}
}
break;
}
}
public void startLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
initAPIClient();
apiClient.connect();
LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
}
}
public void setUpLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
if (checkPlayServices()) {
if (statusSwitch.isChecked()) {
initAPIClient();
makeLocationRequest();
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
}
private void makeLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
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 initAPIClient() {
apiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
apiClient.connect();
}
public void stopLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, this);
}
}
public void displayLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
if (mLastLocation != null) {
if (statusSwitch.isChecked()) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Locn:\t" + "lat:\t" + latitude + "and long:\t" + longitude);
geoFire.setLocation("saj9oPN15VZODBbB87JXU26Rqa53", new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (currentMarker != null) {
currentMarker.remove();
currentMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.car));
currentMarker = mGmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17f);
mGmap.animateCamera(cameraUpdate);
//draw rotate marker animation
//rotateMarker(currentMarker, -360, mGmap);
}
}
});
}
}
}
}
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 onConnected(#Nullable Bundle bundle) {
startLocationListener();
displayLocation();
}
#Override
public void onConnectionSuspended(int i) {
apiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (apiClient != null) {
apiClient = null;
initAPIClient();
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
}
}
Can anyone help me understand why it's not working.

Dont shown 'Add Permission Check' while implementing SetMyLocationEnabled

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" />

Categories

Resources