android Location Listener - android

i want to listen to both GPS and NETWORK location provider from the same listener and implementation
is this ok for doing that:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,metersToUpdate,this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,metersToUpdate,this);
will it user the same methods for both providers ?

Google says here:
You can also request location updates from both the GPS and the Network Location Provider by calling requestLocationUpdates() twice—once for NETWORK_PROVIDER and once for GPS_PROVIDER.

It's simple as 1.2.3 look at my example...
try {
Criteria criteria = new Criteria();
mLocationManagerHelper.SetLocationManager((LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE));
mLocationManagerHelper.GetLocationManager().requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, mLocationManagerHelper.GetLocationListener());
String provider = mLocationManagerHelper.GetLocationManager().getBestProvider(criteria, false);
Location location = mLocationManagerHelper.GetLocationManager().getLastKnownLocation(provider);
if (location != null) {
mLongitude = location.getLongitude();
mLatitude = location.getLatitude();
}
} catch (Exception ex) {
Log.e(TAG, "GPS", ex);
}
Location helper
public class LocationManagerHelper {
private static final String TAG = LocationManagerHelper.class.getSimpleName();
private Context mContext;
private LocationManager mLocationManager;
private GeoUpdateHandler mLocationListener = new GeoUpdateHandler();
public LocationManagerHelper(Context context) {
this.mContext = context;
}
public GeoUpdateHandler GetLocationListener() {
return mLocationListener;
}
public void SetLocationManager(LocationManager locationManager) {
mLocationManager = locationManager;
}
public LocationManager GetLocationManager() {
return mLocationManager;
}
public void Stop() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(mLocationListener);
}
}
private class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
}

Google provides a better API, using fused location API:
https://developers.google.com/location-context/fused-location-provider/
https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient
https://developer.android.com/training/location/receive-location-updates
https://github.com/sakurabird/Android-Fused-location-provider-example
https://youtu.be/eHjHlujp3Tg?list=WL&t=2129

Related

Using Google Play location API in a seperated class?

In the Android Developer guide, Google showed how to use the Google Play Services API in an activity class. What is the best way to offload the API calls into a separate class?
public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The code I wrote above does not work since onConnected is never called since this is not an activity. Is there a better way to separate the GPS services from the Main Activity or is that the only option(If so, is there a reason as to why?) Perhaps making a thread in the main activity to run in the background?
Thanks!
onConnected is called, I made a mistake with reading the logs!
Here is an example :
public class LocationManager implements LocationListener {
private LocationManager locationManager;
public LocationManager()
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location mobileLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null)
{
onLocationChanged(mobileLocation);
}
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null)
{
onLocationChanged(netLocation);
}
}
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
// Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
// Log.e(TAG, "addr : " + addresses.toString());
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
public void pause() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
public void destroy() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
}

how to find location through gps on my phone

I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}

Not getting GPS location, though Google map is showing current location

I am not getting GPS location in my code, while Google maps is showing current location and even its updating, I am starting a service, inside service registering locationListener to the locationManager, handling onLocationChanged callback method, doing entry in the AndroidManifest.xml even. The logs onCreate methods is showing.
below is my code, could you guys please let me know where i am doing wrong...
public class LocationService extends Service implements LocationListener {
private static final long MIN_TIME_INTERVAL_FOR_GPS_LOCATION = 100;
private static final float MIN_DISTANCE_INTERVAL_FOR_GPS_LOCATION = 1.0f;
private static String TAG = LocationService.class.getSimpleName();
private LocationManager locationManager;
private static Location mCurrentLocation;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate...");
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_INTERVAL_FOR_GPS_LOCATION, MIN_DISTANCE_INTERVAL_FOR_GPS_LOCATION, this);
mCurrentLocation = getBestLocation();
}
private Location getBestLocation() {
Log.i(TAG, "getBestLocation...");
Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If both are available, get the most recent
if (location_gps != null && location_network != null) {
return (location_gps.getTime() > location_network.getTime()) ? location_gps : location_network;
} else if (location_gps == null && location_network == null) {
return null;
} else {
return (location_gps == null) ? location_network : location_gps;
}
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged...");
Toast.makeText(LocationService.this, "Location Found", Toast.LENGTH_SHORT).show();
mCurrentLocation = location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static Location getmCurrentLocation() {
return mCurrentLocation;
}
public static void setmCurrentLocation(Location mCurrentLocation) {
LocationService.mCurrentLocation = mCurrentLocation;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy...");
locationManager.removeUpdates(this);
}
}
Your locationManager called requestLocationUpdates using GPS provider only.
I think your device could not catch GPS satellite signal, in-door sate.
So, you should call requestLocationUpdates using Network provider too.
Next two links are may helpful to you.
http://developer.android.com/guide/topics/location/strategies.html
http://developer.android.com/training/location/receive-location-updates.html

Why current location of android phone don't change when i change location?

