Print Longitude and Latitude in textbox Android - android

I have looked about and cannot find any direct threads regarding what I am looking for. I am trying to create an Android application which dials out an emergency number at the push of a button (which I have got working) but cannot get the location (displayed in Longitude and Latitude) to display, I have tried doing it with Toast and EditText boxes. I am new to Android development so wanted to start with something easy, but the LongLat part is being troublesome. Any help would be greatly appreciated.
Below is the code I have been tampering with in order to try and get it to grab the Long and Lat, then in another file I have been trying to use a click listener to assign it to a button so when the button is pressed (in main.xml) it will display the Long and Lat either in a textfield or in toast.
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Context;
import android.location.LocationManager;
import android.location.Criteria;
public class EmergencyLocation extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView);
longitudeField = (TextView) findViewById(R.id.long_lat);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialise the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
private void TextView() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}}

First, you need to set up a LocationManager:
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// set preferred provider based on the best accuracy possible
Criteria fineAccuracyCriteria = new Criteria();
fineAccuracyCriteria.setAccuracy(Criteria.ACCURACY_FINE);
String preferredProvider = manager.getBestProvider(fineAccuracyCriteria, true);
Now, you have to create a LocationListener. In this case, it calls the method updateLocation():
LocationListener listener = new LocationListener() {
public void onLocationChanged(Location location) {
// called when a new location is found by the network location provider.
updateLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
EDIT:
Then, you have to register the listener with your LocationManager (and try to get the cached location):
manager.requestLocationUpdates(preferredProvider, 0, 0, listener);
// get a fast fix - cached version
updateLocation(manager.getLastKnownLocation());
And finally, the updateLocation() method:
private void updateLocation(Location location) {
if (location == null)
return;
// save location details
latitude = (float) location.getLatitude();
longitude = (float) location.getLongitude();
}
EDIT2:
OK, just saw your code. In order to make it work, just move around a few bits:
/** Called when the activity is first created. **/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView);
longitudeField = (TextView) findViewById(R.id.long_lat);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
onLocationChanged(location);
}
#Override
protected void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");
}
}
Hope it helps!

Quite easy. I use the locationListener as an attribute inside a Location class. Here's how I do it:
package com.rifsoft.android.helper.location;
import com.rifsoft.android.helper.IListener;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class Location implements IListener
{
public final static int IDX_LATITIDE = 0;
public final static int IDX_LONGITUDE = 1;
private double[] lastLocation = {0.0, 0.0};
private LocationManager locationManager = null;
private ILocation activity = null;
private LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(android.location.Location location)
{
// TODO: http://developer.android.com/guide/topics/location/obtaining-user-location.html#BestEstimate
lastLocation[IDX_LATITIDE] = location.getLatitude();
lastLocation[IDX_LONGITUDE] = location.getLongitude();
activity.onLocationChange();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
/**
* Constructor, needs LocationManager
* #param activity Activity that will receive the notification when location has changed
* #param locationManager LocationManager
*/
public Location(final ILocation act, LocationManager lm) throws LocationException
{
if (lm == null)
{
throw new LocationException(LocationException.ERR_NULL_LOCATION_MANAGER);
}
if (act == null)
{
throw new LocationException(LocationException.ERR_NULL_ILOCATION);
}
locationManager = lm;
activity = act;
registerListener();
android.location.Location lastCachedLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastCachedLocation != null)
{
lastLocation[IDX_LATITIDE] = lastCachedLocation.getLatitude();
lastLocation[IDX_LONGITUDE] = lastCachedLocation.getLatitude();
}
}
/**
* Retuns last known most accurate location as latitude, longitude
* #return Latitude, Longitude
*/
public double[] getLastLocation()
{
return lastLocation;
}
#Override
public void registerListener()
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
public void unRegisterListener()
{
locationManager.removeUpdates(locationListener);
}
}
Then the activity.onLocationChange() goes like
public void onLocationChange()
{
locationUpdated = true;
double[] coordinates = location.getLastLocation();
EditText lon = (EditText) activity.findViewById(R.id.longitude_value);
lon.setText(String.valueOf(coordinates[Location.IDX_LONGITUDE]));
EditText lat = (EditText) activity.findViewById(R.id.latitude_value);
lat.setText(String.valueOf(coordinates[Location.IDX_LATITIDE]));
}

Related

Not getting location coordinates unless location has changed

