Can not get my current location - android

I have tried to display the Longitude and Latitude of my current location but I could not.
package com.example.laptop.findlonglat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_LOCATION = 1;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
getLocation();
}
void getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latti = location.getLatitude();
double longi = location.getLongitude();
((EditText) findViewById(R.id.etLocationLat)).setText("Latitude: " + latti);
((EditText) findViewById(R.id.etLocationLong)).setText("Longitude: " + longi);
} else {
((EditText) findViewById(R.id.etLocationLat)).setText("Unable to find correct location.");
((EditText) findViewById(R.id.etLocationLong)).setText("Unable to find correct location. ");
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION:
getLocation();
break;
}
}
}
In this example I am trying to display the longitude and latitude of my current location in the textfields but when I am running this code I got the output says that "Unable to find correct location".
I have added this to the Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
Is there any solution to fix this issue

Easiest way to get the user last location is using FusedLocation provider. below i have added code snippet about how to use it:
private FusedLocationProviderClient mFusedLocationClient;
// ..
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
then whenever you need your current location :
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});

#Override
public void onMyLocationChange(final Location location)
{
double lat = location.getlat();
double long = location.getlong();
}

Related

When WIFI is disabled, user should open wifi again. But I want to detect whole time if is on or off. How can I make this happen?

I want to detect when wifi is disabled all the time. When the user disables the wifi, I want to call openWifiWindow() method in order to prompt user to enable it again. After going back, gps should find the location again. How can I achieve this in my code?
This is my code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
public Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
getLocationPermission();
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionsGranted) {
getDeviceLocation();
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
} else {
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
}
}
}
updateLocationUI();
}
public void openWifiWindow() {
Intent intent = new Intent(this, EnableWifiWindow.class);
startActivity(intent);
}
}
You have two possible solutions, either you can use broadcast receiver to know when wifi turned on/of.
or
you can just check wifi periodically like this. This code goes inside your current activity.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (!CheckWifi()) {
timer.cancel();
/open wifi dialog
}
}
}, 0, 5000);

I cant get my location immediately after having given the permissions in google maps activity.What am i doing wrong?

After asking the user for location permissions and accepts, it doesn't find the location, I have to go back and again inside the app in order to show my location. How can I achieve after giving location permissions to get my location instantly?
This is my code
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Gets the device's current location
getLocationPermission();
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// openGpsWindow();
//}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
}else{
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
//initializing map
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission() {
//getting location permissions
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//onRequestPermissionsResult: called
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
//onRequestPermissionsResult: permission failed
return;
}
}
//onRequestPermissionsResult: permission granted
mLocationPermissionsGranted = true;
//initialize the map
initMap();
}
}
}
}
public void openGpsWindow() {
Intent intent = new Intent(this, EnableGpsWindow.class);
startActivity(intent);
}
}
2)And then If I disable gps while I am in mapsactivity i want to call openGpsWindow(which prompts user to go open the gps again.) Thanks in advance.
You can create a method that updates the UI with the location after the permission has been granted. For example:
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
and then call that method after your initMap() method after the permission has been granted.
If that does not work, you can look here https://github.com/PabiMoloi/Location/blob/master/app/src/main/java/com/example/pmoloi/location/presentation/map/MapsActivity.java , it is a project i created that uses maps.

When GPS is disabled, user should open gps again. How can i achieve this?

I want to detect when gps is disabled. When the user disables the gps, I want to call openGpsWindow() in order to prompt user to enable it again. After going back, gps should find the location again. How can i achieve this in my code? Thanks in advance!
My code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 16f;
public Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
getLocationPermission();
//LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// openGpsWindow();
//}
}
private void updateLocationUI() {
if (mMap == null) {
return;
}
try {
if (mLocationPermissionsGranted) {
getDeviceLocation();
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
getLocationPermission();
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
//map is ready
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
//mMap.setMyLocationEnabled(true);
}
}
private void getDeviceLocation() {
// getting the device's current location
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
if (mLocationPermissionsGranted) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
//onComplete: found location
Location currentLocation = (Location) task.getResult();
double latitude = currentLocation.getLatitude();
double longitude = currentLocation.getLongitude();
//Finding user's location
LatLng myCoordinates = new LatLng(latitude, longitude);
moveCamera(myCoordinates, DEFAULT_ZOOM);
//Adding an icon marker to display the user's location and the info window from above
MarkerOptions marker = new MarkerOptions();
mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();
} else {
//unable to get current location
}
}
});
}
}
private void moveCamera(LatLng latLng, float zoom) {
//moveCamera: moving the camera to: lat: + latLng.latitude + lng: + latLng.longitude
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void getLocationPermission() {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
}
}
}
updateLocationUI();
}
public void openGpsWindow() {
Intent intent = new Intent(this, EnableGpsWindow.class);
startActivity(intent);
}
}
I want to detect when gps is disabled. When the user disables the gps, I want to call openGpsWindow() in order to prompt user to enable it again. After going back, gps should find the location again. How can i achieve this in my code?
Thanks in advance!
You have to implement your MapsActvity with LocationListener along with OnMapReadyCallback. There You will find two override methods of Location Listener.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,LocationListener
Then Just Press Alt+Enter , These Override methods will be automatically added.
#Override
public void onProviderDisabled(String provider) {
Log.e("Location Tag", "Provider Disabled");
openGpsWindow();
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Location Tag", "Provider Enabled");
}

