GPS not working - android

What I am doing is trying to get a basic GPS working and can't figure out the problem (there is no errors coming up). When i run it on the emulator it crashes. I am using android 2.2
package Weather.app;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class WeatherAppActivity extends Activity{
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected LocationListener MyLocationListener;
protected Button findButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findButton = (Button) findViewById(R.id.findButton);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
(LocationListener) this
);
findButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message,
Toast.LENGTH_LONG).show();
}
final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(WeatherAppActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
}
This is also in my manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
I have updated this code as I have made a few changes

Here is one example of working basic GPS activity:
public class UseGpsActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
double lati = loc.getLatitude();
double longi = loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + lati + "Longitud = " + longi;
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

Unless some code is missing in your post MyLocationListener (you should not user upper case identifiers for instance fields!) is not initialized when passing the reference (i.e. null) to requestLocationUpdates().

You don't need to create another LocationListener, the statement
WeatherAppActivity extends Activity implements LocationListener
and the overriden methods
#Override
public void onLocationChanged(Location location)
etc means you have one in your main class already, so get rid of the inner class MyLocationListener completely.
Put your Toast code etc inside the overriden listener methods in the main class.
Then in onCreate() have :
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);

I have a tutorial on Android location services on my blog. I'm not sure of your specific error but you can look at the code to see if it helps you!
http://www.scotthelme.co.uk/blog/android-location-services/

Related

Cannot resolve symbol "locationListener" - Android

