How to get current location in android with LocationManager - android

Whenever I use LocationManager and LocationListener,
while using the AndroidEmulator, I get the location,
using the extra tools when I set the latitude and longitude
I checked out other question-answers but i am new to Android Development so i really could not understand the answer. so i raised a new question, i would appreciate the review of my code. Thanks.
but when I run on a physical device my code does not give me my current location on start. How do I get the current location? I also tried getLastKnownLocation but even that does not work.
package com.londonappbrewery.climapm;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
public class WeatherController extends AppCompatActivity {
// Constants:
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
// App ID to use OpenWeather data
final String APP_ID = "5563c6a4ddd7d7181b257988cc2b1ad1";
// Time between location updates (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
// Distance between location updates (1000m or 1km)
final float MIN_DISTANCE = 1000;
//Request Code
final int REQUEST_CODE = 123;
// TODO: Set LOCATION_PROVIDER here:
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
// Member Variables:
TextView mCityLabel;
ImageView mWeatherImage;
TextView mTemperatureLabel;
// TODO: Declare a LocationManager and a LocationListener here:
LocationManager mLocationManager;
LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_controller_layout);
// Linking the elements in the layout to Java code
mCityLabel = (TextView) findViewById(R.id.locationTV);
mWeatherImage = (ImageView) findViewById(R.id.weatherSymbolIV);
mTemperatureLabel = (TextView) findViewById(R.id.tempTV);
ImageButton changeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
// TODO: Add an OnClickListener to the changeCityButton here:
changeCityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(WeatherController.this, ChangeCityController.class);
startActivity(intent);
}
});
}
// TODO: Add onResume() here:
#Override
protected void onResume() {
super.onResume();
Log.d("Clima", "onResume() called");
Intent intent = getIntent();
String cityName = intent.getStringExtra("cityName");
if (cityName != null) {
//Log.d("Clima", cityName);
getWeatherForNewCity(cityName);
} else {
Log.d("Clima", "Getting weather for current location");
getWeatherForCurrentLocation();
}
}
// TODO: Add getWeatherForNewCity(String city) here:
private void getWeatherForNewCity(String city) {
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
// TODO: Add getWeatherForCurrentLocation() here:
private void getWeatherForCurrentLocation() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Log.d("Clima", "");
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
Log.d("Clima", "onLocationChanged() callback received");
Log.d("Clima", "Latitude is " + latitude);
Log.d("Clima", "Longitude is " + longitude);
RequestParams params = new RequestParams();
params.put("lat", latitude);
params.put("lon", longitude);
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Clima", "onProviderDisabled() callback received");
}
};
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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
if(location != null) {
RequestParams params = new RequestParams();
params.put("lat", location.getLatitude());
params.put("lon", location.getLongitude());
params.put("appid", APP_ID);
letsDoSomeNetworking(params);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("Clima", "onRequestPermissionResult(): Permission Granted!");
//mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
getWeatherForCurrentLocation();
}
}
}
// TODO: Add letsDoSomeNetworking(RequestParams params) here:
private void letsDoSomeNetworking(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] header, JSONObject response) {
Log.d("Clima", "Success! JSON : " + response.toString());
WeatherDataModel weatherData = WeatherDataModel.fromJSON(response);
// Log.d("Clima", weatherData.getTemperature()); << WORKING
updateUI(weatherData);
}
#Override
public void onFailure(int statusCode, Header[] header, Throwable e, JSONObject response) {
Log.e("Clima", e.toString());
Log.d("Clima", String.valueOf(statusCode));
Toast.makeText(WeatherController.this, "Request Failed!", Toast.LENGTH_SHORT).show();
}
});
}
// TODO: Add updateUI() here:
private void updateUI(WeatherDataModel weatherData){
mTemperatureLabel.setText(weatherData.getTemperature());
mCityLabel.setText(weatherData.getCity());
int resourceID = getResources().getIdentifier(weatherData.getIconName(), "drawable", getPackageName());
mWeatherImage.setImageResource(resourceID);
}
// TODO: Add onPause() here:
}
What should I do to get the location as soon as the app starts?
P.S. permissions are in place so it isn't an issue of permissions.

LocationManager locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
boolean networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location location;
if(networkEnabled){
longitude=location.getLongitude();
latitude=location.getLatitude();
}
}
Add these permissions in your manifest file:-
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Related

com.google.android.gms.location.LocationListener not working in my activity

