Current Location Latitude Longitude Android Studio Tutorial

It is necessary to find current location android studio latitude longitude programmatically when you are developing location-based applications.

For example, if you want to find restaurants near by you, you need your current gps location latitude and longitude. In current GPS location android example tutorial, you will learn to get current latitude and longitude of Android device.

We will use Google’s FusedLocationAPI for getting current location latitude longitude. Following is the output of current GPS location android example tutorial programmatically:

 

How to get maximum benefit from Current Location Android tutorial

To get most of this current GPS location android studio example, follow  these steps:
  • We strongly recommend you to download the source code and then run in your android studio.
  • If you have a working code already in your hand, then you will quickly grasp all the words in the tutorials.
  • Working code in the android studio will allow you to easily understand the project structure and where to put required images, files, resources and where to create new files.
  • When you are going through the whole example, implement it in your demo and then also check in working source code how it is implemented.
  • The tutorial is theory and source code is practical, and in the end, you need to have right practical so learn it from theory as well as practical.

Download Source Code For Current Location Android

Step 1.  Create a new project in Android Studio.

Make a fresh new project in Android Studio.

Step 2. Update build.gradle(Module:app) file

Add below source code in build.gradle(Module:app)

Step 3.  Implement necessary interfaces

These interfaces are required.

Step 4. Declare instances:

Necessary declare statements.

Step 5.  Put following in onCreate() method

Update your onCreate() method as per following:

Step 6. Override necessary methods.

You are required to override following methods.

Step 7.  Last but not least, put required permissions in AndroidManifest.xml

Below two permissions are must to get desired results.

If you are targeting marshmallow and after versions (targetSdkVersion >=23) then you have to check for run-time permissions.

You can learn about this topic here at our separate example.

Now full source code:

AndroidManifest.xml

build.gradle(Module:app)

activity_main.xml

MainActivity.java

In above class, there is a method

This method is used to check whether location service is on or off in your phone. If off, then it will pop up one dialog, which will take the user to settings to enable location service.

Kotlin Version

Java Version of this tutorial is present at : Android Current Location Kotlin

How to get exact Android example while searching in Google

When you search for any Android example in Google, always add “Android Studio programmatically” at the end of your query.

Why add studio?

If you search with the query “Facebook login in Android” then Google will also show you examples which are developed with Eclipse. Examples made with Eclipse are useless because it is officially deprecated.

Put studio in your query, and it becomes “Facebook login in Android Studio.

Why add programmatically

If your query is “Scan barcode in Android” then Google will show you some app URLs to play store which helps the user to scan the barcode.

Google doesn’t know that you are looking for source code to implement scan in Android.

Now if your query is “Scan barcode in Android Studio programmatically” then google will show you examples which are developed with android studio and will also remove app URLs of play store.

Thus adding Android Studio programmatically will save your lot of time in searching right tutorial.
That’s all for getting current GPS location android tutorial. Now if you run this demo, you will get output latitude and longitude as shown in the video.

 

Other charming tutorials you will definitely like

Cheers and happy coding!

Hardik Parsania

I am mobile app developer. I am always passionate about solving complex and real world problems.I have developed many apps with great interest and superior logical skills.

You may also like...

