Working with Location(GPS) in Android

Android Location APIs are used in a wide variety of apps for different purposes such as finding user location, notifying when a user has left a general area (Geofencing), and help interpret user activity (walking, running, driving, etc).

However, Android Location APIs are not the only means of acquiring user location. The following will give examples of how to use Android’s LocationManager and other common location libraries.

Fused location API

Example Using Activity with LocationRequest

Example Using Service with PendingIntent and BroadcastReceiver.

ExampleActivity

Recommended reading: LocalBroadcastManager

LocationService

NOTE: Don’t forget to register this service in the Manifest!

LocationReceiver

NOTE: Don’t forget to register this receiver in the Manifest!

Get Address From Location using Geocoder

After you got the Location object from FusedAPI, you can easily acquire Address information from that object.

Requesting location updates using LocationManager

As always, you need to make sure you have the required permissions.

Requesting location updates on a separate thread using LocationManager

As always, you need to make sure you have the required permissions.

Getting location updates in a BroadcastReceiver

First, create a BroadcastReceiver class to handle the incoming Location updates:

Then when you connect to the GoogleApiClient in the onConnected callback:

Don’t forget to remove the location update intent in the appropriate lifecycle callback:

Register geofence

I have created GeoFenceObserversationService singleton class.

GeoFenceObserversationService.java:

AppConstant:

Where I started Service? From Application class

How I registered Geofences?

 

Leave a Reply

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

2 × 1 =

Comment moderation is enabled. Your comment may take some time to appear.