I am having trouble implementing a LocationListener.
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
TextView locationNameTV;
double latitude;
double longitude;
double altitude;
String locationName;
LocationManager locationManager;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationNameTV = (TextView) findViewById(R.id.locationName);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
locationName = "Placeholder";
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
locationNameTV.setText("Location: \n" + locationName);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
}
}
I'm not sure if it's a syntax issue or a scoping issue, but I keep getting "unable to resolve symbol" errors. It's acting like I haven't implemented the LocationListener methods. I have tried adding implements LocationListener to MainActivity and that shows an error saying I have not implemented the LocationListener methods. I'm not sure where my mistake is.
EDIT:
I've changed my code per your answers. When I try to implement //locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this); I get the following when trying to launch the app: LocationTestApp keeps stopping. I've commented out that line, and the app works again.
public class MainActivity extends AppCompatActivity implements LocationListener {
TextView latitudeTV;
TextView longitudeTV;
TextView altitudeTV;
double latitude;
double longitude;
double altitude;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTV = (TextView) findViewById(R.id.latitude);
longitudeTV = (TextView) findViewById(R.id.longitude);
altitudeTV = (TextView) findViewById(R.id.altitude);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
//locationManager.requestLocationUpdates(Context.LOCATION_SERVICE, 5000, 0, this);
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
altitude = location.getAltitude();
longitudeTV.setText("Longitude: \n" + longitude + "°");
latitudeTV.setText("Latitude: \n" + latitude + "°");
altitudeTV.setText("Altitude: \n" + altitude + "m");
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
A LocationListener class, in this case an Activity, should be defined as below:
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
public class MainActivity extends AppCompatActivity implements LocationListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this); // Note: You pass this, so the overridden methods
}
#Override
public void onLocationChanged(Location location) {
// Do your stuff here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
And this is the solution in jle's comments.
But if you want to use the locationListener that you've declared in your onCreate, you should declare it before using it, in this way:
...onCreate(...) {
...
LocationListener locationListener = new LocationListener() {...} // Define this...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener); // ...and then call this
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}

get Latitude Longitude fail

I have two question with my code
can not enter the onLocationChanged() function
mylocation is always null
I also add the permission and turn on my device GPS function
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name ="android.permission.ACCESS_COARSE_LOCATION"/>
follows is my code please help me to get Latitude Lontitude thanks all.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Getaddress getaddress = new Getaddress();
getaddress.excute();
}
public class Getaddress implements LocationListener {
Geocoder geocoder;
private Location mylocation;
private double Latitude;
private double Lontitude;
private LocationManager locationManager;
public Getaddress() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
mylocation = locationManager.getLastKnownLocation(provider);
Boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.w("isGPSEnabled",isGPSEnabled.toString());
}
public void excute()
{
Latitude = mylocation.getLatitude();
Lontitude = mylocation.getLongitude();
Toast.makeText(SecondActivity.this, "Latitude"+Double.toString(Latitude),Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location)
{
mylocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Xml File :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/str_tv_location"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_location"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_longitude"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Java file:
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#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
}
}
Permission :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
At first: you need GPS available space.
Secondly: your location is always null, because your space for GRP LOCATION not available. You need to check if GPS working or not
onLocationChanged method work every time when your location changed.
public class GPSTracker implements LocationListener {
public GPSTracker(Context con){
LocationManager lm = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// do something here...
//location.getLatitude();
//location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Android - Update Location every x minutes

I'm pretty new to android, and this is my first post here, so please be kind! :-)
I'm trying to create a service which runs in the background and does a location update every x minutes. To run it every x minutes I'm using the AlarmManager, as described here: Alarm Manager Example
Here's what I've got:
package com.example.service1;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
public class Scheduler extends BroadcastReceiver{
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
//Code which is executed every X seconds/minutes
getLocation(context);
//End of Code
wl.release();
}
public void setScheduler(Context context) {
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Scheduler.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 20, pi);
}
//Method to get the Location
public void getLocation(Context context) {
Log.e("null","getLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e(null, "location change");
makeUseOfLocation(location);
}
#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
}
};
}
//Method to work with the location Data; Instance of Point is created
public void makeUseOfLocation(Location location) {
Log.e(null,"makeuse");
Log.e(null,location.getLatitude() + "");
}
}
getLocation() is called every 20 seconds, but then it never runs onLocationChanged() (I use the EmulatorControl in Eclipse to change the location).
I had the same problem before when I used the ScheduledExecutorService instead of the AlarmManager.
Can anyone help me?
Looking at your code I never see the call to locationManager.requestLocationUpdates() with your listener as an argument.
This means that your listener is never registered with the location manager, and therefore does not get called.
You probably only want to register one listener, instead of registering a new one every time.
Try this..
protected void updateNotification() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener {
public void onLocationChanged(Location location){
if(location!=null){
if(location.hasAccuracy()){
dumpLocation(location);
}else{
dumpLocation(location);
}
}
}
public void onProviderDisabled(String provider){
Log.v("Loc Update","\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider){
Log.v("Loc Update","\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras){
Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
+ status + ", extras=" + extras);
}

Cant get a location on Android smartphone

I am trying to get a location (latitude, longitude) on my Android smartphone (HTC Desire HD), using Wifi-network and GPS.
This is the code I use, only I keep getting "Location not available"
Iam working with Eclipse IDE.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import com.example.shortsproject.R;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class LocationGetter extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.locationtext);
longitudeField = (TextView) findViewById(R.id.locationtext2);
// 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);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Can someone help me with this?

How to collect location data every 10 seconds in Android

I wrote a GPSDataCollectService to collect location data every 10 seconds, but it did not report location in my HTC mobile phone, any wrong? could anyone help me?
package com.android.example;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSDataCollectorService extends Service {
private static final String TAG = GPSDataCollectorService.class
.getSimpleName();
LocationManager locationManager;
LocationListener gpsLocationListener;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private Timer timer;
private TimerTask collectTask = new TimerTask() {
#Override
public void run() {
Log.i(TAG, "Timer task doing work: "
+ Calendar.getInstance().getTimeInMillis());
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gpsLocationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 10 * 1000L, 0,
gpsLocationListener);
}
};
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
timer = new Timer("GPSDataCollectorTimer");
timer.schedule(collectTask, 1000L, 10 * 1000L);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
locationManager.removeUpdates(gpsLocationListener);
timer.cancel();
timer = null;
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: " + location.toString());
locationManager.removeUpdates(gpsLocationListener);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged: " + status);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
If your location is changed every 10 sec then only your LocationManager will track the new location. Otherwise it will use the same last known location.
Instead of using a LocationListener, you may want to use a Timer, within the TimerTask, maybe you can do something like this:
LocationManager lm = yourActivityReference.getSystemService(Context.LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(),true);
Location loc = lm.getLastKnownLocation (provider);
I haven't checked it, but if I do I will let know...
Regards.
EDIt: Let me try again with the "classic" approach.
public class GPSDataCollectorService extends Service {
private static final String TAG = GPSDataCollectorService.class
.getSimpleName();
LocationManager locationManager;
LocationListener gpsLocationListener;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gpsLocationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000L, 0, gpsLocationListener);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
locationManager.removeUpdates(gpsLocationListener);
}
private class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: " + location.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged: " + status);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
I don't think you need any Timer, since the Location updates will call your listener asynchronally and you can set the timeout. I haven't played much with GPS in Android, but there must be plenty of examples out there.
The location update interval can be controlled using the minTime parameter. The elapsed time between location updates will never be less than minTime, although it can be more depending on the Location Provider implementation
Use
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20 * 1000, 0, this);
more details refer Location Manager

Categories

Resources