I am fetching the location from googleApiClient, when i click on yes in the alert builder of google, then i use onActvityResult to check that if user clicks yes then i set my text view to that location, i am not getting the last location at the same time, so i used do while loop,is it a good practice?
these are the functions to get the location and i set it to text view in onActivityResult method in my activity, please tell me, using this do while is a good practice??
public Location getCurrentLatLong() {
checkLastLocation();
Log.w("checkingsAct", mLastLocation + "");
if(mLastLocation != null) {
Log.w("checkingsAct", mLastLocation+"");
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
mLastLocation.setLatitude(latitude);
mLastLocation.setLongitude(longitude);
Log.w("discheck", latitude + "" + " " + longitude);
}
return mLastLocation;
}
public void checkLastLocation() {
do {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.w("checkingsAct", mLastLocation + "do called");
} while(mLastLocation == null);
You need to request for location update like below
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
If once locaiton is updated, you will get call back in void onLocationChanged(Location location) method.
Related
I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
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;
}
locationManager.requestLocationUpdates(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//
}
in onLocationChanged method you can use location.getLatitude & location.getLongitude
I have an application that tracks users location.
My application uses FusedLocationApi , Google new way of getting device location using Google Play Services.
Provider of locations that i give from GPS is labeled as fused.
Because of application users may change device time, it is important to get real time from GPS.
Problem is that when i try to get time from Location object , it returns device time not GPS time.
Any solutions to get GPS time in this situation are appreciated.
private Location mLastLocation;
public void onConnected(Bundle arg0) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
public void onLocationChanged(Location location) {
mLastLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Date date = new Date(mLastLocation.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String time = dateFormat.format(date)
}
To get GPS UTC, do it in normal way:
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
// not LocationManager.NETWORK_PROVIDER
#Override
public void onLocationChanged(Location location)
{
long utc = location.getTime();
// ....
}
I am trying to get current location of my android phone and display the longitude and latitude in a toast. Here is a function I wrote. While debugging the code I see that the control never goes inside onLocationChanged function.
From the following android documentation it looks like, when I call "locationMgr.requestLocationUpdates", it should call the callback function onLocationChanged. But that does not seem to happen in my code.
http://developer.android.com/training/basics/location/currentlocation.html
I checked my phone has GPS turned on. I can not figure out what is wrong in the following code. Please help.
public void getCurrentLocation(){
LocationManager locationMgr;
locationMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// A new location update is received. Do something useful with it
String latitude = "latitude: " + location.getLatitude();
String longitude = "longitude: " + location.getLongitude();
String toastString = "location is" + latitude + "," +longitude;
Toast.makeText( getApplicationContext(),toastString,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// No code here
}
#Override
public void onProviderEnabled(String provider) {
// No code here
}
#Override
public void onStatusChanged(String provider, int status,Bundle extras)
{
// No code here
}
};
locationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, listener);
}
I also have following two lines in my Manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Thank you for your help.
I am using Eclipse and my phone(OS: Thuderbolt) has API level 15, target 4.0.4.
There are several reasons that you are not getting location.
1.) If you are trying to get location on emulator. Then you have to manually push the coordinates using DDMS.
2.) If You are checking it on device and still you are not getting location. Then as you said that you are expecting it from GPS. Then you should have Clear sky view to get that. As GPS receiver dont work under roofs or under some hinderances. They must have sky view.
3.) You can get location from using wi-fi or cell-Tower. Also you can opt for Last known location if location accuracy is not as much important.
What i think is that may be second point will resolve your problem.
The problem was google-play-services library.
I had to download the library code and compile it in eclipse. Then I added the path to the library in my project. This solved the problem.
Earlier I had included the google-play-services .jar file in my project, but it was not working. Not sure why.
Here is example i wrote that uses LocationManager to get the location data every two minutes. Its not perfect but should be sufficient to solve your issue: It can be found here
Focus on:
#Override
public void onLocationChanged(final Location location) {
this.location=location;
final Handler handler = new Handler();
Timer ourtimer = new Timer();
TimerTask timerTask = new TimerTask() {
int cnt=1;
public void run() {
handler.post(new Runnable() {
public void run() {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
Double altitude = location.getAltitude();
Float accuracy = location.getAccuracy();
textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt);
try {
jsonData = new JSONObject();
jsonData.put("Latitude", latitude);
jsonData.put("Longitude", longitude);
jsonData.put("Altitude", altitude);
jsonData.put("Accuracy", accuracy);
System.out.println(jsonData.toString()); //not required, for testing only
if(url!=null) {
new HttpPostHandler().execute();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cnt++;
}
});
}};
ourtimer.schedule(timerTask, 0, 120000);
i am done code for getting current lat/long as follow but i always get null from lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); method.
i have tried by 2 ways.
the code is below.
first way,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
and second way,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Log.d("GPS_PROVIDER","GPS_PROVIDER = " + lm.isProviderEnabled(LocationManager.GPS_PROVIDER));
Log.d("NW_PROVIDER","NW_PROVIDER = " + lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListenerAdapter()
{
#Override
public void onLocationChanged(Location location)
{
if(location != null)
{
lat = location.getLatitude();
lon = location.getLongitude();
}
}
});
LocationListenerAdapter class is implements the method of LocationListener interface and i keep all method blank
i.e no code written into that methods.
i also use gpx and kml file for emulator to change lat/long but i didn't get yet.
can any one provide best answer.
Thanks in advance.
Following is the code which i am using to find the latitude longitude and location of a place in my app, but it always show no location found
I have added the permissions in manifest file
{
LocationManager locManager;
setContentView(R.layout.main);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
String param = (String)locManager.getProviders(true).get(0);
Location loc = locManager.getLastKnownLocation(param);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
private void updateWithNewLocation(Location location)
{
TextView myLocationText = (TextView)findViewById(R.id.widget52);
String latLongString = " ";
if (location != null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
}
else
{
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
private final LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider)
{
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
}
pls help me...
I've put your code in an Android project and ran it on the emulator and it seems to be working fine.
I would change the code to first check for a lastknown location, and after that check for location updates.
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
If that location is null, or too stale (timestamp) for your needs, you can start requesting location updates. (currently, you're first requesting location updates from the GPS, and then decide to retrieve its lastknownlocation). This might cause the location manager to stop querying the GPS.
Also you need to ensure the following is in place :
For GPS Provider, make sure the following permission is put in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Ensure the GPS is turned on that you have sufficient GPS coverage.
Do this by checking for the GPS icon in your Notification bar
Test on a real device
Although testing GPS location listeners works partly through the emulator, the behavior of an actual device will always be different.
Debug on the emulator
Basic GPS testing can be done using the emulator. Put a breakpoint in your locationlistener, and use the DDMS perspective to send some GPS coordinates to your AVD image.
#Siva, your problem is with the UI thread, as your updates are from different thread.
To verify if this is the UI problem, put a toast or Log cat the message when you receive an update.
Once you know that UI problem, then try using Handler to postInvalidate() the UI.