Getting user current location using fused location provider - android

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'

Related

How do I get current location using FusedLocationProviderClient

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()
}
}

Give java.lang.NullPointerException: when i click on current location button [duplicate]

This question already has answers here:
Error invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
(7 answers)
Closed 3 years ago.
when i click on current button for getting user's current location then give nullpointer exception even i check the fusedapi is granted or not and also when user allow for current location access then i retrive the current location but it show the error
MapFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_map, container, false);
latlng.add(new LatLng(22.32371, 73.16409));
latlng.add(new LatLng(22.32737, 73.17566));
latlng.add(new LatLng(22.28, 73.1903696));
latlng.add(new LatLng(22.334, 73.21853));
latlng.add(new LatLng(22.40303, 73.22369));
latlng.add(new LatLng(22.55148, 72.97035));
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(this);
askPermission();
createGoogleApi();
mbtn = rootview.findViewById(R.id.myLocationButton);
mbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getcurrentmarker();
}
});
return rootview;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mgoogleMap = googleMap;
mgoogleMap.setOnMarkerClickListener(this);
}
#Override
public void onStart() {
super.onStart();
// Call GoogleApiClient connection when starting the Activity
googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
// Disconnect GoogleApiClient when stopping Activity
googleApiClient.disconnect();
}
private void createGoogleApi()
{
Log.d(TAG, "createGoogleApi()");
if ( googleApiClient == null )
{
googleApiClient = new GoogleApiClient.Builder( getContext() )
.addConnectionCallbacks(this)
.addOnConnectionFailedListener( this )
.addApi(LocationServices.API)
.build();
}
}
// Check for permission to access Location
private boolean checkPermission() {
Log.d(TAG, "checkPermission()");
// Ask for permission if it wasn't granted yet
return (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED );
}
// Asks for permission
private void askPermission() {
Log.d(TAG, "askPermission()");
ActivityCompat.requestPermissions(
MapFragment.super.getActivity(),
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
REQ_PERMISSION
);
}
// Verify user's response of the permission requested
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQ_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getContext(), "Permission", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
// App cannot work without the permissions
private void permissionsDenied() {
Log.w(TAG, "permissionsDenied()");
}
// Start location Updates
private void startLocationUpdates(){
Log.i(TAG, "startLocationUpdates()");
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(6000)
.setFastestInterval(5000);
//movement in meter
if ( checkPermission() )
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged ["+location+"]");
lastLocation = location;
writeActualLocation(location);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "onConnected()");
getLastKnownLocation();
}
// GoogleApiClient.ConnectionCallbacks suspended
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "onConnectionSuspended()");
}
// GoogleApiClient.OnConnectionFailedListener fail
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.w(TAG, "onConnectionFailed()");
}
// Get last known location
private void getLastKnownLocation() {
Log.d(TAG, "getLastKnownLocation()");
if ( checkPermission() ) {
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if ( lastLocation != null ) {
Log.i(TAG, "LasKnown location. " +
"Long: " + lastLocation.getLongitude() +
" | Lat: " + lastLocation.getLatitude());
writeLastLocation();
startLocationUpdates();
} else {
Log.w(TAG, "No location retrieved yet");
startLocationUpdates();
}
}
else askPermission();
}
private void writeActualLocation(Location location)
{
lastLocation = location;
showmarker(latlng);
}
private void writeLastLocation() {
writeActualLocation(lastLocation);
}
private void getcurrentmarker()
{
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mgoogleMap.setMyLocationEnabled(true);
mgoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
mgoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 14));
}
private void showmarker(List<LatLng> positions)
{
Log.d(TAG,"show");
if(!markers.equals(null))
{
markers.clear();
}
if ( marker != null ) {
marker.remove();
}
for (LatLng position : positions) {
Marker marker = mgoogleMap.addMarker(
new MarkerOptions()
.position(position)
.visible(false)); // Invisible for now
markers.add(marker);
}
for (Marker marker : markers) {
if (SphericalUtil.computeDistanceBetween(new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude()), marker.getPosition()) < 400) {
marker.setVisible(true);
float zoom = 14f;
CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), zoom);
mgoogleMap.animateCamera(cameraUpdate1);
}
}
}
#Override
public boolean onMarkerClick(Marker marker)
{
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(lastLocation,marker.getPosition());
bottomSheetFragment.show(getFragmentManager(), bottomSheetFragment.getTag());
return false;
}
}
Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
before getting googleapiclient connected i ask the permission for current location then i retrive current location and after i click the current location button
logcat
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.eats.Fragment.MapFragment.getcurrentmarker(MapFragment.java:256)
Check for location is enabled/ disabled state
If location is disabled then result will be null.
I recommend using the FusedLocationProviderClient
Then doing something like this:
if (handleLocationPermission()) {
context?.let {
fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it)
if (ContextCompat.checkSelfPermission(it, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED
) {
fusedLocationProvider.lastLocation
.addOnSuccessListener { location ->
if (location != null) {
writeLastLocation(location.latitude, location.longitude)
}
}
}
}
}
}
```

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 location app only running properly after clean install

I wrote this app for an assignment, but for some reason two of the questions will only run properly once, and only after the app is installed.
e.g. If i install the app and run Question 1a then it will work perfectly. If I try and run Question 2 after that, or run Question 1a again, it won't work unless I uninstall and reinstall the apk. It also works the other way around, so if I run Question 2 first then Question 1a won't work and Question 2 won't work if I try and run it again.
I don't get any errors or crashes, it just doesn't do anything. It's strange though because Question 1b works perfectly all the time and is very similar to both Question 1a and Question 2 except it uses a Google Map.
Edit: I just realized that the map in question 1b doesn't work anymore (Google Maps API authorization failed) but it does update the address properly in the TextView, now if only I could figure out why the TextView updates in Question 1b but not the other two.
Any help would be greatly appreciated!
The code is as follows:
Question 1a:
public class Question1a extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private TextView txtAddress;
private GoogleApiClient client;
private LocationRequest locationRequest;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1a);
txtAddress = (TextView) findViewById(R.id.addressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Gets address and displays it in a TextView
#Override
public void onLocationChanged(Location location)
{
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
//Checks if the app has the required permissions to run (Location permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case REQUEST_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
}
Question 1b:
public class Question1b extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener
{
private TextView txtAddress;
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentLocationMarker;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1b);
txtAddress = (TextView) findViewById(R.id.locationAddressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case REQUEST_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
//if the app has the right permissions then it will build the API client and enable location services when the map is ready
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Moves the marker when location changes
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
if (currentLocationMarker != null)
{
currentLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
currentLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//Checks if the app has the required permissions to run (Location permissions & SMS permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
}
Question 2:
public class Question2 extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private TextView txtAddress;
private GoogleApiClient client;
private LocationRequest locationRequest;
public static final int REQUEST_MULTIPLE_PERMISSIONS_CODE = 99;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
txtAddress = (TextView) findViewById(R.id.addressEdit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkPermissions();
}
}
//creates a location request object and sets the location request intervals
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i)
{
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
//Gets address using geocoder and displays it in a TextView
#Override
public void onLocationChanged(Location location)
{
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if(addresses == null)
{
Toast.makeText(this, "No address found", Toast.LENGTH_SHORT).show();
}
else
{
Address address = addresses.get(0);
String finalAddress = "Address: ";
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
{
finalAddress = finalAddress + address.getAddressLine(i);
}
txtAddress.setText(finalAddress);
}
}
//build the API client
protected synchronized void buildGoogleApiClient()
{
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
//Checks if the app has the required permissions to run (Location permissions & SMS permissions)
public boolean checkPermissions()
{
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS}, REQUEST_MULTIPLE_PERMISSIONS_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case REQUEST_MULTIPLE_PERMISSIONS_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//permission has been granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
{
//if client is null(there is no Google API Client) this calls the method to build the Google API Client
if (client == null)
{
buildGoogleApiClient();
}
}
}
else
{
Toast.makeText(this, "Permissions were denied", Toast.LENGTH_SHORT).show();
}
}
}
public void sendMyLocation(View v)
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("+27718831284", null, "Your location is: " + txtAddress.getText(), null, null);
}
}

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