I am new to android and was trying out stuff on my android emulator. While playing with the location manager and location listener, I could test the code of changing location using the emulator. The locationlistener catches the location change and moves to the specific location.
I now want to replicate the same test using my program, i.e. pass new coordinates every x seconds (may be through a thread ?) to the locationlistener, but through my program and not the emulator.
Can someone please suggest a way to go about implementing this functionality ?
The code for location listener that I found somewhere on the net and was trying:
private LocationListener locationListener;
private MapView mapView;
private MapController mc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
lm = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,0,0,locationListener);
mapView = (MapView) findViewById(R.id.mpview);
mc = mapView.getController();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location locn) {
if (locn != null) {
GeoPoint point = new GeoPoint(
(int) (locn.getLatitude() * 1E6),
(int) (locn.getLongitude() * 1E6));
mc.animateTo(point);
mapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
Thanks!
Related
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.
I have to load the current device Location when the MapActivity starts ( it start with an Intent launched from another Activity).
The problem is that looking around the web and in the android developer section I see that i have to use a LocationListener method onLocationChange(location), but i have to get the user location when the MapActivity starts, not when the user change his location. I have tried seveal ways but I don't find a solution.
public class MappaActivity extends MapActivity {
MapView miaMapView;
MapController mc;
LocationManager lm;
GeoPoint actualP;
LocationListener locationListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mappa_activity);
miaMapView=(MapView)findViewById(R.id.miaMapView);
mc=miaMapView.getController();
miaMapView.setBuiltInZoomControls(true);
miaMapView.setSatellite(true);
miaMapView.invalidate();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener=new MyLocationListener();
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// This is MyLocationListener inner class:
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
if(location!=null){
actualP = new
GeoPoint(
(int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6));
mc.animateTo(actualP);
mc.setZoom(10);
}
}
#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
}
}
}
actualP remains null, onLocationChanged method is not fired until the user location is changed.
I also tried with locationManager.getLastKnowLocation(location.GPS_PROVIDER) but it returns null.
I hope to find some help, thanks!
It might be possible that your GPS_PROVIDER is unable to get the location
It will be better if you also use NETWORK_PROVIDER and PASSIVE_PROVIDER for getting the location when your GPS_PROVIDER is unable to give you location
also use lm.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0,locationListener);
and lm.requestLocationUpdates( LocationManager.PASSIVE_PROVIDER, 0, 0,locationListener); may be they are not that much accurate as GPS_PROVIDER.
I am working on a project that has one feature to display (animate to) current user location and one hard coded location(given latitude and longitude). So far I have the hardcoded location working but I can't figure out how to get the user location. I've tried the location listener but my application keeps crashing after I run it. Does anybody have any advice on it? Much appreciated. Here's the code:
public class LocationsActivity extends MapActivity implements LocationListener {
MapView mapView;
MapController mc;
GeoPoint p;
LocationListener locListener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
mapView = (MapView)findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
String coordinates[] = {"52.67596","-8.64910"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint((int)(lat*1E6),(int)(lng*1E6));
OverlayItem overlayitem = new OverlayItem(p, "Limerick Institute of
Technology", "Moylish");
mc.animateTo(p);
mc.setZoom(17);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,
this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
if you are using MapActivity then you can use following code:
/**
* Set current location using MyLocationOverlay
*/
public void setCurrentLocation() {
myLocationOverlay.runOnFirstFix(new Runnable() {
#Override
public void run() {
if (null != myLocationOverlay.getMyLocation()) {
/**
* Put extra sleep to avoid concurrentModicationException
*/
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
map.getController().animateTo(
myLocationOverlay.getMyLocation());
map.getOverlays().add(myLocationOverlay);
}
}
});
}
If you are using MapFragment then inside activity:
1. mapFragment.getMap().setMyLocationEnabled(true);
then call
private void moveMapToMyLocation() {
LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
Location loc = locMan.getLastKnownLocation(locMan.getBestProvider(crit,
false));
CameraPosition camPos = new CameraPosition.Builder()
.target(new LatLng(loc.getLatitude(), loc.getLongitude()))
.zoom(12.8f)
.build();
CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);
mapFragment.getMap().moveCamera(camUpdate);
}
I am building an app in ICS with a mapview within a Fragment.
After initializing the mapView in the activity class I pass it to the mapFragment which is the fragment that is used to display the map.
This is some of the code in my activity class :
mapView = new MapView(this, getString(R.string.mapsAPI));
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(this.myLocationOverlay);
mapView.postInvalidate();
public void calculateLocation() {
setLocationManager();
setLocation();
setGeoPoint(location);
}
public void setGeoPoint(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
geoPoint = new GeoPoint((int)( latitude * 1E6), (int)( longitude * 1E6 ));
}
public void setLocation() {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
public void setLocationManager() {
locationManager = ((LocationManager)getSystemService(Context.LOCATION_SERVICE));
}
and this is the code in my mapFragment class :
public class MapFragment extends Fragment
{
MapView gMap = null;
GeoPoint gPoint = null;
Location location = null;
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
gMap = ((NFCDemoActivity)getActivity()).getMapView();
return this.gMap;
}
public void onActivityCreated(Bundle paramBundle) {
super.onActivityCreated(paramBundle);
((NFCDemoActivity)getActivity()).calculateLocation();
gPoint = ((NFCDemoActivity)getActivity()).getGeoPoint();
gMap.setClickable(true);
gMap.setBuiltInZoomControls(true);
gMap.getController().setZoom(18);
gMap.getController().setCenter(gPoint);
}
public void onDestroy() {
super.onDestroy();
}
}
This will give you the user's current location.
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.
Hi am developing an app that will set the coordinates(latitude and longitude). And it has to show my location as i am at that coordinates..It is similar to location spoofer.. http://www.androidzoom.com/android_applications/tools/location-spoofer_gkmc.html
But I am failing to do that.. here is my code..Please any one help me.
public class Mock extends MapActivity
{
private LocationManager lm;
private LocationListener locationListener;
private MapView mapView;
String mocLocationProvider;
private MapController mc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//---use the LocationManager class to obtain GPS locations---
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
mocLocationProvider=LocationManager.GPS_PROVIDER;
lm.addTestProvider(mocLocationProvider, false, false,false, false, true, true, true, 0, 5);
lm.setTestProviderEnabled(mocLocationProvider,true);
lm.requestLocationUpdates(mocLocationProvider,0,0,locationListener);
mapView = (MapView) findViewById(R.id.mapview1);
mc = mapView.getController();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
loc = new Location(mocLocationProvider);
Double latitude = 1.352566007;
Double longitude = 103.78921587;
//Double altitude = Double.valueOf(parts[2]);
loc.setLatitude(latitude);
loc.setLongitude(longitude);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(mocLocationProvider, loc);
mc.setZoom(16);
mapView.invalidate();
}
#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
}
}
}
I would use this method http://developer.android.com/guide/developing/tools/ddms.html#emulator-control. Haven't tried this one: http://code.google.com/p/android/issues/detail?id=915
You basically set the coordinates on real device in the same way you do in the emulator by using DDMS in Eclipse.
Just make sure you enable "fake locations" in your device. You can find the setting at Settings > Applications > Development > Allow mock locations.