Here is what I need to do. I need to launch my application and on the click of a button, I need to display the current coordinates, that is latitude and longitude. I followed this tutorial and used the following code for my purpose:
public class MainActivity extends Activity {
public double latitude;
public double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
final TextView latValueLabel = (TextView)findViewById(R.id.latLabel);
final TextView lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#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
}
}
(Copy pasted only a part of the code, please ignore any unclosed brackets or anything like that.)
It continuously gets the latitude longitude as location changes and stores it to two double variables latitude and longitude and when the setButton is clicked, it displays the last stored lat-lon value. That would be the user's current location. Now the issue is, I launched the app and while still staying on the exact location from which the app is launched, I clicked the Set Button. But at that time the location is not changed, so the latitude and longitude are displayed as zero, which is the default value of the double variables. I need to take a walk around with the device so that the location is changed before I can get my actual coordinates. How can I get the lat-lon as soon as the app is launched?
You can use getLastKnownLocation(...) to initialise the longitude and latitude values like this:
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
This is your total class.
public class MainActivity extends Activity {
public double latitude;
public double longitude;
private TextView latValueLabel,lonValueLabel ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
#Override
protected void onStart() {
super.onStart();
latValueLabel = (TextView)findViewById(R.id.latLabel);
lonValueLabel = (TextView)findViewById(R.id.lonLabel);
Button setButton = (Button)findViewById(R.id.set_button);
setButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
});
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latValueLabel.setText(String.valueOf(latitude));
lonValueLabel.setText(String.valueOf(longitude));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}

Arcgis : how to get device location

Hie i tried to implement this codes in my application but it doesnt work , i dont know where i went wrong.
basically, when i launch the sample of the device location. it doesnt show me where is my current location and i dont see any blue dots that resembles the current location i am at.
the only thing that i see is the map . just a plain zoom out map.
I would be really thankful if someone who could help me out on how to get the current location with the blue dots that is displayed on the map..
this is my MainActivity.class
public class HelloWorld extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
LocationService ls = mMapView.getLocationService();
ls.setAutoPan(false);
ls.start();
}
}
});
}
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
}
this is a code that draws my location every 1 second via provider and GPS .
let's first declare variables :
private GraphicsLayer myGraphicalLayer;
MapView mMapView;
ArcGISLocalTiledLayer baseLayer;
private LocationManager mlocManager;
private LocationListener mlocListener;
in onCreate function WE CALL LocationListener:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mlocListener);
// loading the map
mMapView = (MapView) findViewById(R.id.localMap);
baseLayer = new ArcGISLocalTiledLayer(basemapurl);
mMapView.addLayer(baseLayer);
// defining my position layer
myGraphicalLayer = new GraphicsLayer();
then a function to draw my location :
private void SetMyLocationPoint(final double x, final double y) {
PictureMarkerSymbol myPin = new PictureMarkerSymbol(getResources().getDrawable(
R.drawable.mylocation_icon));
Point wgspoint = new Point(x, y);
Point mapPoint = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
Graphic myPinGraphic = new Graphic(mapPoint, myPin);
try {
myGraphicalLayer.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
myGraphicalLayer.addGraphic(myPinGraphic);
myGraphicalLayer.setVisible(true);
mMapView.addLayer(myGraphicalLayer);
}
make internal class that implements MyLocationListener to get you instant location, and let it call the function named SetMyLocationPoint like this way :
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SetMyLocationPoint(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "provider enabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "provider disabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You need to use your own location manager or the location client to get the device's current location and then you will have to add that point on the map.
Your map should be in a MapFragment.
Get the googleMap object from the fragment and then add your custom blue dot on it.
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
}
}
#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
}
};
The above code gets you the location in onLocationChanged method.
Note: i have used GPS_PROVIDER to get the location.
There are other ways to get the current location too.

Access LocationManager/ LocationListener from class

