problem with android GPS provider: too many updates - android

Although I set minTime to 10 seconds in the requestLocatioupdate method I still get new location in less than one second.
public class GpsActivity extends Activity {
LocationManager mLocationManager;
TextView mTextView;
int count;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
count = 0;
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0,mGpsLocationListener);
}
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg){
switch(msg.what){
case 1:
mTextView.setText("new location count:"+count);
}
}
};
LocationListener mGpsLocationListener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
count++;
mHandler.sendEmptyMessage(1);
}
#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
}
};
}
My program is written for android 2.2
Any idea?
Thanks in advance.

you can set a distance .if not solve,youcan see :minTime the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
minDistance the minimum distance interval for notifications, in meters
so i think the time not correct,if you hope update 10s,i think you should use Time andTimeTask,or handler. or you can look http://androidforums.com/developer-101/107085-proper-provider-parameter-requestlocationupdates.html

Related

Location updates using Android GPS?

I created a class to use the LocationListener but I am getting classCastException when I request for location updates
This is my class code
public class Loc implements
LocationListener, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
// A request to connect to Location Services
private LocationRequest mLocationRequest;
// Stores the current instantiation of the location client in this object
private LocationClient mLocationClient;
/*
* Note if updates have been turned on. Starts out as "false"; is set to
* "true" in the method handleRequestSuccess of LocationUpdateReceiver.
*/
boolean mUpdatesRequested = false;
// Milliseconds per second
public static final int MILLISECONDS_PER_SECOND = 1000;
// The update interval
public static final int UPDATE_INTERVAL_IN_SECONDS = 10;
// A fast interval ceiling
public static final int FAST_CEILING_IN_SECONDS = 1;
// Update interval in milliseconds
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// A fast ceiling of update intervals, used when the app is visible
public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND
* FAST_CEILING_IN_SECONDS;
Location currentLocation ;
LocationListener locListener;
Context x;
public Loc(Context con) {
// Create a new global location parameters object
this.x=con;
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(con, this, this);
}
public void stop() { // If the client is connected
if (mLocationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
mLocationClient.disconnect();
}
public void start() {
mLocationClient.connect();
}
public void startUpdates() {
mUpdatesRequested = true;
startPeriodicUpdates();
}
public Location getLocation() {
// Get the current location
currentLocation = mLocationClient.getLastLocation();
// Display the current location in the UI
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
return currentLocation;
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
Log.e("lat log", "" + currentLocation.getLatitude() + " , "
+ currentLocation.getLongitude());
}
#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
}
private void stopPeriodicUpdates() {
mLocationClient
.removeLocationUpdates((com.google.android.gms.location.LocationListener) this);
}
private void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
}
}
This is my activity code
public class MainActivity1 extends Activity {
Loc l;
TextView t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
t=(TextView)findViewById(R.id.txt);
l = new Loc(getApplicationContext());
l.start();
}
public void getLoc(View v) {
// l.getLocation();
l.startUpdates();
}
I am getting my lat and long perfectly fine.
But my issue is with for location updates
I get this error
Caused by: java.lang.ClassCastException: com.example.gps.Loc cannot be cast to com.google.android.gms.location.LocationListener
I do get that I cannot pass LocationListener like this
mLocationClient.requestLocationUpdates(mLocationRequest,(com.google.android.gms.location.LocationListener) this);
But how should I exactly pass it??
Only needed to add the interface
com.google.android.gms.location.LocationListener
like this.
public class Loc implements
GooglePlayServicesClient.ConnectionCallbacks
,GooglePlayServicesClient.OnConnectionFailedListener
,com.google.android.gms.location.LocationListener {
//...
}

Remove Location Listener

I want after open dialog and click on location button, detect user's location and show user's location and then user dismiss dialog, location listener removes and not get location from onLocationChanged, I try used locationManager.removeUpdate(locListener)on override dismiss but not any chance and location after dismiss again shows! why? How can i detect user's location after show dialog and after detect location, location listener remove? Thanks
EDIT:
public class DialogTest extends Dialog implements
android.view.View.OnClickListener {
Context context;
LocationManager locationManager;
LocationListener locationListener;
Location location;
public DialogTest(Context context) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.context = context;
setContentView(R.layout.profile_dialog);
getWindow().setBackgroundDrawableResource(R.drawable.background_dialog);
firstAccessLocation=true;
setCancelable(true);
initialize();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
findAddress();
}
private void findAddress() {
// if (gpsCheckBox.isChecked()) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// }
}
private void stopTracking(){
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
#Override
public void dismiss() {
// TODO Auto-generated method stub
stopTracking();
gpsTurnOff();
super.dismiss();
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(location!=null)
Log.e("location", location.getLatitude()+"");
location = loc;
if (location != null&& firstAccessLocation) {
setAddress(location.getLatitude(), location.getLongitude());
firstAccessLocation=false;
}
Toast.makeText(context, "changed", Toast.LENGTH_LONG).show();
Log.e("location", "changed");
}
#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
}
}
}
In new code you should use LocationClient rather then LocationManager. It's more efficient in getting the location with minimal energy(battery drain) with greater accuracy. Look here LocationClient vs LocationManager. With LocationClient established you can call getLastLocation() which provide you last location and doesn't start cyclic location updates.
If you want to stick with LocationManager use requestSingleUpdate (String provider, LocationListener listener, Looper looper) method to get only one newest location from it.

