Thursday, December 25, 2014

Android Application Get GPS ON/OFF Notification

Hello,

Recently in one of my project we had location service which is used send locations to server and draw a path on map of travel. As we know to get accurate location from the device we need GPS turned on and we wanted to track event and log event on server if user turn off GPS purposefully. In this blog I am going to explain how to do this.

First of all you need to add following permissions to your android manifest file so that your app can access users location.

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />

Now create an instance of location manager which receives location updates from GPS. 

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

As you can see in above code we are creating location manager instance and set it to receive updates from GPS. Now we will add GPS status listener.

locationManager.addGpsStatusListener(new android.location.GpsStatus.Listener()
  {
    public void onGpsStatusChanged(int event)
    {
        switch(event)
        {
        case android.location.GpsStatus.GPS_EVENT_STARTED:
            Log.v("gps","gps is on");
            break;
        case android.location.GpsStatus.GPS_EVENT_STOPPED:
            Log.v("gps","gps is off");
            break;
        }
    }
});

As you can see in above code we have added GPS status listener to location manager. When either GPS is turned on or off onGpsStatusChanged event callback will be called and you can check case as shown in above code and do the stuff in there.

Hope this helps you.

No comments:

Post a Comment