I'm kinda lost here: In my main activity, I register a LocationManager and connect it to a LocationListener to use myLocation.getLatitude() and such.
Now I need to use the Location- methods from another class.
I can't use those object from another class because I cant intantiate the main activity.
I can't use getters to pass the L.Manager or L.Listener around, because those are non- static again.
So, in general, how do i access objects that I created in the main activity?
Any hints on how to organize this better? Is the LocationListener class within the main activity class a stupid thing to do in general?
public class URNavActivity extends Activity
{
public LocationManager mlocManager;
public LocationListener mlocListener;
...
}
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mResourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
actVar=this;
initGraph();
setMap();
gpsEnable();
initMyLocation();
getItems();
initOverlay();
}
public void gpsEnable ()
{
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
myMap.getController().setCenter(new GeoPoint(lati, longi));
}
First and foremost your LocationListener should not be part of an activity. Activities have a clearly defined lifecycle and can come into being, and be destroyed, by the Android framework on an as-needed basis. Therefore the instance variables of your Activity will need to be re-initialised in your activity's onResume() method, making them completely unsuitable for long-term storage.
So. Start by creating a sticky service to manage the starting and stopping of location updates. Being sticky means that the service instance hangs around between invocations and therefore you can reliably use instance variables and know that they will retain their values until the service is terminated. This service should also implement the LocationListener interface, and now it can store the Location notified to it when onLocationChanged is invoked:
public class LocationService extends Service implements LocationListener {
private LocationManager locationManager;
private Location location;
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
Logging.i(CLAZZ, "onHandleIntent", "invoked");
if (intent.getAction().equals("startListening")) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else {
if (intent.getAction().equals("stopListening")) {
locationManager.removeUpdates(this);
locationManager = null;
}
}
return START_STICKY;
}
#Override
public IBinder onBind(final Intent intent) {
return null;
}
public void onLocationChanged(final Location location) {
this.location = location;
// TODO this is where you'd do something like context.sendBroadcast()
}
public void onProviderDisabled(final String provider) {
}
public void onProviderEnabled(final String provider) {
}
public void onStatusChanged(final String arg0, final int arg1, final Bundle arg2) {
}
}
Now you have a service you can start and stop the location updates as you need them. This also allows you to continue to receive and process location changes even when your application is not in the foreground, if that is what you want.
You now have two choices on how to make that Location information available: Use context.sendBroadcast() to propagate the new Location to (for example) an activity, or use the bound service approach to allow other classes to invoke the exposed API and obtain the Location. See http://developer.android.com/guide/topics/fundamentals/bound-services.html for more details on creating a bound service.
Note that there are many other aspects to listening for location updates that I have not included here, for the sake of clarity.
I would offer two elegant ways to access your object from anywhere:
use a Singleton design pattern
use ProjectApp class. This class can be accessed from any activity simply by calling getApplication().
ProjectApp app = (ProjectApp)getApplication();
I used a combination of the two:
public class MyApp extends Application {
private MyLocation mMyLocation;
#Override
public void onCreate() {
super.onCreate();
mMyLocation = new MyLocation();
mMyLocation.getLocation(this, GlobalData.getInstance(), true);
}
}
You can see that GlobalData is a singleton class that implements LocationResult interface, meaning that it will send the updated location to this object.
When I need to get the updated location, I take it from GlobalData.
Here is MyLocation class implementation (I used some code from here and made some changes:
package com.pinhassi.android.utilslib;
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;
public class MyLocation {
private Timer timer1;
private LocationManager lm;
private LocationResult locationResult;
private boolean gps_enabled=false;
private boolean network_enabled=false;
private boolean mContinuesUpdates;
private int decimalAccuracy;
/**
* Class constructor
*/
public MyLocation(){
decimalAccuracy = 0;
}
public boolean getLocation(Context context, LocationResult result, boolean continuesUpdates)
{
mContinuesUpdates = continuesUpdates;
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(getDecimalAccurated(location));
if (!mContinuesUpdates)
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(getDecimalAccurated(location));
if (!mContinuesUpdates)
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(getDecimalAccurated(gps_loc));
else
locationResult.gotLocation(getDecimalAccurated(net_loc));
return;
}
if(gps_loc!=null){
locationResult.gotLocation(getDecimalAccurated(gps_loc));
return;
}
if(net_loc!=null){
locationResult.gotLocation(getDecimalAccurated(net_loc));
return;
}
locationResult.gotLocation(null);
}
}
/**
* called when the GPS returns a location.
* can be called multiple times as the location is updated
*/
public interface LocationResult {
public void gotLocation(Location location);
}
/**
* sets location result accuracy
* #param n number of places after the point. negative value or 0 means not set.
*/
public void setDecimalAccuracy(int n)
{
this.decimalAccuracy = n;
}
private Location getDecimalAccurated(Location location) {
if (decimalAccuracy > 0){
double accuracy = Math.pow(10, this.decimalAccuracy);
int ix;
ix = (int)(location.getLatitude() * accuracy);
location.setLatitude(((double)ix)/accuracy);
ix = (int)(location.getLongitude() * accuracy);
location.setLongitude(((double)ix)/accuracy);
}
return location;
}
}
I'll talk in general since I had the same issue:
How to manage the LocationListener and lit this listener access the activity ..
This was my try :
The Listener :
public class MyLocationListener implements LocationListener{
ProgressDialog dialog;
LocationManager locManager;
Context context;
public MyLocationListener (Context context,ProgressDialog dialog){
this.context = context;
this.dialog = dialog;
}
public void startSearch() {
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// If the network provider works run it , else try GPS provider
// TODO : what happens if GPS and Network providers are not suuported ??
if(!locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) )
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
else
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, this);
dialog = new ProgressDialog(context);
dialog.setTitle("");
dialog.setMessage(context.getString(R.string.pleaseWait));
dialog.setButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
locManager.removeUpdates(MyLocationListener .this);
dialog.dismiss();
return;
}
});
dialog.show();
}
// Location Listener implementation
// read Android doc for more info
// this methods is triggered when new location ( latitiude and longitude ) is found by the system
private void updateWithNewLocation(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
//THIS IS MY ACTIVITY
MainActivity mainActivity = (MainActivity) context;
mainActivity.init();
} else {
//this.setSummary( "No location found" );
}
// remove the listener , we don't need it anymore
locManager.removeUpdates(this);
dialog.hide();
}
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) {
}
}
init the listener in the MainActivity like this :
ProgressDialog dialog;
.
.
.
new MyLocationListener (this, dialog).startSearch();
I don't know if that help ? but that was my solution ...

