tags:

views:

136

answers:

1

Hi frinds

I am presently working on GPS. I have to start GPS periodically. I mean I want GPS to start after a particular interval, get Location value and then stop taking location updates. For this, I'm calling requestLocationUpdates( , , ) method in a timer. Then in onLocationChanged(), I stop taking location by using removeUpdates(). Then after particular interval, it again starts taking values, then when location changes, it stops, and so on.

Here is my code: TimerTask IntervelTimer = new TimerTask() { public void run() { Log.d("startLocationUpdate","startLocationUpdate"); startLocationUpdate();

                }
        };
        Timer  timer2 = new Timer();


          try{
        timer2.schedule(IntervelTimer,  1*60 * 1000, 1*60 * 1000);
          }
          catch(Exception e)
          {
              Log.e("Error",e.toString());
          }

 public void startLocationUpdate()
 {
  System.out.println("startLocationUpdate()");
  if(locationListener==null)
    {
        Looper.prepare();

             locationListener = new MyLocationListener();
      try{
      lm.requestLocationUpdates(
             LocationManager.GPS_PROVIDER, 
            0, 
             0, 
             locationListener);  
      }
      catch(Exception e)
      {
       Log.e("error",e.toString());
      }
      Looper.loop();
      Looper.myLooper().quit();
           }
 }

 private class MyLocationListener implements LocationListener 
    {
        public void onLocationChanged(Location loc) {
         System.out.println("GetLocation");
            if (loc != null) {
                         StoreGPSlocation(String.valueOf(loc.getLatitude()),String.valueOf(loc.getLongitude()));
                                stopLocationUpdate();
                            }
        }

        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
        }
    }

public void stopLocationUpdate() { LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); if (lm != null)

    {
  if (locationListener != null)

      {

     lm.removeUpdates(locationListener);
    locationListener= null;      

     }



    lm = null;

     }



 }

Now the problem is:It starts fine for the first time,when location changes it stops then starts again,but the timer stops running after that.I dont get any error or exception.I dont know where is the problem.As far as I am concirned,the problem is in timer......

What do you guys think.......????

I need Help..... urgently!!!!!!!!!!!

Thanks in Advance Nemat

A: 

I had similar problems using timers, switching to Alarms to run at set intervals has worked well for me so far...

Dave