Find out the speed of the User in android Using GPS - android
I tried to find out the speed of User, while user is moving with device. Here, I followed one link with sample code. i.e: Here SpeedDemo.
The problem is, by using location.getSpeed() method, we are finding the speed. So, for that I changed the location values in device, but every time the value of the location.getspeed() return '0' only. Why it happen, even changing the location itself.
Can any one known about this?
You have to track location Updates, and when the method onLocationChanged(Location location) triggers, you can call location.getSpeed(); it will give you correct speed, if your phone is actually moving.
But if you are testing it on Simulator, and sending location by emulator controller, it will always return 0.
Updated with Example
public class LocationService implements LocationListener {
LocationService locationService;
LocationManager locationManager;
Location lastLocation;
private final String TAG = "LocationService" ;
private final String MOCK_LOCAION_PROVIDER = "FAKE_PROVIDER";
LocationService(Context ctx) {
LocationManager locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
String mocLocationProvider = MOCK_LOCAION_PROVIDER;
if (locationManager.getProvider(mocLocationProvider) != null) {
locationManager.removeTestProvider(mocLocationProvider);
}
locationManager.addTestProvider(mocLocationProvider, false, false, false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);
locationManager.requestLocationUpdates(mocLocationProvider, 0, 0,
this);
try {
List<String> data = new ArrayList<String>();
InputStream is = ctx.getAssets().open("data.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
data.add(line);
}
// Log.e(TAG, data.size() + " lines");
new MockLocationProvider(locationManager, mocLocationProvider, data).start();
} catch (IOException e) {
e.printStackTrace();
}
}
class MockLocationProvider extends Thread {
private List<String> data;
private LocationManager locationManager;
private String mocLocationProvider;
private String LOG_TAG = "MockLocationProvider";
public MockLocationProvider(LocationManager locationManager, String mocLocationProvider, List<String> data) throws IOException {
this.locationManager = locationManager;
this.mocLocationProvider = mocLocationProvider;
this.data = data;
}
#Override
public void run() {
for (String str : data) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Set one position
String[] parts = str.split(",");
Double latitude = Double.valueOf(parts[0]);
Double longitude = Double.valueOf(parts[1]);
float speed = Float.valueOf(parts[2]);
Location location = new Location(mocLocationProvider);
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setSpeed(speed);
// location.setAltitude(altitude);
// Log.d(LOG_TAG, location.toString());
// set the time in the location. If the time on this location
// matches the time on the one in the previous set call, it will
// be
// ignored
location.setTime(System.currentTimeMillis());
locationManager.setTestProviderLocation(mocLocationProvider, location);
}
}
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(TAG, "onLocationChanged");
// Get Location Speed Here
Log.d(TAG, "Speed " +location.getSpeed());
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
// Log.e(TAG, "onProviderDisabled : "+provider);
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
// Log.e(TAG, "onProviderEnabled : "+provider);
}
public void onStatusChanged(String provider, int status, Bundle arg2) {
// TODO Auto-generated method stub
// Log.e(TAG, "onStatusChanged : "+status);
}
}
The Above code is actually a location service class, when you make an instance of this class, it register a fake Location Service(other than GPS, and Network) provider, and input some fake location parameters by a given file.
Below is the data.txt file which has latitude,longitude,speed the above class read this data.txt file and input fake lat,lon, and speed in the location, as well as trigger time to change location is also implemented by Thread.sleep() call.
Data.txt file
24.856449265609735,67.04308920288086,1.64
24.856749265609735,67.04408920288086,7.64
24.856949265609735,67.04508920288086,11.64
24.857649265609735,67.04716920288086,13.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.1
24.857849265609735,67.04729920288086,17.64
24.857949265609735,67.04736920288086,12.64
24.857949265609735,67.04739920288086,16.64
24.857949265609735,67.04742520288086,8.64
24.857949265609735,67.04747020288086,4.64
24.856749265609735,67.04408920288086,6.11
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
24.856949265609735,67.04508920288086,2.13
24.857249265609735,67.04608920288086,0.6
24.856949265609735,67.04508920288086,1.19
24.857249265609735,67.04608920288086,1.6
24.856949265609735,67.04508920288086,2.12
24.857249265609735,67.04608920288086,1.15
I think getSpeed() will work only if the particular location have speed component available with GPS. Otherwise it will returned 0.0 all the time.
For that you can check that using condition location.hasSpeed() method. If true then do your stuff else think another way.
First we need to check whether the Gps Enabled or not using location manager.
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Then , you need to implement GpsStatus.Listener to get the Gps updates. It will return the Gps location updates.
GPSManager.locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
if (GPSManager.gpsCallback != null) {
GPSManager.gpsCallback.onGPSUpdate(location);
}
}
#Override
public void onProviderDisabled(final String provider) {
}
#Override
public void onProviderEnabled(final String provider) {
}
#Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
};
From that location you can able to get the current speed.
speed = location.getSpeed();
Refer to my website here for further details : http://velmm.com/get-current-user-speed-using-gps-android/
Related
GpsStatus.GPS_EVENT_FIRST_FIX often takes a long time to be called
I have an android device that is mounted inside a car. I need to receive gps location updates every second. my problem is that I get all the necessary data (number of satellites , coordinates , time etc .. ) but for some reason "GpsStatus.GPS_EVENT_FIRST_FIX" is not called or if is called it takes a long time (like 30 minutes .. ) why is that ? here is my code : public class ExtProtocolService extends Service implements GpsStatus.Listener { private GpsStatus gpsStatus; private GpsData gpsData; private LocationManager locationManager; private LocationListener locationListener; #Override public void onCreate() { locationManager = (LocationManager) getSystemService(this.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); String provider = locationManager.getBestProvider(criteria, true); if(provider.equals("gps")) { locationListener = new 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 // not used } #Override // not used public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } // update location parameters when location is changed #Override public void onLocationChanged(Location location) { gpsData.setLatitude(location.getLatitude()); L.m("LATLONG", "latitude " + location.getLatitude()); gpsData.setLongitude(location.getLongitude()); L.m("LATLONG", "longitude " + location.getLongitude()); gpsData.setSpeed(location.getSpeed()); gpsData.setHeading(location.getBearing()); gpsData.setAltitude(location.getAltitude()); gpsData.setHdop(location.getAccuracy()); } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); // update location every 1000 ms locationManager.addGpsStatusListener(this); } } #Override public void onGpsStatusChanged(int event) { switch (event) { case GpsStatus.GPS_EVENT_FIRST_FIX: gpsData.setLocked(true); // gps is locked break; case GpsStatus.GPS_EVENT_STOPPED: gpsData.setLocked(false); // gps unreachable break; } gpsStatus = locationManager.getGpsStatus(null); // calc number of satelites fixed Iterable<GpsSatellite> sats = gpsStatus.getSatellites(); int satellites = 0; int satellitesInFix = 0; int timetofix = gpsStatus.getTimeToFirstFix(); for (GpsSatellite sat : sats) { if (sat.usedInFix()) { satellitesInFix++; } satellites++; } gpsData.setNumSatellites(satellitesInFix); L.m("GPS", gpsData.toString()); } } edit : also I can not use the google location API's ..
Mock location not working on Google map
I have used code from this. I have changed it a bit. Below is my code snippet. The problem is Google Map is not showing proper location which i have mocked. public class MockGpsProviderActivity extends Activity implements LocationListener { public static final String LOG_TAG = "MockGpsProviderActivity"; private static final String MOCK_GPS_PROVIDER_INDEX = "GpsMockProviderIndex"; private MockGpsProvider mMockGpsProviderTask = null; private Integer mMockGpsProviderIndex = 0; /** Called when the activity is first created. */ /* * (non-Javadoc) * * #see android.app.Activity#onCreate(android.os.Bundle) */ #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** Use saved instance state if necessary. */ if (savedInstanceState instanceof Bundle) { /** Let's find out where we were. */ mMockGpsProviderIndex = savedInstanceState.getInt(MOCK_GPS_PROVIDER_INDEX, 0); } /** Setup GPS. */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ // // use real GPS provider if enabled on the device // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); // } // else if(!locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) { // otherwise enable the mock GPS provider locationManager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false, false, false, false, true, true, true, Criteria.POWER_LOW, Criteria.ACCURACY_FINE); locationManager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER, true); locationManager.setTestProviderStatus(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis()); // } if (locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) { locationManager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, this); /** Load mock GPS data from file and create mock GPS provider. */ try { // create a list of Strings that can dynamically grow List<String> data = new ArrayList<String>(); /** * read a CSV file containing WGS84 coordinates from the 'assets' folder (The website http://www.gpsies.com offers downloadable * tracks. Select a track and download it as a CSV file. Then add it to your assets folder.) */ InputStream is = getAssets().open("mock_gps_data.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // add each line in the file to the list String line = null; while ((line = reader.readLine()) != null) { data.add(line); } // convert to a simple array so we can pass it to the AsyncTask String[] coordinates = new String[data.size()]; data.toArray(coordinates); // create new AsyncTask and pass the list of GPS coordinates mMockGpsProviderTask = new MockGpsProvider(); mMockGpsProviderTask.execute(coordinates); } catch (Exception e) { } } } #Override public void onDestroy() { super.onDestroy(); // stop the mock GPS provider by calling the 'cancel(true)' method try { mMockGpsProviderTask.cancel(true); mMockGpsProviderTask = null; } catch (Exception e) { } // remove it from the location manager try { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER); } catch (Exception e) { } } #Override public void onSaveInstanceState(Bundle savedInstanceState) { // store where we are before closing the app, so we can skip to the location right away when restarting savedInstanceState.putInt(MOCK_GPS_PROVIDER_INDEX, mMockGpsProviderIndex); super.onSaveInstanceState(savedInstanceState); } #Override public void onLocationChanged(Location location) { // show the received location in the view TextView view = (TextView) findViewById(R.id.text); view.setText("index:" + mMockGpsProviderIndex + "\nlongitude:" + location.getLongitude() + "\nlatitude:" + location.getLatitude() + "\naltitude:" + location.getAltitude()); } #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 } /** Define a mock GPS provider as an asynchronous task of this Activity. */ private class MockGpsProvider extends AsyncTask<String, Integer, Void> { public static final String LOG_TAG = "GpsMockProvider"; public static final String GPS_MOCK_PROVIDER = LocationManager.GPS_PROVIDER; /** Keeps track of the currently processed coordinate. */ public Integer index = 0; #Override protected Void doInBackground(String... data) { // process data for (String str : data) { // skip data if needed (see the Activity's savedInstanceState functionality) if (index < mMockGpsProviderIndex) { index++; continue; } // let UI Thread know which coordinate we are processing publishProgress(index); // retrieve data from the current line of text Double latitude = null; Double longitude = null; Double altitude = null; try { String[] parts = str.split(","); latitude = Double.valueOf(parts[0]); longitude = Double.valueOf(parts[1]); altitude = Double.valueOf(parts[2]); } catch (NullPointerException e) { break; } // no data available catch (Exception e) { continue; } // empty or invalid line // translate to actual GPS location Location location = new Location(GPS_MOCK_PROVIDER); location.setLatitude(latitude); location.setLongitude(longitude); location.setAltitude(altitude); location.setAccuracy(1); location.setTime(System.currentTimeMillis()); location.setBearing(0F); location.setSpeed(0.0F); // show debug message in log Log.d(LOG_TAG, location.toString()); // provide the new location LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER, location); // sleep for a while before providing next location try { Thread.sleep(200); // gracefully handle Thread interruption (important!) if (Thread.currentThread().isInterrupted()) throw new InterruptedException(""); } catch (InterruptedException e) { break; } // keep track of processed locations index++; } return null; } #Override protected void onProgressUpdate(Integer... values) { Log.d(LOG_TAG, "onProgressUpdate():" + values[0]); mMockGpsProviderIndex = values[0]; } } }
Try adding: location.setAccuracy(16F); location.setAltitude(0D); location.setBearing(0F);
I think you can call mock location also in your permissions (Manifest.xml), in order to work. Do you have that,in your permissions? Because when I used it with this,it worked. (Sorry I couldn't leave it as a comment because I don't have enough reputation)
Did you turn on Allow_Mock_Location in the setting of your physical device? It's under developer options.
Also add for your mock location location.setSpeed(5); speed more than 1, like 5 or 10
What is the best way to identify places on gps?
i'm trying to develop application with a gps that can know if i arrive at or leave a specific place. I.E if i am at home so, the application know that and if i leaving my home the application know that too. or if i want to set the radius of my home. but i think the problem is that when i trying to running the appliction and search places every x time it could kill my battery. what is the best solution for that action? should i using services too? here is the class i made to get the place and the coordinates: public class LocationMap extends Service implements LocationListener { public static final String LOG = "locationLogger"; Context context; LocationManager manager; Location location; public static final int REFRESH = 1000*1; public static final int DISTANCE = 1*1; double lat,lng; boolean isGps,isWiFi; public LocationMap(Context context) { this.context = context; getLocation(); } private Location getLocation(){ try { manager = (LocationManager) context.getSystemService(LOCATION_SERVICE); manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,REFRESH,DISTANCE,this); //Check who is on WiFi or GPS isWiFi = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Log.d(LOG, "Wifi?="+isWiFi); isGps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);Log.d(LOG, "Gps?="+isGps); Log.d(LOG, "manager is not null?="+manager); if (manager != null) { if(isGps){ Log.d(LOG, "get last location from Gps"); location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); }else if(isWiFi){ Log.d(LOG, "get last location from WiFi"); location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if (location != null) { lat = location.getLatitude(); lng = location.getLongitude(); Log.d(LOG, "lat="+lat +" lng="+lng); } } } catch (Exception e) { } return location; } public String getPlace(){ String placeName = "No place found, check your gps setting"; try { Geocoder geocoder = new Geocoder(context); List<Address> address =geocoder.getFromLocation(getLat(), getLng(), 1); String country = address.get(0).getCountryName(); String city = address.get(0).getLocality(); String street = address.get(0).getAddressLine(0); placeName = country+", "+city+", "+street; } catch (IOException e) { e.printStackTrace(); } return placeName; } public double getLng(){ return lng; } public double getLat() { return lat; } #Override public void onLocationChanged(Location location) { } #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 IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } sorry about my english. hope you understand me :)
That depends on your accuracy needed. If the desired range is about 1 - 3km then there is a battery saving solution, I will not further explain here. (Using the devices Network locationg procider) For accuracy much better there is no way around using GPS always on, which at my iphone 4 lasts about 8 hours. Detection if arrival is simply done via entering inside a circle, defined by lat,lon, radius. Inside circle is calculated by: boolean isInside = currentLocation.distanceTo(circleCenterLongitude, circleCenterLatitude) < radiusMeters.
android mock gps does not work on real device
I have added: uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" and the code below: public class MockGpsProviderActivity extends Activity implements LocationListener { public static final String LOG_TAG = "MockGpsProviderActivity"; private static final String MOCK_GPS_PROVIDER_INDEX = "GpsMockProviderIndex"; private MockGpsProvider mMockGpsProviderTask = null; private Integer mMockGpsProviderIndex = 0; /** Called when the activity is first created. */ /* (non-Javadoc) * #see android.app.Activity#onCreate(android.os.Bundle) */ #Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); /** Use saved instance state if necessary. */ if(savedInstanceState instanceof Bundle) { /** Let's find out where we were. */ mMockGpsProviderIndex = savedInstanceState.getInt(MOCK_GPS_PROVIDER_INDEX, 0); } /** Setup GPS. */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ // use real GPS provider if enabled on the device locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); } else if(!locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) { // otherwise enable the mock GPS provider locationManager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false, false, false, false, true, false, false, 0, Criteria.ACCURACY_HIGH); locationManager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER, true); } if(locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) { locationManager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, this); /** Load mock GPS data from file and create mock GPS provider. */ try { // create a list of Strings that can dynamically grow List<String> data = new ArrayList<String>(); /** read a CSV file containing WGS84 coordinates from the 'assets' folder * (The website http://www.gpsies.com offers downloadable tracks. Select * a track and download it as a CSV file. Then add it to your assets folder.) */ InputStream is = getAssets().open("mock_gps_data.csv"); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); // add each line in the file to the list String line = null; while ((line = reader.readLine()) != null) { data.add(line); } // convert to a simple array so we can pass it to the AsyncTask String[] coordinates = new String[data.size()]; data.toArray(coordinates); // create new AsyncTask and pass the list of GPS coordinates mMockGpsProviderTask = new MockGpsProvider(); mMockGpsProviderTask.execute(coordinates); } catch (Exception e) {} } } #Override public void onDestroy() { super.onDestroy(); // stop the mock GPS provider by calling the 'cancel(true)' method try { mMockGpsProviderTask.cancel(true); mMockGpsProviderTask = null; } catch (Exception e) {} // remove it from the location manager try { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER); } catch (Exception e) {} } #Override public void onSaveInstanceState(Bundle savedInstanceState) { // store where we are before closing the app, so we can skip to the location right away when restarting savedInstanceState.putInt(MOCK_GPS_PROVIDER_INDEX, mMockGpsProviderIndex); super.onSaveInstanceState(savedInstanceState); } #Override public void onLocationChanged(Location location) { // show the received location in the view TextView view = (TextView) findViewById(R.id.text); view.setText( "index:" + mMockGpsProviderIndex + "\nlongitude:" + location.getLongitude() + "\nlatitude:" + location.getLatitude() + "\naltitude:" + location.getAltitude() ); } #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 } /** Define a mock GPS provider as an asynchronous task of this Activity. */ private class MockGpsProvider extends AsyncTask<String, Integer, Void> { public static final String LOG_TAG = "GpsMockProvider"; public static final String GPS_MOCK_PROVIDER = "GpsMockProvider"; /** Keeps track of the currently processed coordinate. */ public Integer index = 0; #Override protected Void doInBackground(String... data) { // process data for (String str : data) { // skip data if needed (see the Activity's savedInstanceState functionality) if(index < mMockGpsProviderIndex) { index++; continue; } // let UI Thread know which coordinate we are processing publishProgress(index); // retrieve data from the current line of text Double latitude = null; Double longitude = null; Double altitude= null; try { String[] parts = str.split(","); latitude = Double.valueOf(parts[0]); longitude = Double.valueOf(parts[1]); altitude = Double.valueOf(parts[2]); } catch(NullPointerException e) { break; } // no data available catch(Exception e) { continue; } // empty or invalid line // translate to actual GPS location Location location = new Location(GPS_MOCK_PROVIDER); //location.setLatitude(latitude); //location.setLongitude(longitude); location.setLatitude(39.794952); location.setLongitude(116.515134); location.setAltitude(10); //location.setAccuracy(4); location.setTime(System.currentTimeMillis()); // show debug message in log Log.d(LOG_TAG, location.toString()); // provide the new location LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER, location); // sleep for a while before providing next location try { Thread.sleep(200); // gracefully handle Thread interruption (important!) if(Thread.currentThread().isInterrupted()) throw new InterruptedException(""); } catch (InterruptedException e) { break; } // keep track of processed locations index++; } return null; } #Override protected void onProgressUpdate(Integer... values) { Log.d(LOG_TAG, "onProgressUpdate():"+values[0]); mMockGpsProviderIndex = values[0]; } } } I start the mockgps app, then press the home button to make it background. then I write another test application, and it can read the Latitude, Longitude, Altitude. But when I open the google map application, the google map always says that "can not locate". what's the problem? thanks.
Getting GPS data?
Inside public class IAmHere extends Activity implements LocationListener { i have #Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } #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 } and inside public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.iamhere); i have LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = lm.getProviders(true); /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ Location l = null; for (int i=providers.size()-1; i>=0; i--) { l = lm.getLastKnownLocation(providers.get(i)); if (l != null) break; } double[] gps = new double[2]; if (l != null) { gps[0] = l.getLatitude(); gps[1] = l.getLongitude(); } gpsString = (TextView)findViewById(R.id.gpsString); String Data = ""; String koordinata1 = Double.toString(gps[0]); String koordinata2 = Double.toString(gps[1]); Data = Data + koordinata1 + " | " + koordinata2 + "\n"; gpsString.setText(String.valueOf(Data)); but seems it's not working? Why? I mean even emulator doesn't want to send GPS data - When I click "send" via UI or console, nothing happens...? Thank you.
First, you implemented LocationListener on IAmHere, then did nothing with that interface. Second, you are calling getLastKnownLocation(), but you are doing nothing to trigger Android to start collection location data on any provider. These two problems are related. Location services are off until something registers to get location data from them. Typically, this is via requestLocationUpdates() on LocationManager...which uses the LocationListener interface you implemented. The recipe for using LocationManager is: Register a LocationListener via requestLocationUpdates() Unregister the LocationListener sometime (e.g., onDestroy()), so that you do not leak memory When location fixes come into onLocationChanged(), do something useful Here is a sample project that uses LocationManager and LocationListener in this fashion.