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.
This entry was posted in Android, Background Services, GPS, Location aware apps, Location Services on by .

About Hiren Dave

Hiren Dave is a software engineer, blogger and consultant with over 9 years of professional experience. He writes code in number of languages. Hiren has a passion for developing web apps, mobile apps and writing books and blog articles about programming. He has a solid experience of startups as he manages products for few startups. He is also passionate about researching and learning new technologies and trends. He has also authored a book Instant Sencha Touch, published by Packt and creator of Video Course "Beginning Laravel" for Packt

Leave a Reply

Your email address will not be published. Required fields are marked *