All CategoriesAndroid App Development

How to Create Location-Based Apps in Android

As we have seen, there are many options to get the current location like Android GPS, LocationManager, etc. by using older Android APIs. Now Google introduces us with the new API, i.e., Fused Location Provider API using Google Play Services in Android to get the current Location or Lattitude and Longitude.
This API connects with the GoogleAPIClient and provides us the most accurate location of the user or device. It automatically starts the Location Provider and tracks the current position of the device.
Nowadays, almost all of the applications use location API integration. By using this API, we can easily retrieve a user’s last location. We can also detect a user’s activity like walking, running, etc.
This is a very powerful API and has a high-level framework which can also take care of power management, wherein, there is a need for high accuracy for getting user’s current location

Interface-LocationListener 

It comes from com.google.android.gms.location.LocationListener. This interface is used to receive the notification from Fused Location Provider API when a user’s location is changed.
onLocationChanged() method is overridden when we implement this interface. Inside this method, we will set the current location of the user.

Example with code

Here, we are going to create a simple example to get a user’s current location which will show the latitude and longitude with the help of Fused Location Provider API using Google Play Services in Android.

  • Create an Application LocationExampleAndroid in Android Studio with updated version.
  • Add the Google Play Services library in the build.gradle file.
  • Add the Location Permission in AndroidManifest.xml file.

Requirements for Example

activity_main.xml, MainActivity.java.
These are the main files to create this simple example. Let’s do it one by one.

build.gradle 

Add the dependency to this file.

dependencies {
    compile "com.google.android.gms:play-services:9.8.0"
}

AndroidManifest.xml
Add the permission in this file.

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

colors.xml

Add the code here under resources.

<color name="green">#33ff9f</color>
<color name="white">#ffffff</color>

strings.xml

Add the code here.

<string name="latitude_string">Latitude now:</string>
<string name="longitude_string">Longitude now:</string>

Also, add the location icon inside a drawable folder if needed.

activity_main.xml

This is our main layout for the application. Here, we will add the TextView to show the latitude, longitude and an ImageView for location icon.

Add the code here

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Get Location Latitude and Longitude"
    android:textColor="@color/white"
    android:textSize="25dp" />
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:src="@drawable/location" />
<TextView
    android:id="@+id/tv_Latitude"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:textColor="@color/white"
    android:textSize="22dp" />
<TextView
    android:id="@+id/tv_Longitude"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="30dp"
    android:textColor="@color/white"
    android:textSize="22dp" />

MainActivity.java

This is our most important activity. As I discussed above, here we implemented the LocationListener interface, and its overridden method to show the latitude, longitude, and set other properties of Location.

Initialization

private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private TextView tv_Latitude, tv_Longitude;
private double fusedLatitude = 0.0;
private double fusedLongitude = 0.0;

Add the code in onCreate(..){..}

initializeViews();
startFusedLocation();
registerRequestUpdate(this);

inside initializeView() method we will take the reference of TextView’s.

tv_Latitude = (TextView) findViewById(R.id.tv_Latitude);
tv_Longitude = (TextView) findViewById(R.id.tv_Longitude);

Inside the startFusedLocation() method, we will connect with GoogleAPIClient and implement all methods according to the need of the application.

if (mGoogleApiClient == null) {
    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnectionSuspended(int cause) {
                }
                @Override
                public void onConnected(Bundle connectionHint) {
                }
            }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                }
            }).build();
    mGoogleApiClient.connect();
} else {
    mGoogleApiClient.connect();
}

After connecting with GoogleAPIClient, we call the method registerRequestUpdate(..). Here, we create the LocationRequest with PRIORITY_HIGH_ACCURACY. And register the Activity with location changes every second.

public void registerRequestUpdate(final LocationListener listener) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(1000);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            try {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, listener);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                if (!isGoogleApiClientConnected()) {
                    mGoogleApiClient.connect();
                }
                registerRequestUpdate(listener);
            }
        }
    }, 1000);
}
public boolean isGoogleApiClientConnected() {
    return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}

Now, add the code for location change in onLocationChanged() method of LocationListener interface.

@Override
public void onLocationChanged(Location location) {
    setFusedLatitude(location.getLatitude());
    setFusedLongitude(location.getLongitude());
    Toast.makeText(getApplicationContext(), "NEW LOCATION RECEIVED", Toast.LENGTH_LONG).show();
    tv_Latitude.setText(getString(R.string.latitude_string) +" "+ getFusedLatitude());
    tv_Longitude.setText(getString(R.string.longitude_string) +" "+ getFusedLongitude());
}
public void setFusedLatitude(double lat) {
    fusedLatitude = lat;
}
public void setFusedLongitude(double lon) {
    fusedLongitude = lon;
}
public double getFusedLatitude() {
    return fusedLatitude;
}
public double getFusedLongitude() {
    return fusedLongitude;
}

We have to disconnect the GoogleAPIClient when we stop the Activity. For this, we create stopFusedLocation() method, add the code here and call this method from onStop() method.

public void stopFusedLocation() {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.disconnect();
    }
}

Output

Download Source Code: GitHub

Conclusion

This is a simple example of how to use location-based libraries which will help us create location-based apps in Android. As I discussed above, there are many libraries to get the current location of the user or device.
In the above example, we use the FusedLocationProviderAPI which is provided by Google using the Google Play services in Android. It is a very powerful API which has a high-level framework to get the current location with high accuracy. Nowadays, as we can see, most of the applications use location awareness, such as Games, weather apps, etc.
As mentioned earlier, a functionality is also added in this API that helps detect a user’s activity even on a moving vehicle, while walking, running, etc.
So, overall this is most important API which is used to get a user’s current location. It is very popular in Android development.
Keep visiting www.acadgild.com for more updates on the technical and certification skill developments courses.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close