LocationListener InSide AsyncTask

Hi I am New to android programming and currently developing an application that uses location manager to get user location and place a marker on a map. i am attempting to use AsyncTask to run the LocationListener and Constantly update the marker when the user location has changed.
this is the class i am working on...
public class IncidentActivity extends MapActivity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this.setContentView(R.layout.incidentactivity);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setTraffic(true);
mapController = mapView.getController();
String coordinates[] = {"-26.167004","27.965505"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));
mapController.animateTo(geoPoint);
mapController.setZoom(16);
mapView.invalidate();
new MyLocationAsyncTask().execute();
}
private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{
private double latLocation;
private Location l;
//location management variables to track and maintain user location
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected Void doInBackground(Void... arg0) {
Looper.prepare();
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener);
this.publishProgress(l);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Location... values) {
super.onProgressUpdate(values);
}
//this method is never executed i dont know why...?
public void onLocationChanged(Location location) {
if (location != null){
latLocation = location.getLatitude();
Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show();
//Log.d("Your Location", ""+latLocation);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
I've just implemented such AsyncTask:
class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener
{
final long TWO_MINUTES = 2*60*1000;
private Location location;
private LocationManager lm;
protected void onPreExecute()
{
// Configure location manager - I'm using just the network provider in this example
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
nearProgress.setVisibility(View.VISIBLE);
}
protected Location doInBackground(Void... params)
{
// Try to use the last known position
Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If it's too old, get a new one by location manager
if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES)
{
while (location == null)
try { Thread.sleep(100); } catch (Exception ex) {}
return location;
}
return lastLocation;
}
protected void onPostExecute(Location location)
{
nearProgress.setVisibility(View.GONE);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.removeUpdates(this);
// HERE USE THE LOCATION
}
#Override
public void onLocationChanged(Location newLocation)
{
location = newLocation;
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
From what I have read and tried, you cannot use a looper (which is needed by the locationlistener), inside an ASyncTask. Click Here
Actually it mean the two threading models are not compatible, so you can't
use these together. Looper expects to to own the thread that you associate
it with, while AsyncTask owns the thread it creates for you to run in the
background. They thus conflict with each other, and can't be used together.
Dianne Hackborn suggested using a HandlerThread, but I succeeded in getting mine to work inside of an IntentService. I will admit that my code is still a bit of a hack.

Getting an updated location throughout my app

I need to have an updated location throughout my app. I'm trying to do so by adding the code shown below in all my activities. My problem is that I can't be sure the user will stay in one activity long enough to get the update. How can I have some application-wise listener to achieve an updated position every given time (say 30min)?
private LocationManager mLocationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// My activity stuff
}
private Location getBestLocation(LocationManager locationManager) {
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
protected void onResume() {
super.onResume();
// Request location updates at startup
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DIST, this);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DIST, this);
getBestLocation(mLocationManager)
}
#Override
protected void onPause() {
super.onPause();
// Remove the locationlistener updates when Activity is paused
mLocationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
GlobalVars.lat = (Double) (location.getLatitude());
GlobalVars.lng = (Double) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Nothing here
}
#Override
public void onProviderEnabled(String provider) {
Location location = getBestLocation(mLocationManager);
// Initialize the location fields
if (location != null) {
GlobalVars.lat = (Double) (location.getLatitude());
GlobalVars.lng = (Double) (location.getLongitude());
}
}
#Override
public void onProviderDisabled(String provider) {
}
After further investigation, I ended up using a service.
public class LocationService extends Service implements LocationListener {
LocationManager locationManager;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location loc = getBestLocation(locationManager);
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
public void onLocationChanged(Location loc) {
GlobalVars.lat = (Double) (loc.getLatitude());
GlobalVars.lng = (Double) (loc.getLongitude());
}
public static Location getBestLocation(LocationManager locationManager) {
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;
}
public void onProviderEnabled(String s){}
public void onProviderDisabled(String s){}
public void onStatusChanged(String s, int i, Bundle b){}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
}
Every Android application has one Application (or subclass) in it, and you can ovverride the default to provide your own application-wide functionality. Simply subclass android.app.Application to add your additional functionality, and declare your Application in your manifest. In the manifest's <application> node, provide an android:name attribute equal to the full name of your override.
Once you've got that, giving it a static set of access methods is trivial.

Categories

Resources