71 Responses

  1. Android learner says:

    Hello,
    Latest version for google play service is “9.4.0”, can I use this version instead of “9.0.2”, which is mentioned on the above blog post?

  2. KRH says:

    Hey!
    First off, great tutorial!
    Secondly, my questions:
    I am new to android, but I am quite good in java. I work in android studio 1.5(do I need to update it?). I wonder if this code can be used as is for broadcasting the location to other devices with the same app, and then somehow plot the coordinates on google maps, such that a nearby person can be notified of the position of another person?

    Or do I have to do a lot of tweaks in this code?

    thnx!

    • Hardik Parsania says:

      You can implement this code on Android Studio 1.5 (No need to update). This code will give you latitude and longitude of your device, for broadcasting these latlong you can send them to server and from server all other devices can get them and then you can show it on google map. So this tutorial will give you only coordinates of your device, for your whole purpose, you have to do lot of tweaks as you guessed.
      Thanks 🙂

  3. Android learner says:

    Thank you very much for amazing tutorial, it’s nice and easy to understand.

  4. John Colley says:

    Beautiful code my friend, it helped me a lot.

  5. saiteja says:

    Hello Hardik Parsania,

    I’m writing a simple app that needs to set the current GPS coordinates from let’s say point A, then travel to another point B and have it detect the coordinates at point B. I am able to get point A coordinates no problem. I’m just not getting it to detect the coordinates at point B, it reads the same coordinates as the ones at point A. I’ve got the app installed on my phone, and I am driving a mile between points. My manifest file includes every possible permission for location.

    • Hardik Parsania says:

      Hello,
      It may happen that when you are at point A, app is giving you coordinates from wifi and at point no wifi is there. You can try by switching off your wifi and use only mobile data for testing.
      Also try by opening google map at both points and see if you are getting correct coordinates or not.

  6. saiteja says:

    Hello Hardik Parsania,

    I am writing a simple GPS location application in android studio. The current longitude latitude values are stored in SQL server database through web service.GPS Application is Refreshed every 5 secs and SQL server database is ping every 5 sec correctly. but SQL server is ping every 5 secs up to 40 mins only.After the values are not stored in database.Again App is opened and minimized the values are stored in SQL server database 40 mins or 1 Hour.my net speed is also good.how to solve this problem.My Agenda is daily once app is opened and minimized the values are stored up to next 24 hours in every 5 secs in SQL server Database

  7. Pulkit Shah says:

    Hi,
    I am trying to update GPS coordinates even when the screen is off? Will the above solution mentioned by you help me achieve so ?

    • Hardik Parsania says:

      If you want to achieve coordinates when screen is off, then you should fetch coordinates in to service class(Background service) instead of activity.

  8. Keeley Fenton says:

    Hello,
    Very informative articles and good description overall. Nice work !

  9. August says:

    Whats up are using WordPress for your site platform?
    I’m new to the blog world but I’m trying to get started and set up my own. Do you
    require any coding expertise to make your own blog? Any help would be greatly appreciated!

  10. Pokhraj Chaudhuri says:

    I ve used your code, but following line is returning null only.

    mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    • Hardik Parsania says:

      What is the brand name and model of your android device?

      • Pokhraj Chaudhuri says:

        Trying with Nexus 5X_API25 Emulator.

        Please find the build.gradle also for your reference.

        apply plugin: ‘com.android.application’

        android {
        compileSdkVersion 25
        buildToolsVersion ‘25.0.0’

        defaultConfig {
        applicationId “com.exampledemo.parsaniahardik.gpsdemocode”
        minSdkVersion 25
        targetSdkVersion 25
        versionCode 1
        versionName “1.0”
        }
        buildTypes {
        release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
        }
        }
        }

        dependencies {
        compile fileTree(dir: ‘libs’, include: [‘*.jar’])
        testCompile ‘junit:junit:4.12’
        compile ‘com.android.support:appcompat-v7:25.2.0’
        compile ‘com.google.android.gms:play-services-maps:10.2.0’
        compile ‘com.google.android.gms:play-services-location:10.2.0’
        compile ‘com.google.android.gms:play-services-gcm:10.2.0’
        }

  11. Blake says:

    Hello. Good writing technique and well experience. Can you publish tutotials about SQlite for Android?

  12. Jin Ming says:

    Thanks for your great tutorial!!!
    it helped me a lot.

    I have one question.
    I am developing app now, I have to send location info to server in every 1 min on background.

    can you send me sample about this?

    • Hardik Parsania says:

      Thanks for your review. You can call web service every 1 min to send location info to server. You can use handler or thread for calling particular code snippet every 1 minute.

      You can use below code to send info every 1 second

      new Handler().postDelayed(new Runnable() {
      public void run() {
      requestHttp();
      }
      }, 1000);

      Visit link: Send info every 1 second

      • Jin Ming says:

        Thank you very much.
        But I didn’t understand fully.
        Because I am beginner on app development.
        so can you post full code step by step, please?

  13. Bob Marsh says:

    Thank you very much! Nice and easy…Keep posting this kinds of tutorials, it really helps.

  14. Rachana says:

    When I tried the code I’m not able to get the latitude and longitude. It is just showing blank like this
    Latitude:
    Longitude:

  15. Andreas says:

    I was studying some off youhr articles on this site and I conceive this web site is very informative!
    Retain posting.

  16. manicure says:

    Write more, thats all I have to say. Literally, it seems as though
    you relied on the video to make your point. You clearly know what youre talking about, why waste your intelligence on just
    posting videos to your weblog when you could be giving
    us something enlightening to read?

  17. priyanka says:

    hai,
    ihave some trouble, when i run this project i can see my lat and long.
    and there is no error message.
    please someone help me

    • priyanka says:

      hai,
      ihave some trouble, when i run this project i cant
      see my lat and long.
      and there is no error message.
      please someone help me

  18. Daniel says:

    Thank you very much!
    You helped me alot!
    I have one question, how do I get the current location just by clicked a button? I mean I don’t want to put the interval.
    So, which part do I need to change?

    Thank you for your attention!
    Appreciate it!

  19. Riho says:

    Hi. Code is working perfectly and send information to my server but if i copy that .java and .xml to the other project then its not starting. It showing just plain latitude and longitude labels but not values. Is there anything i can do to forse it?

  20. Priya says:

    Very nice blog! But I have a question.
    How to ask for runtime permission in this example?

  21. Kunal says:

    hey buddy..
    i tried your code but after successful installation of apk on my phone ..
    its showing a toast “Location not detected”
    please help
    also i turned my gps on.

  22. Kunal says:

    Hey buddy..
    your code was successfully installed but its showing only a toast that “location not detected”
    please help.
    i am using
    minSdkVersion 21
    targetSdkVersion 25
    also in Eveent log its showing :
    RuntimeException: java.util.zip.ZipException: incorrect header check

    • Hardik Parsania says:

      your target version is upper than marshmallow so have you check for runtime permissions?

      • Kunal says:

        Hey,
        i changed targetSdkVersion but its not showing any output.
        Nothing is happening.
        Please Help

        • Hardik Parsania says:

          Try by opening Google map first. If google map is showing your current location then your app should also show current location. I had this problem in lenovo A600 model.

  23. priya says:

    Use Shared Preferences to read and store values (1,2,3,4,5,6,7,8) 1+2 =3 every 5 sec.How to solve this example

    • Krishnan says:

      Try this..will help you

      private int counter = 0;
      private int total = 30; // the total number
      //…
      //when you want to start the counting start the thread bellow.
      new Thread(new Runnable() {

      public void run() {
      while (counter < total) {
      try {
      Thread.sleep(500);
      } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      t.post(new Runnable() {

      public void run() {
      t.setText("" + counter);

      }

      });
      counter++;
      }

      }

      }).start();

  24. Krishnan says:

    how can we get current location by signal provider(not using gps)

    • Krishnan says:

      Try this..will help you

      private int counter = 0;
      private int total = 30; // the total number
      //…
      //when you want to start the counting start the thread bellow.
      new Thread(new Runnable() {

      public void run() {
      while (counter < total) {
      try {
      Thread.sleep(500);
      } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      t.post(new Runnable() {

      public void run() {
      t.setText("" + counter);

      }

      });
      counter++;
      }

      }

      }).start();

  25. Bert says:

    How can i put in on gmaps sir ? please help me

  26. shubha says:

    Hi!
    The function onLocationChanged() is not getting called. I amrunning it on Honor6x. Plese help.
    this is gradle file-
    android {
    compileSdkVersion 26
    defaultConfig {
    applicationId “com.example.dell.finallocation”
    minSdkVersion 18
    targetSdkVersion 26
    versionCode 1
    versionName “1.0”
    testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”
    }
    buildTypes {
    release {
    minifyEnabled false
    proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’
    }
    }
    }

    dependencies {
    implementation fileTree(dir: ‘libs’, include: [‘*.jar’])
    implementation ‘com.android.support:appcompat-v7:26.1.0’
    implementation ‘com.android.support.constraint:constraint-layout:1.0.2’
    testImplementation ‘junit:junit:4.12’
    androidTestImplementation ‘com.android.support.test:runner:1.0.1’
    androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.1’
    compile ‘com.google.android.gms:play-services:11.8.0’
    }

    • Hardik Parsania says:

      Download working source code of tutorial and check if it works or not.

      • Shubha says:

        Yeah it’s working on the source code. I actually have want to combine this code with another code. That time when I copy the above code into a new project the function is not getting called. Please help. Thanks in advance

        • Hardik Parsania says:

          Then it must be error when you combine both codes. Check closely everything again. If possible again do it from scratch.

  27. Indranil says:

    Thank you sir!
    Best tutorial!

  28. Mahnoor says:

    Hello
    My app is crashing. An i am running it on my real device. and my android version is 2.3.3 Please help me to find location and send in a text.
    Thanks

  29. Sanjay says:

    Hello ,
    I check this document and implement my android project.
    but i have run my apk but latitude longitude is display has null. (0).
    and my application is crashes.
    ?

Leave a Reply

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