my Lat Long always display 0.0

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private final FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLattitude;
private double currentLongitude;
Button button;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
button = (Button) findViewById(R.id.btn_start);
textView = (TextView) findViewById(R.id.txt_route);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(String.valueOf(currentLattitude + currentLongitude));
}
});
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
#Override
public void onConnected(Bundle arg0) {
final LocationRequest locationRequest = LocationRequest.create();
locationRequest
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
locationRequest, this);
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
//
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
fusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient,
locationRequest, this);
// currentLattitude = location.getLatitude();
// currentLongitude = location.getLongitude();
Log.e("Lat" , "" +currentLattitude);
Log.e("Long" , "" +currentLongitude);
} else {
currentLattitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.e("Lat" , "" +currentLattitude);
Log.e("Long" , "" +currentLongitude);
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// the location is no more than 10 min old, and with reasonable
// accurarcy (50m), done
if (System.currentTimeMillis() < location.getTime() + 10 * 60 * 1000
&& location.getAccuracy() < 50) {
mGoogleApiClient.disconnect();
mGoogleApiClient = null;
}
}
}
In my app i get the lat long of user without enabling the GPSLocation of Mobile . I tried with this code a lot but this code always throws the LAT LONG 0.0 . Please help me with this issue . Tell me what will be the issue with this code.?
So basically ,
Manifest.permission.ACCESS_FINE_LOCATION - this will work with GPS
Manifest.permission.ACCESS_COARSE_LOCATION - this will work with Network
So change your && with || will work for you , currently you are asking that both should be Permitted.
if (ActivityCompat.checkSelfPermission(this, `Manifest.permission.ACCESS_FINE_LOCATION`) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
You should get coordinates in the 'onLocationChanged' callback, by getting latitude and longitude from the Location object passed in the function.
Also check if your manifest has this:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Add this code in "OnCreate":
// CHECK LOCATION SERVICES IS ON
LocationManagerControl locationManagerControl = new LocationManagerControl(this);
try {
if (locationManagerControl.isLocationServiceAvailable()) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
// #Override
public void onLocationChanged(Location location) {
user_lat = location.getLatitude();
user_lng = location.getLongitude();
}
};
} else {
locationManagerControl.createLocationServiceError(MainActivity.this);
}
}catch (Exception e){
e.printStackTrace();
}
And you want to call it wherever you want:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
And don't forget to add:
LocationManager locationManager;
LocationListener locationListener;
And add the following permissions to your application in your AndroidManifest.xml file
INTERNET
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
I hope this helps..

LocationManager returns null

I'm using GPS to get my location in an android app. But when I create a LocationManager it returns null pointer exception. Even though the permissions are set on the androidMainFest.xml and also for the app, still it returns the following exception. Can anyone help in advance. Thank You!
Code :
package com.example.pavsaranga.scat;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Map extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
double longitude, latitude;
String bestProvider;
LocationManager lm;
Location location;
Criteria criteria;
LocationListener locList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomGesturesEnabled(true);
try {
boolean permissionGranted = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (permissionGranted) {
setMyLocation();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 200);
}
} catch(Exception e){
e.printStackTrace();
}
}
private void setMyLocation() {
try {
lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Map.this, "Please Grant Permission.", Toast.LENGTH_SHORT).show();
} else {
criteria = new Criteria();
bestProvider = String.valueOf(lm.getBestProvider(criteria, true)).toString();
location = lm.getLastKnownLocation(bestProvider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else{
lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
}
LatLng myLocation = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
}
} catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 200: {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(Map.this, "Thank You, Permission Granted!.", Toast.LENGTH_SHORT).show();
setMyLocation();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
Exception :
java.lang.IllegalArgumentException: invalid listener: null
MainFest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
LocationManager isn't returning null. The error is that you are passing a null LocationListener.
You need to initialize loclist before passing it to requestLocationUpdates
You are declaring locList and passing it in to the lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList); method. It doesn't look like you are initializing it though.
That is what the exception it telling you, you are passing in null where it is expecting a listener.
You can remove the locList declaration and try making the following change:
change
lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
to
lm.requestLocationUpdates(bestProvider, 2000, 0, new LocationListener(){
// #Override
public void onStatusChanged(String provider, int status, Bundle extras) {
/*
* Called when the provider status changes.
* This method is called when a provider is unable to fetch a location
* or if the provider has recently become available after a period of unavailability.
*/
}
// #Override
public void onLocationChanged(Location location) {
/*
* Called when the location has changed.
*/
}
});

Categories

Resources