I would like to retrieve the device position each time the user moves but the onLocationChanged callback does not work. could someone please help me? here is my code of my activity that manages the google map. Please note, I'm using the onLocationChanged from the Google Library com.google.android.gms.location.LocationListener
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.annotation.TargetApi;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.LocationCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.proper_international.properinternationnal.R;
import com.proper_international.properinternationnal.activity.customer.BookingProviderActivity;
import com.proper_international.properinternationnal.activity.menus.HamburgerMenuProviderActivity;
import com.proper_international.properinternationnal.entities.Nettoyeur;
import com.proper_international.properinternationnal.miscs.UserEnum;
import com.proper_international.properinternationnal.miscs.Utilities;
import com.proper_international.properinternationnal.services.ActionAPIService;
import com.proper_international.properinternationnal.services.FCMNotificationService;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class ProviderToCustomerMapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private Button btnAccept, btnDecline;
FusedLocationProviderClient mFusedLocationClient;
SharedPreferences sharedpreferences;
String latLong, idReserve, from, login;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
LocationRequest mLocationRequest;
Marker mCurrLocationMarker;
private LatLng equipierPosition;
private LocationManager locationManager;
static int MY_REQUEST_CODE = 225;
private String provider_info;
boolean isGPSEnabled, isNetworkEnabled;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_provider_to_customer_maps);
btnAccept = (Button) findViewById(R.id.btnAccept);
btnDecline = (Button) findViewById(R.id.btnDecline);
sharedpreferences = getSharedPreferences(Utilities.MY_PREFERENCE, Context.MODE_PRIVATE);
if (getIntent() != null) {
latLong = getIntent().getStringExtra("latLng");
idReserve = getIntent().getStringExtra("idReserve");
from = getIntent().getStringExtra("from");
login = getIntent().getStringExtra("login");
}
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
runOnClick();
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Provider.toString())) {
btnDecline.setVisibility(View.INVISIBLE);
btnAccept.setText("Consulter son profile.");
}
btnDecline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String result = new declinerReservation().execute().get();
if (result.equals("true"))
Toast.makeText(ProviderToCustomerMapsActivity.this, "Merci!", Toast.LENGTH_LONG).show();
finish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
try {
String result = new assignerReservation().execute().get();
if (result.equals("true")) {
String latLng = mLastLocation.getLatitude() + "," + mLastLocation.getLongitude();
String title = "Reservation A.";
String body = "Un Eest prêt à vous R.";
//Notification PUSH
boolean notSend = false;
while (notSend == false) {
notSend = new FCMNotificationService().execute(from, title, body, latLng, idReserve, sharedpreferences.getString(Utilities.EXTRA_LOGIN, "")).get();
}
startActivity(new Intent(ProviderToCustomerMapsActivity.this, HamburgerMenuProviderActivity.class));
finish();
} else {
Toast.makeText(ProviderToCustomerMapsActivity.this, "Dommage! Un autre Ea décroché cette O.", Toast.LENGTH_LONG).show();
finish();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent intent = new Intent(ProviderToCustomerMapsActivity.this, BookingProviderActivity.class);
String[] chaine = idReserve.split(",");
intent.putExtra("idReserver", chaine[0]);
intent.putExtra("login", chaine[1]);
startActivity(intent);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
public void runOnClick() {
// mGoogleApiClient = this;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Last known location. In some rare situations, it can be null.
if (location != null) {
// Logique pour gérer l'objet d'emplacement
mLastLocation = location;
}
}
});
mFusedLocationClient.getLastLocation().addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception ex) {
Log.e("getLastLocation", "onFailure: "+ex.getMessage());
}
}
);
}
private boolean isGooglePlayServicesAvailable() {
int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GoogleApiAvailability.getInstance().getErrorDialog(this, status, 0).show();
return false;
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
if (sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
btnAccept.setText("Ma liste de R");
btnAccept.setVisibility(View.INVISIBLE);
//String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".", "_"), new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'e."));
geoFire.getLocation(userId.replaceAll(".", "_"), new LocationCallback() {
#Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'équipier."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire", key));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur produite", "Une erreur s'est produite lors de l'obtention de l'emplacement GeoFire: " + databaseError);
}
});
} else {
String userIds = login;
DatabaseReference refs = FirebaseDatabase.getInstance().getReference("ClientDisponible");
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
GeoFire geoFire = new GeoFire(refs);
geoFire.setLocation(userIds.replaceAll(".", "_"), new GeoLocation(latitude, longitude));
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 0."));
geoFire.getLocation(userIds.replaceAll(".", "_"), new LocationCallback() {
#Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 1."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire:" + key));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur obtention", databaseError.getMessage());
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
} else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
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;
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
com.google.android.gms.location.LocationCallback mLocationCallback = new com.google.android.gms.location.LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Position actuelle");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
};
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onResume() {
super.onResume();
runOnClick();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".","_"), new GeoLocation(location.getLatitude(), location.getLongitude()));
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
String userId = login.replaceAll(".","_");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString()))
ref = FirebaseDatabase.getInstance().getReference("ClientDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.removeLocation(userId);
}
}
}
I was able to solve my problem by adding this line of code in the onConnected method:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
I had not used LocationServices because FusedLocationApi is deprecated.

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..