I get location of android phone as:
android.location.Location locationA;
LocationManager locationManager;
Criteria cri = new Criteria();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String tower = locationManager.getBestProvider(cri, false);
locationA = locationManager.getLastKnownLocation(tower);
if (locationA != null) {
// lat = (double) (locationA.getLatitude() * 1E6);
// longi = (double) (locationA.getLongitude() * 1E6);
double lat = locationA.getLatitude();
double longi = locationA.getLongitude();
TextView txt = (TextView) findViewById(R.id.textView1);
String td = String.valueOf(lat) + "," + String.valueOf(longi);
txt.setText(td);
}
Why current location of android phone don't change when i change location and get again current location?
check the time of your location using locationA.getTime(). if it was not up to date wait for a new location and then stop.
private static Location currentLocation;
private static Location prevLocation;
public void yourMethod()
{
locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
MIN_DISTANCE, locationListener);
}
private static LocationListener 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) {
gotLocation(location);
}
};
private static void gotLocation(Location location) {
prevLocation = currentLocation == null ?
null : new Location(currentLocation);
currentLocation = location;
if (isLocationNew()) {
// do something
locationManager.removeUpdates(locationListener);
}
}
private static boolean isLocationNew() {
if (currentLocation == null) {
return false;
} else if (prevLocation == null) {
return false;
} else if (currentLocation.getTime() == prevLocation.getTime()) {
return false;
} else {
return true;
}
}

Current user location is not retrieving

This is my last question about gps
Getting 0.0 for latitude and longitude while showing current location in map
Now here is the code I'm using to get the user's current location.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(crta, true);
Location loc = null;
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
}
LocationListener mlocListener = new MyLocationListener();
mlocListener.onLocationChanged(loc);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 10, mlocListener);
public class MyLocationListener implements LocationListener{
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location loc) {
if (null != loc) {
String Text = "Your current location is: \n" + "Latitude = \n"
+ loc.getLatitude() + "\nLongitude = \n" + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
GeoPoint myGeoPoint = new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
mpc.animateTo(myGeoPoint);
mpc.setZoom(10);
objMapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText(getApplicationContext(), "gps disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "gps enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Now the problem I'm facing is, it is not showing me the current location when the gps is turned on. The loc object , loc = mlocManager.getLastKnownLocation(provider); always returns null. I got the value for provider as gps.
But if I turn of my gps connection, the same loc object will have relevant information and it works partiall correct. That means, it gives me the nearest location. I mean the full city location where I am sitting.
But if I on my gps connection, it does not give me even the city location also, does not enters if loop only inside location listener class. I am not getting what is going wrong here.
Any one can tell me how to solve it?
Update:
This is the value I get for loc object if my gps is off
Location[mProvider=network,mTime=1331718353322,mLatitude=12.9053401,mLongitude=74.8359128,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy=36.0,mExtras=Bundle[mParcelledData.dataSize=148]].
But if the gps is on, loca return null
CustomLocationManager.Java
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class CustomLocationManager {
private LocationManager mLocationManager;
private LocationValue locationValue;
private Location networkLocation = null;
private Location gpsLocation = null;
private Timer mTimer;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private static CustomLocationManager _instance;
private CustomLocationManager() {}
public static CustomLocationManager getCustomLocationManager() {
if (_instance == null) {
_instance = new CustomLocationManager();
}
return _instance;
}
public LocationManager getLocationManager(Context context) {
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return mLocationManager;
}
public boolean getCurrentLocation(Context context, LocationValue result) {
locationValue = result;
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
try {
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!isGpsEnabled && !isNetworkEnabled)
return false;
if (isGpsEnabled)
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
if (isNetworkEnabled)
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
mTimer = new Timer();
mTimer.schedule(new GetLastKnownLocation(), 20000);
return true;
}
LocationListener gpsLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(networkLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener networkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(gpsLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastKnownLocation extends TimerTask {
CurrentLocationHandler handler;
GetLastKnownLocation() {
handler = new CurrentLocationHandler();
}
#Override
public void run() {
mLocationManager.removeUpdates(gpsLocationListener);
mLocationManager.removeUpdates(networkLocationListener);
if (isGpsEnabled)
gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkEnabled)
networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
handler.sendEmptyMessage(0);
}
}
private class CurrentLocationHandler extends Handler {
#Override
public final void handleMessage(Message msg) {
if (gpsLocation != null && networkLocation != null) {
if (gpsLocation.getTime() > networkLocation.getTime())
locationValue.getCurrentLocation(gpsLocation);
else
locationValue.getCurrentLocation(networkLocation);
return;
}
if (gpsLocation != null) {
locationValue.getCurrentLocation(gpsLocation);
return;
}
if (networkLocation != null) {
locationValue.getCurrentLocation(networkLocation);
return;
}
locationValue.getCurrentLocation(null);
}
}
}
LocationValue.Java
import android.location.Location;
public abstract class LocationValue {
public abstract void getCurrentLocation(Location location);
}
YourActivity.Java
private void getCurrentLocation() {
CustomLocationManager.getCustomLocationManager().getCurrentLocation(this, locationValue);
}
public LocationValue locationValue = new LocationValue() {
#Override
public void getCurrentLocation(Location location) {
// You will get location here if the GPS is enabled
if(location != null) {
Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
}
}
};
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
First of all I'm not familiar with the Android location API, but did you try the GPS outside? Since GPS doesn't work inside buildings, it's pretty hard to retrieve the location of your mobile device using only your GPS. When indoors, typically your "GPS" position is determined using your WiFi acces point connection instead.

Categories

Resources