Friday, September 2, 2011

Acquiring GPS location fix



GPS has opened a Pandora's box for mobile developer. There has been a huge influx of such application ranging from tracking apps to location based social networking apps.

Many of today's applications require us to get a GPS fix on the location of the device when the application is being used.

Therefore without further ado lets get into some coding.
The following snippet of codes employ a service and a broadcast receiver to get onto a location fix. It gets the most recent fix on the location and then closes the GPS updates as soon as it gets a fix.

public class FindGPSActivity extends Activity{

Intent myGpsService;
MainGpsReciever gpsReciever;
final String GPS_FILTER = "MyGPSLocation";  

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.textlayout);
                initGpsListeners()
}



- initGpsListeners method initializes the necessary services and the recievers. 

private void initGpsListeners() {
           
            myGpsService = new Intent(this, GpsService.class);
            startService(myGpsService);
            String GPS_FILTER = getResources().getString(GPS_FILTER);
            IntentFilter mainFilter = new IntentFilter(GPS_FILTER);
            gpsReciever = new MainGpsReciever();
            registerReceiver(gpsReciever, mainFilter);
           
      }

- this is where i get my location data which i can further use in my activity.
This receiver is called from within the service which is actually looking for a GPS location. A GPS location fix is an unreliable bit of information and we cannot be sure when we might get it. it can range anywhere from 5 seconds to 5 minutes or if you are inside a huge structure like a building you might never get it unless you come out. Therefore we use a service because we do not want our location finder to be garbage collected by android.


private class MainGpsReciever extends BroadcastReceiver {

             public void onReceive(Context arg0, Intent calledIntent) {
                       
                   Constants.GPSLatitude = calledIntent.getDoubleExtra("latitude", -1);
                   Constants.GPSLongitude = calledIntent.getDoubleExtra("longitude", -1);
                   Constants.GPSSpeed = calledIntent.getFloatExtra("speed", -1);
                       
                   Log.i("GPS Demo", "Lat & Long --- "+Constants.GPSLatitude+"--"+Constants.GPSLongitude);
                   Log.i("GPS Demo", Speed --- "+Constants.GPSSpeed);
//               
                                         
             }
       }
}

This is the service class in its entirety. 

public class GpsService extends Service {

      String GPS_FILTER = "";
      Thread triggerService;
      LocationManager lm;
      GpsListener gpsLocationListener;
      boolean isRunning = true;
     
      @Override
      public void onCreate() {
           
            // TODO Auto-generated method stub
            super.onCreate();
            GPS_FILTER = “MyGPSLocation”;
           
      }
     
      @Override
      public void onStart(Intent intent, int startId) {
            // TODO Auto-generated method stub
            super.onStart(intent, startId);          
            triggerService = new Thread(new Runnable(){
                  public void run(){
                        try{
                              Looper.prepare();//Initialize the current thread as a looper.
                              lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                              gpsLocationListener = new GpsListener();
                              long minTime = 30000; // 5 sec...
                              float minDistance = 10;
                              lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,
                                          minDistance, gpsLocationListener);
                              Looper.loop();
                        }catch(Exception ex){
                              System.out.println("Exception in triggerService Thread -- "+ex);
                        }
                  }
            }, "myLocationThread");
            triggerService.start();
      }
     
      @Override
      public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            removeGpsListener();
      }
     
      @Override
      public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
      }
     
      private void removeGpsListener(){
            try{
                  lm.removeUpdates(gpsLocationListener);
            }
            catch(Exception ex){
                  System.out.println("Exception in GPSService --- "+ex);
            }
      }
     
      class GpsListener implements LocationListener{

            public void onLocationChanged(Location location) {
                  // TODO Auto-generated method stub
                  double latitude = location.getLatitude();
                  double longitude = location.getLongitude();
                  float speed = location.getSpeed();
                  Intent filterRes = new Intent(GPS_FILTER);
                  filterRes.putExtra("latitude", latitude);
                  filterRes.putExtra("longitude", longitude);
                  filterRes.putExtra("speed", speed);
                  sendBroadcast(filterRes);
            }

            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
                 
            }

      }

}

13 comments:

  1. How can you post such things publically?

    ReplyDelete
    Replies
    1. and why do you say so? why can't such post be public?

      Delete
    2. yeah, it is a knowledge sharing, it is very good

      Delete
  2. hello :)
    how can i get the bus postion every 30 second and display it on a map.
    think you in advance :):)

    ReplyDelete
  3. hi.. i am trying to integrate this code in my application, but unfortunately i am not able to do so..
    Can you please forward me an sample application so that i can go through the minute details of it at sumit.bhartia26@gmail.com

    Thanks
    sumit

    ReplyDelete
  4. Hi Sumit,
    Can you tell me what exactly is the problem you are facing. I hope you've included the necessary permissions (ACCESS_FINE_LOCATION and INTERNET).

    ReplyDelete
  5. Yup I have done that..
    No output is displayed on this screen
    i have used two classes 1 that extends activity which calls
    startService(new Intent(this, GpsService.class));

    and 2nd GpsService does not returns any value, I have just Toasted a text inside run method it executes only once..my point is run methrd is not called again after 5seconds.. please help

    ReplyDelete
  6. I only want to fetch my latitude and longitude after 1 hours duration and send that value in my db.. This should in background.

    ReplyDelete
  7. Sir Umesh. im currently creating a application for my school project and this codes really helped me though i really need guidance and advice can you send me an Email carpio.janmichael@gmail.com i would really appreciate your help sir. Thanks

    ReplyDelete
  8. Dear Umesh,I really appreciate your code because I see that it could more help me in my project but I am still unable to manipulate it. Please could you help me by share an example complete code that could lead me to develop mine? Thanks and thanks so much

    ReplyDelete
  9. i want to create baground servicees for android to get .user location,sms,call logs, contacts,on my mobile

    ReplyDelete
  10. Constants.GPSLatitude error shows in these lines, can i know how to clear

    ReplyDelete
  11. Use this diet hack to drop 2 lb of fat in just 8 hours

    Over 160000 women and men are hacking their diet with a easy and secret "liquids hack" to burn 2 lbs every night as they sleep.

    It's simple and it works with everybody.

    Here's how you can do it yourself:

    1) Go grab a glass and fill it up half glass

    2) Now do this weight losing HACK

    and you'll become 2 lbs lighter the very next day!

    ReplyDelete