GoogleApiClient is not working in marshmallow and above devices?

Am using googleapi client for getting user location it is working fine below marshmallow devices but on marshmallow devices application getting crashed don't know the reason can someone help me out let me post my code this is the activity am trying to get location:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
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.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.gcm.GcmNetworkManager;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.text.DateFormat;
import java.util.Date;
import static precisioninfomatics.backgroundgps.MyLocationService.TASK_GET_LOCATION_PERIODIC;
public class GPS extends Activity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, GetMethod {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "LocationActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
Button btnFusedLocation;
TextView tvLocation;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
private AsyncTaskGet asyncTaskGet;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate ...............................");
if (!checkPlayServices()) {
finish();
}
createLocationRequest();
startService(new Intent(this, GPSService.class));
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_gps);
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mCurrentLocation != null) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
String userID = "1";
String time = String.valueOf(System.currentTimeMillis());
String url = "http://172.16.6.106:8080/gpstracker/api/coordinates/" + lat + "/" + lng + "/" + userID + "/" + time;
Log.d("url", url);
GetNoteList(getApplicationContext());
asyncTaskGet.execute(url);
}
}
});
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();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
GPS.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
startPeriodicLocationTask();
}
public void startPeriodicLocationTask() {
Log.d("periodictask", "startPeriodicLocationTask");
GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(this);
PeriodicTask taskBuilder = new PeriodicTask.Builder()
.setService(MyLocationService.class)
.setTag(TASK_GET_LOCATION_PERIODIC)
.setPeriod(30).setFlex(20)
.setPersisted(true).build();
mGcmNetworkManager.schedule(taskBuilder);
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
public void GetNoteList(Context context) {
asyncTaskGet = new AsyncTaskGet(context);
asyncTaskGet.getMethod = this;
}
#Override
public Void getDataFromServer(String objects) {
Log.d("response", objects);
return null;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.d("nogps", "nogps");
break;
}
break;
}
}
}
My gradle:
dependencies {
compile 'com.google.android.gms:play-services:9.8.0'
testCompile 'junit:junit:4.12'
}
I think am making mistake in googleplay service am using late googleplay service version can somebody help me to solve this issue!!
Runtime permissions are your issue, in Android M and above google added the need to request for permissions when they are needed (like in iOS).
See this link: https://developer.android.com/training/permissions/requesting.html
There are many wrappers around to make adding permissions easier on sites like https://android-arsenal.com/tag/235?category=1
Here is some code, taken from android developers site to help you along:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation 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.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}

Android- Get GPS location

