Reputation: 1654
Cheers, I'm trying to get the current GPS-Location via Android. I followed this Tutorial and Vogellas article aswell. Though it ain't working. When using LocationManager.NETWORK_PROVIDER I'm always getting a latitude of 51 and longitude of 9 - no matter where I stand. When using LocationManager.GPS_PROVIDER, I'm getting nothing at all.
Though Everything works when using GMaps :S No idea why. How can I get the current GPS Location like GMaps does?
Here's my code:
package com.example.gpslocation;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class GPS_Location extends Activity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps__location);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.gps__location, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Upvotes: 35
Views: 125949
Reputation: 1696
Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)
///////////////////////////////////
////////// LOCATION PACK //////////
//
// locationManager: (LocationManager) for getting LOCATION_SERVICE
// osLocation: (Location) getting location data via standard method
// dataLocation: class type storage locztion data
// x,y: (Double) Longtitude, Latitude
// location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
// AutoLocation: class help getting provider info
// tmLocation: (Timer) for running update location over time
// LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
// LocationStart(): LocationStart(500)
// LocationStop(): stop getting location data
//
// EX:
// LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//
LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
@Override public void onLocationChanged(Location p1){}
@Override public void onStatusChanged(String p1, int p2, Bundle p3){}
@Override public void onProviderEnabled(String p1){}
@Override public void onProviderDisabled(String p1){}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,0,0,this);
if (locationManager != null) {
osLocation = locationManager.getLastKnownLocation(provider);
return osLocation;
}
}
return null;
}
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
final AutoLocation autoLocation = new AutoLocation();
tmLocation=cycleF(new Runnable() {public void run(){
Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
location.y = nwLocation.getLatitude();
location.x = nwLocation.getLongitude();
} else {
//bodym.text("NETWORK_LOCATION is loading...").show();
}
Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
location.y = gpsLocation.getLatitude();
location.x = gpsLocation.getLongitude();
} else {
//bodym.text("GPS_LOCATION is loading...").show();
}
}}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}
//////////
///END//// LOCATION PACK //////////
//////////
/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
// import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
// Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
//
// EX:
// delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
// final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
// delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
// final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
// delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
final Handler h = new Handler();
h.postDelayed(r, delay);
return new Runnable(){
@Override
public void run(){h.removeCallbacks(r);}
};
}
public static Timer cycleF(final Runnable r, long interval) {
final Timer t=new Timer();
final Handler h = new Handler();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {h.post(r);}
}, interval, interval);
return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
//////////
///END//// RUNTIME //////////
//////////
Upvotes: 0
Reputation: 3812
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
Upvotes: 9
Reputation: 43
Excerpt:-
try
{
cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e)
{
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.
IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread
Upvotes: 0
Reputation: 111
This code have one problem:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
You can change int
to double
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Upvotes: 13
Reputation: 25755
Here's your problem:
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
Latitude and Longitude are double
-values, because they represent the location in degrees.
By casting them to int
, you're discarding everything behind the comma, which makes a big difference. See "Decimal Degrees - Wiki"
Upvotes: 31
Reputation: 4692
Give it a try :
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
Upvotes: 23