Changing the GPS coordinates with out moving anywhere

**i have used the gps coordinates for calculating the distance using location updates. but problem is that if i am standing at same place the coordinates changes and distance is changing with out moving anywhere. I want to change it only when I have moved min 10 mtrs.
## Activity ##
//Activity
public TextView dist;
public double lati1,lati2,longi1,longi2;
private boolean run1 = false;
private Handler handler1 = new Handler();
private Runnable task1 = new Runnable() {
public void run() {
// TODO Auto-generated method stub
if (run1) {
handler1.postDelayed(this,1000);
if(lati1==0.0&&longi1==0.0)
{
lati1=Service1.lat1;
longi1=Service1.lon1;
}
lati2=Service1.lat1;
longi2=Service1.lon1;
double R=63710;
double dLat=Math.toRadians(lati2-lati1);
double dLon=Math.toRadians(longi2-longi1);
double a=Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.cos(Math.toRadians(lati1))*Math.cos(Math.toRadians(lati2))*
Math.sin(dLon/2)*Math.sin(dLon/2);
double c=2*Math.asin(Math.sqrt(a));
double d=R*c;
d=(double)(Math.round(d*100.00))/1000.00;
distance+=d;
String s=String.format("%.2f", distance);
dist.setText(s);
lati1 = lati2;
longi1 = longi2;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dist=(TextView)findViewById(R.id.distancetextView);
Intent i = new Intent(context, Service1.class);
startService(i);
}
## Service ##
//Service
private double new_latitude = 0.0;
private double new_longitude = 0.0;
public static double lat1=0.0,lon1=0.0;
LocationManager locationManager = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
locationManager.removeUpdates(this);
super.onDestroy();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
lat1=new_latitude;
lon1=new_longitude;
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}****
I should see the code you are writing. But without it I can say that there is a function, that you call, and it give you location update each X milliseconds. Or you can get the latest updated location, again, I should see your code.
UPDATE:
change this line
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 10.0f, this);
You'll receive updates after moving 10m.
The second parameter is time in millisecond, the third is minimum distance. But it doesn't mean you'll get update exactly at the requested time or requested distance, but rather about it.
//Public or class variable of previous speed initialised on class.
// float previousSpeed;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
float speed = location.getSpeed();
//You could also use location.hasSpeed(), which is a boolean, but it almost
//always returns True
if(speed > DESIRED_LIMIT && previousSpeed > DESIRED_LIMIT){
lat1=new_latitude;
lon1=new_longitude;
}
previousSpeed = speed;
}
So something like that. That condition is not very well optimized or designed. But that is how you get GPS speed from location object. You can tweak the speed limit or the whole condition to get the best results. Or add even more history of speed to monitor.
You can use the location spoofer application from the android market and specify the duration of spoofing the location and also the distance

android locationlistener carries on calling onlocationChanged after unregistering listener

I've an app that gets the user's location. I've registered the locationManager and listener in oncreate(). I've requested and removed updates in onResume() and onPause() respectively. The app finds the location and calls the getTime() on the loc object of onLocationChanged, this is to get an external time and then later compare to system time. This time is set in an applicationObject so that it's available app-wide. Everything works fine and i toast the time to the user from the applicationObject time setter method.
What i'm finding is that when i have found the time by getting a fix on the user's location, and i move to the next activity, the app continues to get the time for another 20 secs and sometimes more.
How can this be when i have unregistered the locaction listener in the first activity's onPause() method?
#Override
protected void onPause() {
mlocManager.removeUpdates(mlocListener);
super.onPause();
}
#Override
protected void onResume() {
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
super.onResume();
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
Log.e(TAG, "external time = " + loc.getTime());
DateTime dt = new DateTime(loc.getTime());
DateTimeFormatter df3 = DateTimeFormat.forPattern("yyyy-MM-dd H:mm:ss.SSS");
String formattedNowTime3 = df3.print(dt);
Log.e(TAG, "formatted ext time = " + formattedNowTime3);
nfcscannerapplication.setExternalTime(dt);
}
#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
}
}//end of MyLocationListener
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
.
The onPause() may be called only after the new activity has started.
If you only want a single onLocationChange(), you can use requestSingleUpdate() and your problem is gone.
Regards.
Set mlocListener to null just after removeUpdates();

whats wrong with this code?

I am trying to get the current GPS location of the mobile. I am using emulator I have given the position to the emulator using DDMS but I am getting nothing in the screen also I don't get any errors.
public class getitright extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager lm=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new LocationListener(){
public void onLocationChanged(Location l)
{
go(l);
}
#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
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
public void go(Location l){
TextView tv=(TextView)findViewById(R.id.tv1);
tv.setText(""+l.getLatitude());
}
}
Put some log messages in for a start.
But secondly. You shouldn't declare your TextView or your LocationListener to be local variables like that. Those should both be member variables. By declaring your locationlistener like that, you lose your reference to it. That could be the problem, but if it's not, you're still unable to remove the locationlistener from the manager because you don't have a reference.
Are you sure your textview is even showing at all? Try setting it to something static in onCreate just to make sure
Also add an #Override statement to
public void onLocationChanged(Location l)
{
go(l);
}
Just to be 100% sure you're actually overriding the method.

Categories

Resources