I'm doing a project where i need to get the gps location when an anomaly occurs.
How i call/start the gps location in a method inside my Anomaly class?
So i have a class Anomaly and i've used this class to get the gps location:
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
public class GPS extends Activity {
private LocationManager locationManager;
private LocationListener locationListener;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n "+location.getLatitude()+" "+location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
}else {
updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
updateGPS();
}
}
public void updateGPS() {
locationManager.requestLocationUpdates("gps", 3600000, 0, locationListener);
}
}
this is my class Anormaly (i'm a begginer so i don´t know what i should extend and if i need to start a new intent)
public class Anomaly extends AppCompatActivity{
private GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
}
public void abnormalHRDetected(int heartRateInt) {
if (heartRateInt < 40 || heartRateInt > 120) {
Intent intent = new Intent(this, GPS.class);
startActivity(intent);
finish();
}
}
It's simple. I'm receiving the heart rate and i put that on a screen "data". When the value of the heart rate it's lower than 40 or bigger than 120 occurs an anomaly and i want get the gps location at the moment (to send to a data base not to put that on the screen) sorry about my english
Make sure you should give access_gps and access_finelocation permissions in your manifest file.
The below code may help you to fix your problem
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
public class GPS extends Activity {
private LocationManager locationManager;
private LocationListener locationListener;
private TextView textView;
Location cLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
}else {
cLocation = updateGPS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED)
cLocation = updateGPS(); //In update gps method the textview will set to current lat & long values and it returns the current location to your cLocation variable, if you wana use that values further you can use with cLocation variable.
}
}
public Location updateGPS() {
Location currentLocation;
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
textView.append("\n "+location.getLatitude()+" "+location.getLongitude());
currentLocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
locationManager.requestLocationUpdates("gps", 3600000, 0, locationListener);
}
return currentLocation;
}
}
Refer this link
https://github.com/HariKrish4/TurnNavigation
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.location.Location;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 100;
private GoogleMap mMap;
ArrayList<LatLng> list = new ArrayList<>();
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private LocationRequest mLocationRequest;
private Marker marker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// 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);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getDirections();
}
private void getDirections() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url = "https://maps.googleapis.com/maps/api/directions/json?origin=triplicane,chennai&destination=saidapet,chennai&sensor=false";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
try {
JSONObject json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
list = decodePoly(encodedString);
// Polylines are useful for marking paths and routes on the map.
mMap.addPolyline(new PolylineOptions().geodesic(true)
.addAll(list)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
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.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
} else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
putNavigationMarker();
createLocationRequest();
startLocationUpdates();
}
}
private void startLocationUpdates() {
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;
}else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
private void putNavigationMarker() {
LatLng mapCenter = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mapCenter, 13));
// Flat markers will rotate when the map is rotated,
// and change perspective when the map is tilted.
marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_navigation_black_48dp))
.position(mapCenter)
.flat(true)
.rotation(245));
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(16)
.bearing(90)
.build();
// Animate the change in camera view over 2 seconds
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);
}
public void animateMarker(final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 500;
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);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_ACCESS_FINE_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
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;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
putNavigationMarker();
} else {
// permission denied
finish();
}
break;
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng mapCenter = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
animateMarker(marker,mapCenter,false);
}
}
I suggest to use the code below, use the interface LocationListener like a parameter. That way you don´t need to start Activity to get Location as in the original code.
Make sure you give ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION and ACCESS_NETWORK_STATE permissions on your manifest file.
public class LocationSuporte
{
private LocationListener mLocationListener;
private final static String TAG = "Location Suporte";
private Context mContext;
public LocationSuporte(Context mContext, LocationListener mLocationListener) {
this.mLocationListener = mLocationListener;
this.mContext = mContext;
}
public boolean isGPSEnable() {
LocationManager lManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
return lManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public boolean isNetworkAvailable() {
final ConnectivityManager connectivityManager = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
public Location getLocation() {
Location location = null;
LocationManager lManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(mContext,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
return null;
}
try {
boolean isGPSEnabled = this.isGPSEnable();
Log.d(TAG, "isGPSEnabled = " + isGPSEnabled);
boolean isNetworkEnabled = isNetworkAvailable();
Log.d(TAG, "isNetworkEnabled = " + isNetworkEnabled);
if (isNetworkEnabled) {
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, this.mLocationListener);
if (lManager != null) {
location = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled && location == null) {
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this.mLocationListener);
Log.d("GPS Enabled", "GPS Enabled");
if (lManager != null) {
location = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
} catch (Exception e) {
e.printStackTrace();
}
lManager.removeUpdates(this.mLocationListener);
return location;
}
}
Use example;
public void abnormalHRDetected(int heartRateInt)
{
if (heartRateInt < 40 || heartRateInt > 120) {
Location location = new LocationSuporte(getApplicationContext(), new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("EXAMPLE","onLocationChanged");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("EXAMPLE","onStatusChanged");
}
#Override
public void onProviderEnabled(String s) {
Log.d("EXAMPLE","onProviderEnabled");
}
#Override
public void onProviderDisabled(String s) {
Log.d("EXAMPLE","onProviderDisabled");
}
}).getLocation();
Log.d("EXAMPLE","\n "+location.getLatitude()+" "+location.getLongitude());
}
}

android: Location returns null object reference error

I am trying to get the user's location, more specifically their city. The app asks for permission at runtime. But when it tries to put the location into an ArrayList, it gives a null object reference error.
I will comment the specific line below.
What am I doing wrong?
ERROR
Attempt to invoke virtual method 'java.util.List android.location.Geocoder.getFromLocation(double, double, int)' on a null object reference
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class PhoneList extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
private String provider;
public final static int MY_PERMISSIONS_REQUEST_READ_LOCATION = 1;
public double myLng;
public double myLat;
List addresses = new ArrayList();
public Geocoder myGeo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_list);
if (1 == 0) {
showAlert();
} else {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
GetLocationPermission();
return;
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
myLat = location.getLatitude();
myLng = location.getLongitude();
}
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
public void GetLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_LOCATION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
System.out.println("Yes");
} else {
System.out.println("boo");
}
return;
}
}
}
#Override
public void onLocationChanged(Location location) {
try {
//ERROR IS ON THIS LINE
addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Looks like you haven't initialized your myGeo reference.
To fix it, just initialize it before you call getFromLocation(). As a side note, you should also make sure that the Location is not null, since the locationManager.getLastKnownLocation() call has the potential to return null.
#Override
public void onLocationChanged(Location location) {
try {
//Add initialization:
myGeo = new Geocoder(this, Locale.getDefault());
//Make sure that the Location is not null:
if (location != null) {
addresses = myGeo.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
}
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}

Categories

Resources