Skip to main content

android location service tutorial fetch users last known location

Introduction

This android tutorial is about adding Location module in the app. You have already seen that almost all the android app out there detects your current location. These apps provides services according to your current location. The services can range from sending plumber to getting food delivered in user’s location. In this Android tutorial we will learn how to get the last know location of a device (as latitude, longitude). We’ll add location module in Android app using FusedLocationProviderClient provided by latest google play service API’s .
Through Google Play Services SDK, Android has provided a new way to access user location. You can read more about the location services here. This is connection-less API. This new API does not mandate the developer to manually manage a connection to Google Play services through a GoogleApiClient. If you have already implemented location aware app using GoogleApiClient, you must already know that to access the location related services, the app first needs to connect to Google Play services asynchronously. The logic that a developer builds around it is many a times erroneous or error-prone. However, in the new LocationServices API, the connection logic is handled implicitly and automatically by Google. Thus, this makes a developer’s life earlier, code complexity is lesser and lesser error prone.
This blog is first part of location related tutorials. In this  tutorial, we will keep it very simple. We’ll just get the last known location of the device or user. It’ll retrieve the most recently available location and at times, it may be null as well in those rarest of rare cases when there is no location available or location is disabled in device. This tutorial (as a by product) will also show how we can check for user permission in android app.
So, let’s get cracking folks!!

App Screenshot

I have erased the location intentionally, so that you don’t know where I am coding from ðŸ™‚
android-user-last-known-location
android-user-last-known-location

Tech Stack

Basic Steps for implementing location aware app

Well, that’s it. Let’s get started with the development.

Create an empty project

  • Launch Android Studio and click: File –> New –> New Project…
  • A “Create New Project” dialog box will open; we’ll provide the app name and company domain. I have entered following details, you can provide the name/domain as per your choice and preference.
    • Application Name:- ItcGoogleFusedLocationSample
    • Company Domain:- iteritory.com
  • Click on Next button. In the next window, select the minimum SDK version; you can choose as per your preference. In this case, I have chosen API 16: Android 4.1 (Jelly Bean). Click Next button.
  • In the next window, select “Empty Activity“. Click Next button.
  • In the next window,  let’s keep the Activity Name and Layout Name to default. Click Finish button.
  • I’ll change the app name a bit here, traverse and open res–> values –> strings.xml. Find the line with app_name attribute. Change the value to “Last Location ”.

Prerequisite

  • Ensure that your android studio is updated to the latest and also you have latest google play service installed. Please check the below screenshot for reference. You can open the SDK manager from the studio to check the relevant details –
android-location-google-play-service
android-location-google-play-service
  • In the app level build.gradle file, add a dependency for play service –> compile ‘com.google.android.gms:play-services-location:11.0.0’. Post modification, the build.gradle file looks like –
  • Next, open the AndroidManifest.xml and followings –
    • Add a meta-data section for the google play service
    • Add user-permission section for “ACCESS_FINE_LOCATION”.  With the ACCESS_FINE_LOCATION setting is specified, the Fused Location Provider API returns location updates that are accurate to within a few feet.
  • Post modification AndroidManifest.xml looks like –

     

Build the UI

Next, we will build a very simple UI for displaying the latitude, longitude of the user’s current or last known location. This UI will be loaded with the last known device location on app startup. After putting in necessary objects, the activity_main.xml is as follows –

Develop the code

  • Now, we will start with developing the code. For the sake of simplicity, we will write all the codes in the MainActivity class itself
  • Declare required variables for holding location information and initialize them in the onCreate function –

     
  • Write functions to check if the the app has necessary permission to access location. If the permission is unavailable, request permission from user for the app. Write a function that will actually start the permission requesting dialog.

     
  • Write a function to get the current or last known location. In some situations, it’s possible that it returns null when location is not available or when the location is not enabled.

     
  • Stitching all the components together, the MainActivity class looks like –

     
  • I have provided Log statement in every step; this is to make sure we understand the workflow. When you run the app in your device from android studio, open the Logcat pen and notice how the statements are printed. That’s exactly the workflow of the app in that specific situation. For example, when I ran this app with location enabled, I got following workflow –

Github Link

The project can be downloaded from this github page.

Conclusion

In this tutorial, we learn a very simple way to get the last known location of a user. In the subsequent tutorial, we will see how to fetch the current location and how we keep getting updated location. See you soon with new learning folks. ðŸ™‚

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!